fix(desktop): keep operation history the predecessor read would drop

readOperationHistory could silently omit the rotation predecessor:
one transient Windows sharing or permission failure on the second
segment's open was counted as unavailable, and any equal device/inode
pair dropped the segment even when the current path still named the
file already read, because the 64-bit Windows file ID is not unique.

Retry the documented Windows transient open codes on a bounded
exponential delay, and deduplicate a segment only when the current
segment path stopped naming it. Both stats now come from bigint
stats so the exact file ID is compared.

The coverage test now asserts the whole collection result, so a
missing record also reports filesRead, bytesRead and unavailableFiles.
This commit is contained in:
dsh-ci-bot committed 2026-11-18 07:20:22 +08:00
1 parent b8ad4dc7f5
commit e473fcfa82
2 files changed
+250 -15

No files matched your search

+77 -10
View File
@@ -1,9 +1,17 @@
/** Bounded, cancellable reads of Desktop-owned plugin operation history. */
import { open } from 'node:fs/promises'
import { open, stat, type FileHandle } from 'node:fs/promises'
import { join } from 'node:path'
import { setImmediate } from 'node:timers/promises'
import { setImmediate, setTimeout as wait } from 'node:timers/promises'
import { parsePluginOperationRecord, type PluginOperationRecord } from '@deepseek-ai/dsh-plugin-manager/diagnostic'
/** The segment this collector reads first; the other owned segment is its rotation predecessor. */
const CURRENT_SEGMENT = 'operations.jsonl'
/** Windows reports these while another handle temporarily owns an otherwise readable file. */
const WINDOWS_TRANSIENT_OPEN_ERRORS: ReadonlySet<string> = new Set(['EACCES', 'EBUSY', 'EPERM'])
const WINDOWS_OPEN_RETRY_INITIAL_MS = 10
const WINDOWS_OPEN_RETRY_MAX_MS = 40
const WINDOWS_OPEN_RETRY_LIMIT = 4
/** Resource budgets for auxiliary history collection, independent of basic crash report writing. */
export interface OperationHistoryReadLimits {
readonly bytes: number
@@ -23,9 +31,67 @@ export interface OperationHistoryReadResult {
readonly cancelled: boolean
}
/**
* Exact two-name key for one file; both stats are BigInt so a Windows 64-bit file ID
* round-trips without the precision loss of its Number form.
* @param info - Stats of the opened segment or of the current segment path.
* @returns Device and inode as one comparable string.
*/
function fileIdentity(info: { readonly dev: number | bigint; readonly ino: number | bigint }): string {
return `${String(info.dev)}:${String(info.ino)}`
}
/** Whether Windows reported temporary interference with opening a history segment. */
function isTransientWindowsOpenError(error: unknown): boolean {
if (process.platform !== 'win32') return false
return WINDOWS_TRANSIENT_OPEN_ERRORS.has((error as NodeJS.ErrnoException | null)?.code ?? '')
}
/**
* Open one segment, retrying the temporary Windows sharing and permission failures a scanner
* causes on a freshly written file. One persistent failure would otherwise drop the whole
* segment from the report. A signal aborted during the bounded wait ends the retries without
* another open.
* @param filename - Absolute path of the owned segment.
* @param signal - Caller-owned collection deadline or shutdown cancellation.
* @returns The opened read handle.
*/
async function openSegment(filename: string, signal: AbortSignal): Promise<FileHandle> {
let delay = WINDOWS_OPEN_RETRY_INITIAL_MS
for (let retries = 0;; retries += 1) {
try {
return await open(filename, 'r')
} catch (error) {
if (!isTransientWindowsOpenError(error) || retries >= WINDOWS_OPEN_RETRY_LIMIT || signal.aborted) throw error
await wait(delay)
if (signal.aborted) throw error
delay = Math.min(delay * 2, WINDOWS_OPEN_RETRY_MAX_MS)
}
}
}
/**
* Whether the current segment path stopped naming the file this collection already read.
* Identity equality alone cannot decide: Windows does not guarantee that its 64-bit file ID
* is unique, so two distinct segments can report one identity; a rotation is only deduplicated
* once the current path itself moved on.
* @param directory - Desktop's operation history directory.
* @param identity - Identity of the segment already read from the current path.
* @returns Whether the predecessor is the segment already read.
*/
async function currentSegmentRotated(directory: string, identity: string): Promise<boolean> {
try {
return fileIdentity(await stat(join(directory, CURRENT_SEGMENT), { bigint: true })) !== identity
} catch {
// A path that no longer resolves cannot still name the segment already read.
return true
}
}
/**
* Read only the bounded tails of the two owned history files, newest segment first.
* Cancellation is observed between bounded records after yielding to Worker messages and stops subsequent I/O and parsing.
* A segment is deduplicated as already read only when the current path stopped naming it.
* An already-issued OS read must settle before its handle closes.
* @param directory - Desktop's operation history directory; unrelated files are never enumerated.
* @param limits - Positive byte, record-size and record-count budgets.
@@ -48,29 +114,30 @@ export async function readOperationHistory(
let truncated = false
let invalidRecords = 0
let unavailableFiles = 0
for (const name of ['operations.jsonl', 'operations.previous.jsonl']) {
for (const name of [CURRENT_SEGMENT, 'operations.previous.jsonl']) {
if (cancelled()) break
try {
await using handle = await open(join(directory, name), 'r')
await using handle = await openSegment(join(directory, name), signal)
if (cancelled()) break
const fileStat = await handle.stat()
const fileStat = await handle.stat({ bigint: true })
if (cancelled()) break
if (!fileStat.isFile()) {
unavailableFiles++
continue
}
const identity = `${String(fileStat.dev)}:${String(fileStat.ino)}`
if (seenFiles.has(identity)) {
const identity = fileIdentity(fileStat)
const size = Number(fileStat.size)
if (seenFiles.has(identity) && await currentSegmentRotated(directory, identity)) {
truncated = true
continue
}
if (fileStat.size > 0 && (bytesRead >= limits.bytes || records.length >= limits.records)) {
if (size > 0 && (bytesRead >= limits.bytes || records.length >= limits.records)) {
truncated = true
break
}
const readLength = Math.min(fileStat.size, limits.bytes - bytesRead)
const readStart = fileStat.size - readLength
const readLength = Math.min(size, limits.bytes - bytesRead)
const readStart = size - readLength
const buffer = Buffer.alloc(readLength)
let readOffset = 0
while (readOffset < readLength && !cancelled()) {
+173 -5
View File
@@ -1,4 +1,4 @@
import { mkdtemp, mkdir, open, rename, rm, writeFile } from 'node:fs/promises'
import { mkdtemp, mkdir, open, rename, rm, stat, writeFile } from 'node:fs/promises'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { expect, it, onTestFinished, vi } from 'vitest'
@@ -6,7 +6,7 @@ import { readOperationHistory } from '../src/operation-history.ts'
vi.mock('node:fs/promises', async (importOriginal) => {
const actual = await importOriginal<typeof import('node:fs/promises')>()
return { ...actual, open: vi.fn(actual.open) }
return { ...actual, open: vi.fn(actual.open), stat: vi.fn(actual.stat) }
})
const limits = { bytes: 64 * 1024, recordBytes: 2048, records: 100 }
@@ -25,11 +25,158 @@ async function fixture() {
it('collects recent complete records and reports malformed and incomplete entries', async () => {
const path = await fixture()
await writeFile(join(path, 'operations.jsonl'), line(1) + '{broken}\n' + line(2) + '{"incomplete":')
const current = line(1) + '{broken}\n' + line(2) + '{"incomplete":'
await writeFile(join(path, 'operations.jsonl'), current)
await writeFile(join(path, 'operations.previous.jsonl'), line(0))
const result = await readOperationHistory(path, limits, new AbortController().signal)
expect(result.records).toEqual([record(2), record(1), record(0)])
expect(result).toMatchObject({ invalidRecords: 1, truncated: true, cancelled: false, unavailableFiles: 0 })
// The whole result is asserted so a missing record also names the collection facts that caused it.
expect(result).toEqual({
records: [record(2), record(1), record(0)],
bytesRead: Buffer.byteLength(current) + Buffer.byteLength(line(0)),
filesRead: 2,
truncated: true,
invalidRecords: 1,
unavailableFiles: 0,
cancelled: false,
})
})
it('keeps a predecessor whose reported identity equals the current segment without a rotation', async () => {
const path = await fixture()
const current = join(path, 'operations.jsonl')
const previous = join(path, 'operations.previous.jsonl')
const currentText = line(2)
const previousText = line(1)
await writeFile(current, currentText)
await writeFile(previous, previousText)
const currentHandle = await open(current, 'r')
const previousHandle = await open(previous, 'r')
onTestFinished(async () => { await currentHandle.close(); await previousHandle.close() })
const currentStat = await currentHandle.stat()
const previousStat = await previousHandle.stat()
// Windows does not guarantee its 64-bit file ID is unique; one ID can name two segments.
currentStat.dev = 0
currentStat.ino = 7
previousStat.dev = 0
previousStat.ino = 7
const currentStats = vi.spyOn(currentHandle, 'stat').mockResolvedValueOnce(currentStat)
const previousStats = vi.spyOn(previousHandle, 'stat').mockResolvedValueOnce(previousStat)
const opener = vi.mocked(open).mockClear().mockResolvedValueOnce(currentHandle).mockResolvedValueOnce(previousHandle)
const pathStat = vi.mocked(stat).mockClear().mockResolvedValueOnce(currentStat)
try {
const result = await readOperationHistory(path, limits, new AbortController().signal)
expect(result).toEqual({
records: [record(2), record(1)],
bytesRead: Buffer.byteLength(currentText) + Buffer.byteLength(previousText),
filesRead: 1,
truncated: false,
invalidRecords: 0,
unavailableFiles: 0,
cancelled: false,
})
expect(pathStat).toHaveBeenCalledTimes(1)
} finally {
currentStats.mockRestore()
previousStats.mockRestore()
opener.mockClear()
pathStat.mockClear()
}
})
it('retries transient Windows sharing failures while opening a segment', async () => {
const platform = vi.spyOn(process, 'platform', 'get').mockReturnValue('win32')
const actualFs = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')
const opener = vi.mocked(open)
onTestFinished(async () => {
platform.mockRestore()
opener.mockReset().mockImplementation(actualFs.open)
})
const path = await fixture()
await writeFile(join(path, 'operations.jsonl'), line(2))
await writeFile(join(path, 'operations.previous.jsonl'), line(1))
opener.mockRejectedValueOnce(Object.assign(new Error('sharing violation'), { code: 'EBUSY' }))
const result = await readOperationHistory(path, limits, new AbortController().signal)
expect(result.records).toEqual([record(2), record(1)])
expect(result.unavailableFiles).toBe(0)
expect(opener).toHaveBeenCalledTimes(3)
})
it('counts a segment unavailable after bounded Windows open retries expire', async () => {
const platform = vi.spyOn(process, 'platform', 'get').mockReturnValue('win32')
const actualFs = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')
const opener = vi.mocked(open)
onTestFinished(async () => {
platform.mockRestore()
opener.mockReset().mockImplementation(actualFs.open)
})
const path = await fixture()
await writeFile(join(path, 'operations.jsonl'), line(2))
await writeFile(join(path, 'operations.previous.jsonl'), line(1))
for (let attempt = 0; attempt <= 4; attempt++) {
opener.mockRejectedValueOnce(Object.assign(new Error('access denied'), { code: 'EPERM' }))
}
const result = await readOperationHistory(path, limits, new AbortController().signal)
expect(result.records).toEqual([record(1)])
expect(result.unavailableFiles).toBe(1)
expect(opener).toHaveBeenCalledTimes(6)
})
it('does not retry a Windows transient code outside Windows', async () => {
const platform = vi.spyOn(process, 'platform', 'get').mockReturnValue('linux')
const actualFs = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')
const opener = vi.mocked(open)
onTestFinished(async () => {
platform.mockRestore()
opener.mockReset().mockImplementation(actualFs.open)
})
const path = await fixture()
await writeFile(join(path, 'operations.jsonl'), line(2))
await writeFile(join(path, 'operations.previous.jsonl'), line(1))
opener.mockRejectedValueOnce(Object.assign(new Error('access denied'), { code: 'EPERM' }))
const result = await readOperationHistory(path, limits, new AbortController().signal)
expect(result.records).toEqual([record(1)])
expect(result.unavailableFiles).toBe(1)
expect(opener).toHaveBeenCalledTimes(2)
})
it('stops Windows open retries when the collection is already cancelled', async () => {
const platform = vi.spyOn(process, 'platform', 'get').mockReturnValue('win32')
const actualFs = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')
const opener = vi.mocked(open)
onTestFinished(async () => {
platform.mockRestore()
opener.mockReset().mockImplementation(actualFs.open)
})
const path = await fixture()
await writeFile(join(path, 'operations.jsonl'), line(2))
const controller = new AbortController()
opener.mockImplementationOnce(async () => {
controller.abort()
throw Object.assign(new Error('sharing violation'), { code: 'EBUSY' })
})
const result = await readOperationHistory(path, limits, controller.signal)
expect(result).toMatchObject({ records: [], cancelled: true, unavailableFiles: 1 })
expect(opener).toHaveBeenCalledTimes(1)
})
it('stops Windows open retries when cancellation lands during the retry wait', async () => {
const platform = vi.spyOn(process, 'platform', 'get').mockReturnValue('win32')
const actualFs = await vi.importActual<typeof import('node:fs/promises')>('node:fs/promises')
const opener = vi.mocked(open)
onTestFinished(async () => {
platform.mockRestore()
opener.mockReset().mockImplementation(actualFs.open)
})
const path = await fixture()
await writeFile(join(path, 'operations.jsonl'), line(2))
const controller = new AbortController()
opener.mockImplementationOnce(async () => {
setImmediate(() => controller.abort())
throw Object.assign(new Error('sharing violation'), { code: 'EBUSY' })
})
const result = await readOperationHistory(path, limits, controller.signal)
expect(result).toMatchObject({ records: [], cancelled: true, unavailableFiles: 1 })
expect(opener).toHaveBeenCalledTimes(1)
})
it('reads no more than its byte budget from a two GiB file and ignores unrelated history', async () => {
@@ -159,6 +306,27 @@ it('does not collect the same open segment twice when it rotates during collecti
}
})
it('does not re-collect a rotated segment while the current path is briefly absent', async () => {
const path = await fixture()
const current = join(path, 'operations.jsonl')
await writeFile(current, line(1))
const handle = await open(current, 'r')
onTestFinished(async () => { await handle.close() })
const opener = vi.mocked(open).mockClear().mockImplementationOnce(async () => {
await rename(current, join(path, 'operations.previous.jsonl'))
return handle
})
try {
const result = await readOperationHistory(path, limits, new AbortController().signal)
expect(result.records).toEqual([record(1)])
expect(result).toMatchObject({ filesRead: 1, truncated: true })
expect(handle.fd).toBe(-1)
} finally {
opener.mockClear()
await handle.close()
}
})
it.each(['absent', 'empty', 'nonempty'])('reports omitted bytes at an exact budget: previous segment %s', async (previous) => {
const path = await fixture()
const current = line(1)