fix(session): address restore review feedback

This commit is contained in:
imccyu
2026-08-06 03:59:01 +08:00
parent 2551b757fb
commit e89b1e612f
11 changed files with 69 additions and 36 deletions

View File

@@ -203,12 +203,18 @@ export function snapshotSessionEvent<T extends SessionEvent>(event: T): T {
return adoptSessionEvent(structuredClone(event))
}
/** Deep-freeze one acyclic object tree materialized by JSON parsing. input is stackoverflow-safe */
function freezeRestoredObject<T>(value: T): T {
Object.freeze(value)
for (const key in value) {
const child = (value as Record<string, unknown>)[key]
if (child !== null && typeof child === 'object') freezeRestoredObject(child)
/** Deep-freeze one acyclic JSON tree without consuming the JavaScript call stack. */
function freezeRestoredObject<T extends object>(value: T): T {
const pending: object[] = [value]
while (pending.length > 0) {
// The non-empty check proves an object remains to visit.
// oxlint-disable-next-line typescript/no-non-null-assertion
const current = pending.pop()!
Object.freeze(current)
for (const key in current) {
const child = (current as Record<string, unknown>)[key]
if (child !== null && typeof child === 'object') pending.push(child)
}
}
return value
}

View File

@@ -941,6 +941,36 @@ describe('Session', () => {
expect(() => { appendedEvent.data.todos[0]!.content = 'mutated' }).toThrow(TypeError)
})
it('iteratively freezes deeply nested restored event data', () => {
const depth = 20_000
const data: Record<string, unknown> = {}
let tail = data
for (let index = 0; index < depth; index += 1) {
const child: Record<string, unknown> = {}
tail['child'] = child
tail = child
}
const event = {
type: 'test/deep-restore', seq: 0, time: 1, data,
} as unknown as SessionEvent
expect(() => Session.fromRestore(SessionId('deep-restore'), [event], {
version: SESSION_FORMAT_VERSION,
id: SessionId('deep-restore'),
createdAt: 1,
})).not.toThrow()
let current: unknown = event
let frozenNodes = 0
for (let index = 0; index <= depth + 1; index += 1) {
if (!Object.isFrozen(current)) break
frozenNodes += 1
current = (current as Record<string, unknown>)['data']
?? (current as Record<string, unknown>)['child']
}
expect(frozenNodes).toBe(depth + 2)
})
it('returns cached frozen event-array snapshots that do not grow after append', () => {
const session = Session.create(SessionId('events-snapshot'))
session.append('turn/start', { turn: 1 })

View File

@@ -34,7 +34,11 @@ export type { JsonlCompression } from './format.ts'
const DEFAULT_PACK_CHUNKS = true
const DEFAULT_COMPRESSION: JsonlCompression = 'zstd'
/** internal yield interval. */
/**
* Internal scheduling constant, not deployment configuration: balance
* frame-boundary event-loop yields against `setImmediate` overhead. One frame
* remains an indivisible synchronous decode.
*/
const ZSTD_DECODE_YIELD_INTERVAL_MS = 500
/** Assert that the independently decodable first frame contains only the header record. */

View File

@@ -713,7 +713,7 @@ describe('SessionPersistenceJsonl: scanLog unit', () => {
expect(result.events).toEqual([oneTurnLog()[0]])
expect(result.committedBytes).toBe(header.length + event.length + 1)
expect(() =>{ scanner.write(Buffer.from('\n')) }).toThrow(/finished/)
expect(() => { scanner.write(Buffer.from('\n')) }).toThrow(/finished/)
})
it('keeps scanning after a tolerable corrupt suffix until a committed turn end appears', () => {
@@ -728,7 +728,7 @@ describe('SessionPersistenceJsonl: scanLog unit', () => {
expect(scanner.finish().events).toEqual([oneTurnLog()[0]])
const committed = new SessionLogScanner(header)
expect(() =>{ committed.write(Buffer.from([
expect(() => { committed.write(Buffer.from([
JSON.stringify({ type: 'turn/end', seq: 1, time: 2, data: { turn: 1, reason: { kind: 'completed' } } }),
'',
].join('\n'))) }).toThrow(/seq gap in committed region/)

View File

@@ -1,8 +1,9 @@
/**
* Read-only interpretation of session-query lineage as durable subagent
* children. The module owns no catalog state and does not consult Activation,
* Agent-registry, continuation-manager, or provider state. A child's
* descriptor distinguishes one-shot work from a continuable conversation.
* children. Only descendants with durable `origin: 'subagent'` enter per-child
* inspection. The module owns no catalog state and does not consult Activation,
* Agent-registry, continuation-manager, or provider state. A child's descriptor
* distinguishes one-shot work from a continuable conversation.
*
* @module @deepseek-ai/dsh-subagent
*/
@@ -20,12 +21,13 @@ type SessionQueryRuntime = Pick<
>
/**
* One entry of a {@link listChildren} result in trace candidate order. A valid
* descriptor produces a `child`, a per-child inspection failure produces a
* `diagnostic`, and a descriptor-less ordinary child is omitted. Healthy rows
* include a one-level, origin-classified descendant hint. Diagnostics are
* transient query results, never session events or catalog state, and never
* expose model-hidden descriptor content.
* One entry of a {@link listChildren} result in trace candidate order. Only a
* candidate whose durable header has `origin: 'subagent'` is inspected. A
* valid descriptor produces a `child`, a per-child inspection failure produces
* a `diagnostic`, and a candidate without its own descriptor is omitted.
* Healthy rows include a one-level, origin-classified descendant hint.
* Diagnostics are transient query results, never session events or catalog
* state, and never expose model-hidden descriptor content.
*/
export type SubagentListEntry =
| {
@@ -69,8 +71,9 @@ export type SubagentListEntry =
}
/**
* Interpret one parent's direct session descendants as session-backed subagents
* without loading or resuming an Agent.
* Interpret one parent's origin-classified direct descendants as session-backed
* subagents without loading or resuming an Agent. Ordinary forks are skipped
* before per-child event inspection.
* @see {@link SubagentService.listChildren} for the public cancellation and
* failure contract.
* @param ctx - context carrying the optional session-query service.

View File

@@ -410,16 +410,6 @@ describe('SubagentService.listChildren', () => {
expect(entries).toEqual([{ kind: 'diagnostic', id: childId, reason: 'corrupt' }])
})
it('maps an invalid child surface to corrupt', async () => {
const { ctx, parent } = await setup([textResponse('done')])
const childId = await startChild(ctx, parent, 'invalid surface')
const query = ctx.get('sessionQuery')!
query.listEvents = () =>
Promise.reject(new SessionQueryError('invalid surface', 'SESSION_QUERY_INVALID_SURFACE'))
const entries = await ctx.subagents.listChildren(parent.id)
expect(entries).toEqual([{ kind: 'diagnostic', id: childId, reason: 'corrupt' }])
})
it('diagnoses a read whose target is no longer the descriptor event as corrupt', async () => {
const { ctx, parent } = await setup([textResponse('done')])
const childId = await startChild(ctx, parent, 'shifted log')