diff --git a/apps/frontend/package.json b/apps/frontend/package.json
index ba8baa74..43846cb4 100644
--- a/apps/frontend/package.json
+++ b/apps/frontend/package.json
@@ -27,7 +27,7 @@
"@antv/x6-plugin-minimap": "2.0.7",
"@antv/x6-vue-shape": "2.1.2",
"@element-plus/icons-vue": "2.3.1",
- "@crysound/crychart": "1.0.1",
+ "@crysound/crychart": "1.0.2",
"@number-flow/vue": "0.5.2",
"@vueuse/core": "12.7.0",
"axios": "1.7.9",
diff --git a/apps/frontend/src/libs/charts/adapters/crychart/data-graph/components/views/waveform/__tests__/clear-data.test.ts b/apps/frontend/src/libs/charts/adapters/crychart/data-graph/components/views/waveform/__tests__/clear-data.test.ts
index 24f32220..6281bd8c 100644
--- a/apps/frontend/src/libs/charts/adapters/crychart/data-graph/components/views/waveform/__tests__/clear-data.test.ts
+++ b/apps/frontend/src/libs/charts/adapters/crychart/data-graph/components/views/waveform/__tests__/clear-data.test.ts
@@ -1,7 +1,8 @@
import { mount } from '@vue/test-utils'
-import { computed, nextTick, ref, toValue, useTemplateRef, watch, watchEffect } from 'vue'
+import { computed, nextTick, ref, shallowRef, toValue, useTemplateRef, watch, watchEffect } from 'vue'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import WaveformView from '../index.vue'
+import { WaveformTimeIndexLoadError } from '@/modules/shared/data-graph/utils/waveform-time-index-error'
import type { DataGraphAxisConfig, DataGraphConfig } from '../../../../../../../../../modules/shared/data-graph/types'
const mocks = vi.hoisted(() => {
@@ -27,11 +28,13 @@ const mocks = vi.hoisted(() => {
}
const chartInstance = chartInstanceBase as typeof chartInstanceBase & {
getSeriesDataComplete: (_seriesId: string) => boolean
+ timeOriginNs?: bigint
}
return {
axisX,
chartInstance,
+ chartRef: null,
createRef,
loadGraphicData: vi.fn(),
cryChartOptions: null,
@@ -88,7 +91,7 @@ vi.mock('@/libs/charts/adapters/crychart/data-graph/hooks/use-cry-chart', () =>
useCryChart: vi.fn(options => {
mocks.cryChartOptions = options
return {
- chartInstance: mocks.createRef(mocks.chartInstance),
+ chartInstance: mocks.chartRef,
updateChartData: mocks.updateChartData,
clearPendingUpdates: vi.fn()
}
@@ -277,6 +280,8 @@ describe('WaveformView clearData', () => {
beforeEach(() => {
vi.clearAllMocks()
+ mocks.chartInstance.timeOriginNs = undefined
+ mocks.chartRef = shallowRef(mocks.chartInstance)
mocks.cryChartOptions = null
mocks.calibrationOptions = null
mocks.playbackRunning = ref(false)
@@ -297,6 +302,33 @@ describe('WaveformView clearData', () => {
vi.unstubAllGlobals()
})
+ it('gives a chart created after the index the same origin used for loading windows', async () => {
+ mocks.chartRef.value = null
+ const wrapper = mount(WaveformView, { props: { config: createPreviewConfig() } })
+ mocks.waveformDataOptions.onIndexLoaded({
+ later: [{ timeOriginNs: '1794312010000000123' }],
+ earlier: [{ timeOriginNs: '1794312000000000123' }]
+ })
+ expect(mocks.waveformDataOptions.getTimeOriginNsFn()).toBe(1794312000000000123n)
+ mocks.chartRef.value = mocks.chartInstance
+ await nextTick()
+ expect(mocks.chartInstance.timeOriginNs).toBe(1794312000000000123n)
+ wrapper.unmount()
+ })
+
+ it('shows a file error for an invalid time index until a valid index is loaded', async () => {
+ const wrapper = mount(WaveformView, { props: { config: createPreviewConfig() } })
+ const alert = '[data-testid="waveform-index-load-error"]'
+ expect(wrapper.find(alert).exists()).toBe(false)
+ mocks.waveformDataOptions.onError(new WaveformTimeIndexLoadError('series-1', new Error('decreasing timestamps')))
+ await nextTick()
+ expect(wrapper.get(alert).attributes('role')).toBe('alert')
+ mocks.waveformDataOptions.onIndexLoaded({ 'series-1': [{ timeOriginNs: '1794312000000000123' }] })
+ await nextTick()
+ expect(wrapper.find(alert).exists()).toBe(false)
+ wrapper.unmount()
+ })
+
it('fits an Enhancement Waveform overwrite frame to its sample duration', () => {
const wrapper = mount(WaveformView, {
props: {
diff --git a/apps/frontend/src/libs/charts/adapters/crychart/data-graph/components/views/waveform/__tests__/time-axis-context.test.ts b/apps/frontend/src/libs/charts/adapters/crychart/data-graph/components/views/waveform/__tests__/time-axis-context.test.ts
index db833cff..0d296bed 100644
--- a/apps/frontend/src/libs/charts/adapters/crychart/data-graph/components/views/waveform/__tests__/time-axis-context.test.ts
+++ b/apps/frontend/src/libs/charts/adapters/crychart/data-graph/components/views/waveform/__tests__/time-axis-context.test.ts
@@ -17,6 +17,25 @@ describe('waveform and preview clock', () => {
expect(main.timeOriginNs).toBeUndefined()
})
+ it('keeps the indexed origin when the preview and main chart are created after the index', () => {
+ const context = createWaveformTimeAxisContext()
+ context.initializeFromIndex({
+ late: [{ timeOriginNs: '1794312010000000123' }],
+ early: [{ timeOriginNs: '1794312000000000123' }]
+ })
+ expect(context.origin.value).toBe(1794312000000000123n)
+ const preview = { timeOriginNs: undefined as bigint | undefined }
+ const main = { timeOriginNs: 1n as bigint | undefined }
+ context.apply(preview, { timeOriginNs: '1794312010000000123', start: 0, step: 1, yValues: [1, 2] })
+ context.apply(main)
+ expect(main.timeOriginNs).toBe(1794312000000000123n)
+ expect(preview.timeOriginNs).toBe(main.timeOriginNs)
+ context.reset()
+ context.initializeFromIndex({ replacement: [{ timeOriginNs: '1794312020000000123' }] })
+ context.apply(main)
+ expect(main.timeOriginNs).toBe(1794312020000000123n)
+ })
+
it('derives the shared clock from realtime acquisition timestamps, excluding rejected batches', () => {
const context = createWaveformTimeAxisContext()
const chart = { timeOriginNs: undefined as bigint | undefined }
diff --git a/apps/frontend/src/libs/charts/adapters/crychart/data-graph/components/views/waveform/index.vue b/apps/frontend/src/libs/charts/adapters/crychart/data-graph/components/views/waveform/index.vue
index f2c825c4..2222a7ca 100644
--- a/apps/frontend/src/libs/charts/adapters/crychart/data-graph/components/views/waveform/index.vue
+++ b/apps/frontend/src/libs/charts/adapters/crychart/data-graph/components/views/waveform/index.vue
@@ -25,7 +25,15 @@
/>
+ {{ translate('chart.config.fileReadError') }}
+
+ waveformTimeSourceKey(props.config.renderDatas)
let loadedTimeSourceKey = timeSourceKey()
let previewDataSourceKey = createDataSourceFingerprint(props.config.renderDatas ?? [])
const timeAxisContext = createWaveformTimeAxisContext()
-watch(timeSourceKey, () => timeAxisContext.reset(), { flush: 'sync' })
+const waveformIndexError = shallowRef(false)
+watch(
+ timeSourceKey,
+ () => {
+ timeAxisContext.reset()
+ waveformIndexError.value = false
+ },
+ { flush: 'sync' }
+)
const { playbackRunning, playbackTime, playbackEnabled, playbackWaveformInterval } = usePlaybackInfo()
@@ -121,15 +141,15 @@ const applyWaveformDisplayUnitReference = (result: WaveformDisplayReference) =>
}
pendingDisplayReferences.delete(key)
const wasMissing = missingCalibrationSeriesIds.value.has(key)
- const sourceUnit = result.sourceUnitY?.trim() ?? (
- unitConversion?.displayOnly ? unitConversion.sourceUnit?.trim() : unitConversion?.targetUnit?.trim()
- )
+ const sourceUnit =
+ result.sourceUnitY?.trim() ??
+ (unitConversion?.displayOnly ? unitConversion.sourceUnit?.trim() : unitConversion?.targetUnit?.trim())
const targetUnit = result.targetUnitY?.trim() ?? unitConversion?.targetUnit?.trim()
const isCalibratedDbTarget = ['dBV', 'dBSPL'].includes(targetUnit)
- const requiresCalibration = result.displayOnly === true || unitConversion?.displayOnly === true || (
- isCalibratedDbTarget
- && (!sourceUnit || sourceUnit.toUpperCase() === 'FS')
- )
+ const requiresCalibration =
+ result.displayOnly === true ||
+ unitConversion?.displayOnly === true ||
+ (isCalibratedDbTarget && (!sourceUnit || sourceUnit.toUpperCase() === 'FS'))
if (sourceUnit !== undefined) {
chartInstance.value?.setWaveformSourceUnit?.(seriesId, sourceUnit)
@@ -225,7 +245,11 @@ const waveformDisplayMappingCalibration = useWaveformDisplayMappingCalibration({
inferRealtimeDisplayCoordinateUnit: true
})
-const { chartInstance, updateChartData: submitChartData, clearPendingUpdates } = useCryChart({
+const {
+ chartInstance,
+ updateChartData: submitChartData,
+ clearPendingUpdates
+} = useCryChart({
config: () => props.config,
containerRef,
loadDataFn: () => requestDataLoad(),
@@ -252,14 +276,22 @@ watch([chartInstance, timeAxisContext.origin], ([instance]) => timeAxisContext.a
flush: 'sync'
})
-watch(chartInstance, instance => {
- if (instance) pendingDisplayReferences.forEach(applyWaveformDisplayUnitReference)
-}, { flush: 'sync' })
-watch(() => createDataSourceFingerprint(props.config.renderDatas ?? []), () => {
- pendingDisplayReferences.clear()
- // 未建图时通用配置更新尚不能重载,清掉旧样本并使用现有请求代际加载新来源。
- if (!chartInstance.value) reloadMainData()
-}, { flush: 'sync' })
+watch(
+ chartInstance,
+ instance => {
+ if (instance) pendingDisplayReferences.forEach(applyWaveformDisplayUnitReference)
+ },
+ { flush: 'sync' }
+)
+watch(
+ () => createDataSourceFingerprint(props.config.renderDatas ?? []),
+ () => {
+ pendingDisplayReferences.clear()
+ // 未建图时通用配置更新尚不能重载,清掉旧样本并使用现有请求代际加载新来源。
+ if (!chartInstance.value) reloadMainData()
+ },
+ { flush: 'sync' }
+)
const getSeriesDataComplete = (seriesId: string | number) => {
if (isRealtime.value || showPreview.value) {
@@ -357,10 +389,16 @@ const updateData = (seriesId: string | number, data: DataGraphSeriesData, isAppe
renderData,
frame: data,
replay: mappedData => {
- waveformCoordinates.submit(seriesId, mappedData, mappedData, (projected, metadata) => {
- if (!applyWaveformDisplayUnitReference({ seriesId, ...metadata })) return
- renderWaveformData(seriesId, projected, isAppend)
- }, isAppend && !props.config.isRealtime)
+ waveformCoordinates.submit(
+ seriesId,
+ mappedData,
+ mappedData,
+ (projected, metadata) => {
+ if (!applyWaveformDisplayUnitReference({ seriesId, ...metadata })) return
+ renderWaveformData(seriesId, projected, isAppend)
+ },
+ isAppend && !props.config.isRealtime
+ )
}
})
}
@@ -369,6 +407,7 @@ const { isLoading, loadGraphicData, xDataMax } = useWaveformData({
config: () => props.config,
lazy: showPreview,
getSeriesTimeOffsetFn: seriesId => chartInstance.value?.getSeriesTimeOffset?.(seriesId) ?? 0,
+ getTimeOriginNsFn: () => timeAxisContext.origin.value,
getIntervalFn: () => {
const axis = chartInstance.value?.getDefaultAxisX()
if (axis) {
@@ -381,18 +420,36 @@ const { isLoading, loadGraphicData, xDataMax } = useWaveformData({
},
onDataLoaded: (data, result) => {
const { seriesId, step, isAppend, start } = result
- waveformCoordinates.submit(seriesId, { ...data, timeOriginNs: typeof result.timeOriginNs === 'string' ? result.timeOriginNs : data.timeOriginNs, yValues: data.yValues, step, start }, result, (projected, metadata) => {
- if (!applyWaveformDisplayUnitReference({ seriesId, ...metadata })) return
- mainDataLoadTask.markDataLoaded(seriesId, projected)
- renderWaveformData(seriesId, projected, isAppend)
- }, isAppend)
+ waveformCoordinates.submit(
+ seriesId,
+ {
+ ...data,
+ timeOriginNs: typeof result.timeOriginNs === 'string' ? result.timeOriginNs : data.timeOriginNs,
+ yValues: data.yValues,
+ step,
+ start
+ },
+ result,
+ (projected, metadata) => {
+ if (!applyWaveformDisplayUnitReference({ seriesId, ...metadata })) return
+ mainDataLoadTask.markDataLoaded(seriesId, projected)
+ renderWaveformData(seriesId, projected, isAppend)
+ },
+ isAppend
+ )
},
onIndexLoaded: indexMap => {
const indexEntries = Object.entries(indexMap ?? {})
+ waveformIndexError.value = false
+ timeAxisContext.initializeFromIndex(indexMap)
+ timeAxisContext.apply(chartInstance.value)
seriesFileCompleteness.value = new Map(indexEntries.map(([seriesId]) => [String(seriesId), false]))
const hasMultipleShards = indexEntries.some(([, files]) => Array.isArray(files) && files.length > 1)
hasMultipleMainShards.value = hasMultipleShards
},
+ onError: error => {
+ if (error instanceof WaveformTimeIndexLoadError) waveformIndexError.value = true
+ },
onSeriesDataComplete: (seriesId, complete) => {
const nextCompleteness = new Map(seriesFileCompleteness.value)
nextCompleteness.set(String(seriesId), complete === true)
@@ -406,9 +463,7 @@ const mainDataLoadTask = useDataLoadTask({
execute: async ({ mode, resetPreviewState, preserveTimeOrigin, ...loadOptions }) => {
if (mode === 'refresh') clearLoadedData(resetPreviewState === true, preserveTimeOrigin === true)
try {
- const result = await loadGraphicData(
- mode === 'poll' ? { ...loadOptions, poll: true } : mode === 'refresh'
- )
+ const result = await loadGraphicData(mode === 'poll' ? { ...loadOptions, poll: true } : mode === 'refresh')
if (result?.error) throw result.error
} finally {
waveformCoordinates.finish()
@@ -417,9 +472,13 @@ const mainDataLoadTask = useDataLoadTask({
})
// 包括缩放、预览拖动和播放参与者触发的内部加载,均在队列结束时释放待校准块。
-watch(isLoading, loading => {
- if (!loading) waveformCoordinates.finish()
-}, { flush: 'sync' })
+watch(
+ isLoading,
+ loading => {
+ if (!loading) waveformCoordinates.finish()
+ },
+ { flush: 'sync' }
+)
const aggregateWaveformTasks = tasks => {
const settled = Promise.all(tasks.map(task => task.settled)).then(
@@ -647,6 +706,7 @@ defineExpose({
max-height: 80px;
}
+ .waveform-load-error,
.calibration-message {
position: absolute;
top: 8px;
@@ -660,5 +720,9 @@ defineExpose({
border-radius: 4px;
transform: translateX(-50%);
}
+
+ .waveform-load-error {
+ color: var(--el-color-danger);
+ }
}
diff --git a/apps/frontend/src/libs/charts/adapters/crychart/data-graph/components/views/waveform/time-axis-context.ts b/apps/frontend/src/libs/charts/adapters/crychart/data-graph/components/views/waveform/time-axis-context.ts
index b5e1e9f1..1d0acd7b 100644
--- a/apps/frontend/src/libs/charts/adapters/crychart/data-graph/components/views/waveform/time-axis-context.ts
+++ b/apps/frontend/src/libs/charts/adapters/crychart/data-graph/components/views/waveform/time-axis-context.ts
@@ -8,6 +8,17 @@ export function createWaveformTimeAxisContext() {
const origin = shallowRef
()
return {
origin,
+ initializeFromIndex(files: Record> = {}) {
+ if (origin.value !== undefined) return
+ let earliest: bigint | undefined
+ for (const series of Object.values(files)) {
+ for (const file of series) {
+ const candidate = parseTimeOrigin(file.timeOriginNs)
+ if (candidate !== undefined && (earliest === undefined || candidate < earliest)) earliest = candidate
+ }
+ }
+ origin.value = earliest
+ },
apply(chart?: Pick | null, data?: DataGraphSeriesData, fallbackOrigin?: string) {
const timed = data && resolveTimestampData(data, { waveform: true })
if (origin.value === undefined && timed && increasingTimeRange(timed)) {
diff --git a/apps/frontend/src/libs/file-loader/__tests__/waveform-time-index.test.ts b/apps/frontend/src/libs/file-loader/__tests__/waveform-time-index.test.ts
new file mode 100644
index 00000000..e7bad07a
--- /dev/null
+++ b/apps/frontend/src/libs/file-loader/__tests__/waveform-time-index.test.ts
@@ -0,0 +1,144 @@
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { appendFile, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
+import { createRequire } from 'node:module'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { V1_MAX_HEADER_LENGTH } from '../crybin'
+import { readWaveformTimeIndex } from '../handlers/waveform-time-index'
+import { CRYBIN_V1_FIELD_TYPE, createCrybinFile, createV1Block, createV1CrybinFile } from './crybin-fixtures'
+
+const origin = 1794326399250123456n
+const block = (sampleStart: number, sourceStart: number, count = 1000) => ({
+ yValues: new Array(count).fill(0), taskRelativeTimeMs: sampleStart + count,
+ extraFields: [{ fieldId: 8, type: CRYBIN_V1_FIELD_TYPE.UINT64, value: origin + BigInt(sourceStart) * 1000000n }]
+})
+let dir: string
+beforeEach(async () => { globalThis.require = createRequire(import.meta.url); dir = await mkdtemp(join(tmpdir(), 'waveform-index-')) })
+afterEach(async () => { delete globalThis.require; await rm(dir, { recursive: true, force: true }) })
+async function file(name: string, chunks, start = 0, end = 4000, isComplete = true) {
+ const filePath = join(dir, name)
+ await writeFile(filePath, createV1CrybinFile({ header: { xStep: 1, samplingRate: 1000 }, chunks }))
+ return { filePath, start, end, isComplete }
+}
+
+describe('waveform acquisition-time index', () => {
+ it('maps physical shards by source timestamps, independently of cumulative sample positions', async () => {
+ const a = await file('a.crybin', [block(0, 0), block(1000, 1000)], 0, 2000)
+ const b = await file('b.crybin', [block(2000, 10000), block(3000, 11000)], 2000, 4000)
+ const result = await readWaveformTimeIndex([a, b], 1000)
+ expect(result.files.map(f => [f.start, f.end, f.timeOriginNs])).toEqual([
+ [0, 2000, origin.toString()], [10000, 12000, origin.toString()]
+ ])
+ expect(result.files[1].waveformTimeRanges).toEqual([{ start: 10000, end: 12000, sampleStart: 0, sampleEnd: 2000, step: 1 }])
+ expect(result.bytesRead).toBeGreaterThan(0)
+ expect(result.bytesRead).toBeLessThan(2000) // headers, not the 32 kB sample payload
+ })
+
+ it('keeps file-internal gaps as separate sample ranges', async () => {
+ const input = await file('gap.crybin', [block(0, 0), block(1000, 10000), block(2000, 11000)])
+ const result = await readWaveformTimeIndex([input], 1000)
+ expect(result.files[0].waveformTimeRanges).toEqual([
+ { start: 0, end: 1000, sampleStart: 0, sampleEnd: 1000, step: 1 },
+ { start: 10000, end: 12000, sampleStart: 1000, sampleEnd: 3000, step: 1 }
+ ])
+ })
+
+ it('does not manufacture timestamps for old records and retains the legacy reader for explicit X', async () => {
+ const taskOnly = await file('task.crybin', [{ yValues: [1, 2], taskRelativeTimeMs: 2 }, { yValues: [3, 4], taskRelativeTimeMs: 12 }])
+ const explicit = await file('explicit.crybin', [{ xValues: [0, 10], yValues: [1, 2] }])
+ const old = { filePath: join(dir, 'legacy.crybin'), start: 0, end: 2, isComplete: true }
+ await writeFile(old.filePath, createCrybinFile({ xType: 0, yType: 0, xValues: [], yValues: [1, 2] }))
+ const task = await readWaveformTimeIndex([taskOnly], 1000)
+ expect(task.files[0].timeOriginNs).toBeUndefined()
+ expect(task.files[0].waveformTimeRanges.map(r => [r.start, r.end])).toEqual([[0, 2], [10, 12]])
+ expect((await readWaveformTimeIndex([explicit], 1000)).files).toEqual([explicit])
+ expect((await readWaveformTimeIndex([old], 1000)).files).toEqual([old])
+ })
+
+ it('rejects overlap or reversal across physical shard boundaries before returning any index', async () => {
+ const a = await file('a.crybin', [block(0, 0)], 0, 1000)
+ const b = await file('b.crybin', [block(1000, 500)], 1000, 2000)
+ await expect(readWaveformTimeIndex([a, b], 1000)).rejects.toThrow(/overlap|increase/i)
+ })
+
+ it('ignores an incomplete growing tail and sees it once complete without reusing stale metadata', async () => {
+ const a = await file('growing.crybin', [block(0, 0)], 0, Infinity, false)
+ const next = createV1Block(block(1000, 10000))
+ await appendFile(a.filePath, next.subarray(0, 20))
+ const first = await readWaveformTimeIndex([a], 1000)
+ expect(first.files[0].end).toBe(1000)
+ await appendFile(a.filePath, next.subarray(20))
+ const second = await readWaveformTimeIndex([a], 1000)
+ expect(second.files[0].end).toBe(11000)
+ expect(second.files[0].waveformTimeRanges).toHaveLength(2)
+ })
+
+ it('does not establish a clock from the first growing block before its task end is committed', async () => {
+ const pending = { ...block(0, 0), taskRelativeTimeMs: 0 }
+ const a = await file('pending.crybin', [pending], 0, Infinity, false)
+ const first = await readWaveformTimeIndex([a], 1000)
+ expect(first.files[0].waveformTimeRanges).toEqual([])
+ expect(first.files[0].timeOriginNs).toBeUndefined()
+ await writeFile(a.filePath, createV1CrybinFile({ header: { xStep: 1, samplingRate: 1000 }, chunks: [block(0, 0)] }))
+ const second = await readWaveformTimeIndex([a], 1000)
+ expect(second.files[0]).toMatchObject({ start: 0, end: 1000, timeOriginNs: origin.toString() })
+ })
+
+ it('resumes a growing scan without rereading its committed headers', async () => {
+ const chunks = Array.from({ length: 50 }, (_, i) => block(i * 1000, i * 1000))
+ const a = await file('append.crybin', chunks, 0, Infinity, false)
+ const first = await readWaveformTimeIndex([a], 1000)
+ await appendFile(a.filePath, createV1Block(block(50000, 60000)))
+ const second = await readWaveformTimeIndex([a], 1000)
+ expect(second.bytesRead).toBeLessThan(first.bytesRead / 5)
+ expect(second.files[0].waveformTimeRanges).toEqual([
+ { start: 0, end: 50000, sampleStart: 0, sampleEnd: 50000, step: 1 },
+ { start: 60000, end: 61000, sampleStart: 50000, sampleEnd: 51000, step: 1 }
+ ])
+ const completed = await readWaveformTimeIndex([{ ...a, isComplete: true }], 1000)
+ expect(completed.files[0].waveformTimeRanges).toEqual(second.files[0].waveformTimeRanges)
+ expect((await readWaveformTimeIndex([{ ...a, isComplete: true }], 1000)).bytesRead).toBe(0)
+ })
+
+ it('rechecks the mutable final header before resuming a growing scan', async () => {
+ const firstBlock = block(0, 0)
+ const nextBlock = block(1000, 1000)
+ const a = await file('backfill.crybin', [firstBlock, { ...nextBlock, taskRelativeTimeMs: 2010 }], 0, Infinity, false)
+ const before = await readWaveformTimeIndex([a], 1000)
+ expect(before.files[0].waveformTimeRanges).toHaveLength(2)
+ await writeFile(a.filePath, createV1CrybinFile({ header: { xStep: 1, samplingRate: 1000 }, chunks: [firstBlock, nextBlock] }))
+ await appendFile(a.filePath, createV1Block(block(2000, 2000)))
+ const after = await readWaveformTimeIndex([a], 1000)
+ expect(after.files[0].waveformTimeRanges).toEqual([
+ { start: 0, end: 3000, sampleStart: 0, sampleEnd: 3000, step: 1 }
+ ])
+ })
+
+ it('does not reuse a growing cursor after the file is truncated and rewritten', async () => {
+ const a = await file('rewritten.crybin', [block(0, 0), block(1000, 1000), block(2000, 2000)], 0, Infinity, false)
+ await readWaveformTimeIndex([a], 1000)
+ await writeFile(a.filePath, createV1CrybinFile({ header: { xStep: 1 }, chunks: [block(0, 9000)] }))
+ const rewritten = await readWaveformTimeIndex([a], 1000)
+ expect(rewritten.files[0]).toMatchObject({ end: 1000, timeOriginNs: (origin + 9000000000n).toString(),
+ waveformTimeRanges: [{ start: 0, end: 1000, sampleStart: 0, sampleEnd: 1000, step: 1 }] })
+ })
+
+ it('rejects an oversized block header before attempting to read it', async () => {
+ const a = await file('invalid-length.crybin', [block(0, 0)])
+ const bytes = await readFile(a.filePath)
+ const offset = bytes.readUInt32LE(12)
+ bytes.writeUInt32LE(V1_MAX_HEADER_LENGTH + 1, offset)
+ await writeFile(a.filePath, bytes)
+ await expect(readWaveformTimeIndex([a], 1000)).rejects.toMatchObject({
+ code: 'CRYBIN_INVALID_BLOCK', offset, message: expect.stringContaining('waveform block header length')
+ })
+ })
+
+ it('reuses complete header indexes without rereading payload or headers', async () => {
+ const a = await file('cached.crybin', [block(0, 0), block(1000, 10000)])
+ const first = await readWaveformTimeIndex([a], 1000)
+ const second = await readWaveformTimeIndex([a], 1000)
+ expect(second.files).toEqual(first.files)
+ expect(second.bytesRead).toBe(0)
+ })
+})
diff --git a/apps/frontend/src/libs/file-loader/__tests__/worker-manager.test.ts b/apps/frontend/src/libs/file-loader/__tests__/worker-manager.test.ts
index 6786126b..8e7ab7be 100644
--- a/apps/frontend/src/libs/file-loader/__tests__/worker-manager.test.ts
+++ b/apps/frontend/src/libs/file-loader/__tests__/worker-manager.test.ts
@@ -57,6 +57,7 @@ vi.mock('@/modules/shared/data-graph/utils/perf-logger', () => ({
}))
import { workerManager } from '../worker-manager.js'
+import { loadWaveformTimeIndex } from '../index'
describe('WorkerManager', () => {
beforeEach(() => {
@@ -427,6 +428,19 @@ describe('WorkerManager', () => {
expect(workerManager.taskCallbacks.has(taskId)).toBe(false)
})
+ it.each([
+ ['cancelled', { name: 'AbortError' }],
+ ['complete', { message: 'Waveform time index completed without a result' }]
+ ])('settles an unfinished waveform index promise on %s', async (type, expected) => {
+ const worker = workerMock.instances.at(-1)
+ const pending = loadWaveformTimeIndex([{ filePath: 'record.crybin' }], 48000)
+ const { taskId } = worker.postMessage.mock.lastCall[0]
+ const rejected = expect(pending).rejects.toMatchObject(expected)
+ worker.onmessage({ data: { type, taskId } })
+ await rejected
+ expect(workerManager.taskCallbacks.has(taskId)).toBe(false)
+ })
+
it('shares one pending cancellation for repeated calls', async () => {
const worker = workerMock.instances[workerMock.instances.length - 1]
const taskId = workerManager.startTask('chunk-parser', { filePath: 'demo.crybin' }, {})
diff --git a/apps/frontend/src/libs/file-loader/file-processor.worker.ts b/apps/frontend/src/libs/file-loader/file-processor.worker.ts
index 3cb1de75..e71adaa6 100644
--- a/apps/frontend/src/libs/file-loader/file-processor.worker.ts
+++ b/apps/frontend/src/libs/file-loader/file-processor.worker.ts
@@ -3,6 +3,7 @@ import { RangeFileHandler } from './handlers/range-file-handler'
import { FrameRangeFileHandler } from './handlers/frame-range-file-handler'
import { LastFrameFileHandler } from './handlers/last-frame-file-handler'
import { IndexFileHandler } from './handlers/index-file-handler'
+import { WaveformIndexHandler } from './handlers/waveform-index-handler'
import { BinaryFileHandler } from './handlers/binary-file-handler'
import { MainCsvFileHandler } from './handlers/main-csv-file-handler'
import { WavFileHandler } from './handlers/wav-file-handler'
@@ -60,6 +61,7 @@ const HANDLERS = {
'frame-range-parser': FrameRangeFileHandler,
'last-frame-parser': LastFrameFileHandler,
'index-parser': IndexFileHandler,
+ 'waveform-index': WaveformIndexHandler,
'binary-parser': BinaryFileHandler,
'main-csv-parser': MainCsvFileHandler,
'wav-parser': WavFileHandler,
diff --git a/apps/frontend/src/libs/file-loader/handlers/waveform-index-handler.ts b/apps/frontend/src/libs/file-loader/handlers/waveform-index-handler.ts
new file mode 100644
index 00000000..f5511edc
--- /dev/null
+++ b/apps/frontend/src/libs/file-loader/handlers/waveform-index-handler.ts
@@ -0,0 +1,16 @@
+import { BaseHandler } from './base-handler'
+import { readWaveformTimeIndex, type WaveformIndexedFile } from './waveform-time-index'
+import { serializeFileLoaderError } from '../crybin/errors'
+
+export class WaveformIndexHandler extends BaseHandler {
+ async run(): Promise {
+ try {
+ const { files, sampleRate } = this.payload as { files: WaveformIndexedFile[]; sampleRate: number }
+ const { files: data, bytesRead } = await readWaveformTimeIndex(files, sampleRate, () => this.isCancelled)
+ if (!this.isCancelled) this.postResult({ success: true, data, bytesRead })
+ } catch (error) {
+ const details = serializeFileLoaderError(error)
+ if (!this.isCancelled) this.postResult({ success: false, error: details.message, ...details })
+ } finally { this.postComplete() }
+ }
+}
diff --git a/apps/frontend/src/libs/file-loader/handlers/waveform-time-index.ts b/apps/frontend/src/libs/file-loader/handlers/waveform-time-index.ts
new file mode 100644
index 00000000..f57722c0
--- /dev/null
+++ b/apps/frontend/src/libs/file-loader/handlers/waveform-time-index.ts
@@ -0,0 +1,205 @@
+import { getNodeFsPromises } from './node-runtime'
+import { readFrameBytes, frameReadCancelled } from './crybin-frame-index'
+import { readImplicitTimeRange, validateImplicitTime, type ImplicitTimeRange } from './implicit-time'
+import { millisecondsToNanoseconds } from '@/modules/shared/data-graph/hooks/resolve-timestamp-data'
+import {
+ probeCrybinFileHeader, readCrybinFileHeader, probeV1Block,
+ V1_BLOCK_FIXED_HEADER_LENGTH, V1_MAX_HEADER_LENGTH, CrybinParseError, CRYBIN_ERROR_CODE, rebaseCrybinError
+} from '../crybin'
+
+export interface WaveformTimeRange {
+ start: number
+ end: number
+ sampleStart: number
+ sampleEnd: number
+ step: number
+}
+export interface WaveformIndexedFile extends Record {
+ filePath?: string
+ start?: number
+ end?: number
+ isComplete?: boolean
+ timeOriginNs?: string
+ waveformTimeRanges?: WaveformTimeRange[]
+}
+interface Run extends ImplicitTimeRange { sampleStart: number; clock: 'source' | 'task' | 'index' }
+interface Cursor {
+ offset: number
+ samples: number
+ previous?: ImplicitTimeRange
+}
+interface CachedScan {
+ fileId: string
+ size: number
+ mtimeMs: number
+ ctimeMs: number
+ complete: boolean
+ runs: Run[]
+ cursor: Cursor
+ bytes: number
+}
+const cache = new Map()
+const CACHE_BUDGET = 8 * 1024 * 1024
+const invalid = (message: string, offset?: number) => new CrybinParseError(CRYBIN_ERROR_CODE.INVALID_BLOCK, message,
+ { offset, crybinFormat: 'v1', crybinVersion: 1 })
+
+function cacheScan(path: string, scan: Omit) {
+ // Include per-file metadata so scans with no committed ranges cannot grow the cache without bound.
+ const bytes = 256 + scan.runs.length * 96
+ if (bytes > CACHE_BUDGET) return
+ cache.set(path, { ...scan, bytes })
+ let size = [...cache.values()].reduce((sum, item) => sum + item.bytes, 0)
+ while (size > CACHE_BUDGET) {
+ const key = cache.keys().next().value!
+ size -= cache.get(key)!.bytes
+ cache.delete(key)
+ }
+}
+
+const view = (bytes: Uint8Array) => new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength)
+
+/** Locate waveform samples from block headers. No sample payload is read or retained here. */
+export async function readWaveformTimeIndex(
+ files: WaveformIndexedFile[], sampleRate: number, cancelled = () => false
+): Promise<{ files: WaveformIndexedFile[]; bytesRead: number }> {
+ let bytesRead = 0
+ const scans: Run[][] = []
+ for (const entry of files) {
+ if (cancelled()) throw frameReadCancelled()
+ if (!entry.filePath) return { files, bytesRead }
+ const file = await getNodeFsPromises().open(entry.filePath, 'r').catch(error => {
+ if (entry.isComplete !== true && error.code === 'ENOENT') return null
+ throw error
+ })
+ if (!file) { scans.push([]); continue }
+ try {
+ const stats = await file.stat()
+ const fileId = JSON.stringify([stats.dev, stats.ino, stats.birthtimeMs, entry.start, sampleRate])
+ const cached = cache.get(entry.filePath)
+ const sameFile = cached?.fileId === fileId
+ const sameSnapshot = sameFile && stats.size === cached.size
+ && stats.mtimeMs === cached.mtimeMs && stats.ctimeMs === cached.ctimeMs
+ cache.delete(entry.filePath)
+ if (entry.isComplete === true && cached?.complete && sameSnapshot) {
+ cache.set(entry.filePath, cached)
+ scans.push(cached.runs)
+ continue
+ }
+ // The growing writer appends blocks. A shrink, replacement, or same-size edit
+ // requires a fresh scan; the checkpoint itself never includes a mutable last block.
+ const resume = sameFile && !cached.complete && (sameSnapshot || stats.size > cached.size) ? cached : undefined
+ const read = async (length: number, position: number) => {
+ const result = await readFrameBytes(file, length, position, cancelled)
+ bytesRead += result.length
+ return result
+ }
+ const initial = await read(Math.min(stats.size, 16), 0)
+ if (initial.length < 16) {
+ if (entry.isComplete === true) throw invalid('Incomplete recorded waveform header')
+ return { files, bytesRead }
+ }
+ const probe = probeCrybinFileHeader(view(initial))
+ if (probe.format !== 'v1') return { files, bytesRead }
+ if (stats.size < probe.requiredLength) {
+ if (entry.isComplete === true) throw invalid('Incomplete recorded waveform header')
+ return { files, bytesRead }
+ }
+ const header = readCrybinFileHeader(view(await read(probe.requiredLength, 0)))
+ if (header.dataLayout) return { files, bytesRead }
+ const runs = resume?.runs.map(run => ({ ...run })) ?? []
+ let previous = resume?.cursor.previous
+ let offset = resume?.cursor.offset ?? header.headerLength
+ let samples = resume?.cursor.samples ?? 0
+ let tail: { cursor: Cursor; runCount: number; lastCount?: number } | undefined
+ let incomplete = false
+ let blocks = 0
+ while (offset < stats.size) {
+ try {
+ const fixed = await read(Math.min(V1_BLOCK_FIXED_HEADER_LENGTH, stats.size - offset), offset)
+ if (fixed.length < V1_BLOCK_FIXED_HEADER_LENGTH) { incomplete = true; break }
+ const length = view(fixed).getUint32(0, true)
+ if (length < V1_BLOCK_FIXED_HEADER_LENGTH || length > V1_MAX_HEADER_LENGTH) {
+ throw invalid(`Invalid waveform block header length: ${length}`, 0)
+ }
+ if (offset + length > stats.size) { incomplete = true; break }
+ const block = probeV1Block(view(await read(length, offset)), 0, header)
+ if (!block.header || !block.totalLength || offset + block.totalLength > stats.size) { incomplete = true; break }
+ const { xCount, yCount, metadata } = block.header
+ if (xCount || metadata.firstZeroTimeSeconds !== undefined) return { files, bytesRead }
+ const step = metadata.xStep ?? header.xStep ?? 1000 / sampleRate
+ if (!Number.isFinite(step) || step <= 0) return { files, bytesRead }
+ if (entry.isComplete !== true && offset + block.totalLength === stats.size
+ && yCount > 0 && metadata.taskRelativeTimeMs === 0) {
+ incomplete = true
+ break
+ }
+ if (entry.isComplete !== true && offset + block.totalLength === stats.size) {
+ // The writer can backfill task time after publishing the payload length.
+ tail = { cursor: { offset, samples, previous }, runCount: runs.length, lastCount: runs.at(-1)?.count }
+ }
+ if (yCount) {
+ const time = readImplicitTimeRange(metadata, yCount, step) ?? { count: yCount, stepMs: step }
+ time.startMs ??= (entry.start ?? 0) + samples * step
+ let gap: boolean
+ try { gap = validateImplicitTime(previous, time) } catch (error) {
+ // The writer commits payload length before backfilling the active block's task time.
+ if (entry.isComplete !== true && offset + block.totalLength === stats.size) { incomplete = true; break }
+ throw error
+ }
+ const clock = time.sourceNs !== undefined ? 'source' : metadata.taskRelativeTimeMs !== undefined ? 'task' : 'index'
+ const last = runs.at(-1)
+ // Separate either clock's discontinuities so the range reader never merges incompatible clocks.
+ if (last && !gap && last.stepMs === step && last.clock === clock) {
+ last.count += yCount
+ } else runs.push({ ...time, sampleStart: samples, clock })
+ previous = time
+ }
+ samples += yCount
+ offset += block.totalLength
+ if (++blocks % 256 === 0) await new Promise(resolve => setTimeout(resolve, 0))
+ } catch (error) { throw rebaseCrybinError(error, offset) }
+ }
+ if (incomplete && entry.isComplete === true) throw invalid('Incomplete recorded waveform block')
+ const stableRuns = tail ? runs.slice(0, tail.runCount) : runs
+ if (tail && stableRuns.length) {
+ const last = stableRuns[stableRuns.length - 1]
+ stableRuns[stableRuns.length - 1] = { ...last, count: tail.lastCount! }
+ }
+ cacheScan(entry.filePath, {
+ fileId, size: stats.size, mtimeMs: stats.mtimeMs, ctimeMs: stats.ctimeMs,
+ complete: entry.isComplete === true, runs: stableRuns, cursor: tail?.cursor ?? { offset, samples, previous }
+ })
+ scans.push(runs)
+ } finally { await file.close() }
+ }
+ const runs = scans.flat()
+ const firstSource = runs.find(run => run.sourceNs !== undefined)
+ const origin = firstSource?.sourceNs === undefined ? undefined
+ : firstSource.sourceNs - millisecondsToNanoseconds(firstSource.startMs!)
+ let previous: Run | undefined
+ let previousEnd: number | undefined
+ const indexed = files.map((entry, index) => {
+ const ranges = scans[index].map(run => {
+ // Source/task differences can encode genuine acquisition pauses. Each clock must
+ // still be monotone; a missing-clock fallback must never silently move those samples.
+ validateImplicitTime(previous, run)
+ const start = origin !== undefined && run.sourceNs !== undefined
+ ? Number(run.sourceNs - origin) / 1000000 : run.startMs!
+ const end = start + run.count * run.stepMs
+ if (!Number.isFinite(start) || !Number.isFinite(end) || (previousEnd !== undefined && start < previousEnd - 0.000001)) {
+ throw invalid(previous && previous.clock !== run.clock
+ ? 'Waveform time is uncertain where acquisition timestamps are missing'
+ : 'Waveform acquisition times must increase without overlapping shards')
+ }
+ previous = run; previousEnd = end
+ return { start, end, sampleStart: run.sampleStart, sampleEnd: run.sampleStart + run.count, step: run.stepMs }
+ })
+ return { ...entry,
+ start: ranges[0]?.start ?? previousEnd ?? entry.start ?? 0,
+ end: ranges.at(-1)?.end ?? previousEnd ?? entry.start ?? 0,
+ waveformTimeRanges: ranges,
+ ...(origin === undefined ? {} : { timeOriginNs: origin.toString() })
+ }
+ })
+ return { files: indexed, bytesRead }
+}
diff --git a/apps/frontend/src/libs/file-loader/index.ts b/apps/frontend/src/libs/file-loader/index.ts
index 747f3d9f..b3853f01 100644
--- a/apps/frontend/src/libs/file-loader/index.ts
+++ b/apps/frontend/src/libs/file-loader/index.ts
@@ -7,6 +7,7 @@ import type { WorkerTaskCallbacks, WorkerTaskPayload } from './worker-manager'
import type { FileUnitConversionOptions } from '@/modules/shared/data-graph/utils/unit-conversion-options'
import type { FrameWindowRequest, FrameWindowResult } from './handlers/frame-range-file-handler'
import type { LastFrameOptions, LastFrameResult } from './handlers/last-frame-file-handler'
+import type { WaveformIndexedFile } from './handlers/waveform-time-index'
interface FileLoadOptions extends Record {
splitType?: string
@@ -196,6 +197,18 @@ export function loadFile(filePath: string, options: FileLoadOptions = {}) {
})
}
+export function loadWaveformTimeIndex(files: WaveformIndexedFile[], sampleRate: number, perfTraceId?: string) {
+ return new Promise((resolve, reject) => {
+ startWorkerTask>('waveform-index', { files, sampleRate }, {
+ onResult: result => result.success ? resolve(result.data ?? [])
+ : reject(createFileLoaderError(result.error || 'Waveform time index failed', result)),
+ onComplete: () => reject(new Error('Waveform time index completed without a result')),
+ onCancelled: () => reject(new DOMException('Waveform time index cancelled', 'AbortError')),
+ onError: reject
+ }, perfTraceId)
+ })
+}
+
export function loadWaveformByRange(filePath: string, start: number, end: number, options: FileLoadOptions = {}) {
return new Promise>((resolve, reject) => {
if (!filePath) {
diff --git a/apps/frontend/src/libs/file-loader/worker-manager.ts b/apps/frontend/src/libs/file-loader/worker-manager.ts
index f4cbfdae..a32f4544 100644
--- a/apps/frontend/src/libs/file-loader/worker-manager.ts
+++ b/apps/frontend/src/libs/file-loader/worker-manager.ts
@@ -18,6 +18,7 @@ export type WorkerTaskPayload = Record & { filePath?: string }
export interface WorkerTaskCallbacks {
onResult?: (_result: TResult) => void
onComplete?: (_taskId: string) => void
+ onCancelled?: (_taskId: string) => void
onError?: (_error: Error) => void
}
@@ -166,9 +167,11 @@ class WorkerManager {
}
if (type === 'cancelled') {
+ const callbacks = this.taskCallbacks.get(taskId)
this.taskCallbacks.delete(taskId)
this.taskFilePaths.delete(taskId)
this.settleCancellation(taskId)
+ callbacks?.onCancelled?.(taskId)
return
}
diff --git a/apps/frontend/src/modules/shared/data-graph/components/views/waveform/__tests__/use-waveform-data.test.ts b/apps/frontend/src/modules/shared/data-graph/components/views/waveform/__tests__/use-waveform-data.test.ts
index e44bec3f..6db7923c 100644
--- a/apps/frontend/src/modules/shared/data-graph/components/views/waveform/__tests__/use-waveform-data.test.ts
+++ b/apps/frontend/src/modules/shared/data-graph/components/views/waveform/__tests__/use-waveform-data.test.ts
@@ -97,6 +97,150 @@ function setSingleIndexFile() {
}
describe('useWaveformData', () => {
+ it.each(['LEGACY', 'WAV_ONLY'])('seeks directly into a file-internal acquisition gap timeline using the indexed sample positions (%s)', async storage => {
+ const origin = '1794326399250123456'
+ mocks.indexFilesDataMap.value = { 'series-1': [{ filePath: 'gapped.crybin', start: 0, end: 170000,
+ timeOriginNs: origin, isComplete: true, waveformTimeRanges: [
+ { start: 0, end: 40000, sampleStart: 0, sampleEnd: 40000, step: 1 },
+ { start: 130000, end: 170000, sampleStart: 40000, sampleEnd: 80000, step: 1 }
+ ] }] }
+ mocks.loadWaveformByRange.mockImplementation(async (_path, start, end) => ({ data: new Float64Array(end - start) }))
+ let interval = { start: 140000, end: 150000 }
+ const onDataLoaded = vi.fn()
+ const api = createApi([{ ...persistedRenderData, resultStorageMode: storage }], { lazy: true, getIntervalFn: () => interval, onDataLoaded })
+ await api.loadGraphicData()
+ expect(mocks.loadWaveformByRange.mock.calls.map(([, start, end]) => [start, end])).toEqual([[40000, 70000]])
+ expect(onDataLoaded.mock.calls[0][1]).toMatchObject({ start: 130000, timeOriginNs: origin })
+ interval = { start: 5000, end: 15000 }
+ await api.loadGraphicData()
+ expect(mocks.loadWaveformByRange.mock.lastCall.slice(1, 3)).toEqual([0, 25000])
+ expect(onDataLoaded.mock.lastCall[1]).toMatchObject({ start: 0, timeOriginNs: origin, isAppend: false })
+ api.dispose()
+ })
+
+ it.each(['LEGACY', 'WAV_ONLY'])('reloads an evicted early viewport even when it lies inside the last oversized request (%s)', async storage => {
+ mocks.indexFilesDataMap.value = { 'series-1': [{ filePath: 'long.crybin', start: 0, end: 120000, isComplete: true }] }
+ mocks.loadWaveformByRange.mockImplementation(async (_path, start, end) => ({ data: new Float64Array(end - start) }))
+ let interval = { start: 0, end: 120000 }
+ const api = createApi([{ ...persistedRenderData, resultStorageMode: storage }], { lazy: true, getIntervalFn: () => interval })
+ await api.loadGraphicData()
+ mocks.loadWaveformByRange.mockClear()
+ interval = { start: 35000, end: 45000 }
+ await api.loadGraphicData()
+ expect(mocks.loadWaveformByRange.mock.calls.map(([, start, end]) => [start, end])).toEqual([[25000, 55000]])
+ api.dispose()
+ })
+
+ it.each(['LEGACY', 'WAV_ONLY'])('plays through indexed gaps without reading nominal samples or waiting for nonexistent data (%s)', async storage => {
+ mocks.indexFilesDataMap.value = { 'series-1': [{ filePath: 'gap.crybin', start: 0, end: 140000,
+ isComplete: true, timeOriginNs: '1794326399250123456', waveformTimeRanges: [
+ { start: 0, end: 40000, sampleStart: 0, sampleEnd: 40000, step: 1 },
+ { start: 130000, end: 140000, sampleStart: 40000, sampleEnd: 50000, step: 1 }
+ ] }] }
+ mocks.loadWaveformByRange.mockImplementation(async (_path, start, end) => ({ data: new Float64Array(end - start) }))
+ const api = createApi([{ ...persistedRenderData, resultStorageMode: storage }], { lazy: true, getIntervalFn: () => ({ start: 70000, end: 80000 }) })
+ await api.loadGraphicData()
+ mocks.playbackRunning.value = true
+ await api.loadGraphicData({ playback: true, playbackTime: 75000 })
+ expect(mocks.loadWaveformByRange).not.toHaveBeenCalled()
+ api.dispose()
+ })
+
+ it('keeps indexed WAV_ONLY runs atomic when a later range fails', async () => {
+ const origin = '1794326399250123456'
+ mocks.indexFilesDataMap.value = { 'series-1': [{ filePath: 'internal.crybin', start: 0, end: 3000,
+ timeOriginNs: origin, isComplete: true, waveformTimeRanges: [
+ { start: 0, end: 1000, sampleStart: 0, sampleEnd: 1000, step: 1 },
+ { start: 2000, end: 3000, sampleStart: 1000, sampleEnd: 2000, step: 1 }
+ ] }] }
+ mocks.loadWaveformByRange
+ .mockResolvedValueOnce({ data: new Float64Array(1000) })
+ .mockResolvedValueOnce({ data: [] })
+ const onDataLoaded = vi.fn()
+ const api = createApi([wavOnlyRenderData], { lazy: true,
+ getIntervalFn: () => ({ start: 500, end: 2500 }), onDataLoaded })
+ await api.loadGraphicData()
+ expect(onDataLoaded).not.toHaveBeenCalled()
+ mocks.loadWaveformByRange.mockImplementation(async (_path, start, end) => ({ data: new Float64Array(end - start) }))
+ await api.loadGraphicData()
+ expect(onDataLoaded.mock.calls.map(([, file]) => [file.start, file.step, file.isAppend, file.timeOriginNs]))
+ .toEqual([[0, 1, false, origin], [2000, 1, true, origin]])
+ expect(mocks.loadWaveformByRange.mock.calls.slice(-2).map(([, start, end]) => [start, end]))
+ .toEqual([[0, 1000], [1000, 2000]])
+ api.dispose()
+ })
+
+ it.each(['LEGACY', 'WAV_ONLY'])('does not require the previous shard at an indexed gap boundary (%s)', async storage => {
+ const coordinator = createPlaybackCoordinator()
+ mocks.playbackCoordinator = coordinator
+ mocks.playbackRunning.value = true
+ mocks.playbackTime.value = 75000
+ mocks.indexFilesDataMap.value = { 'series-1': [{ filePath: 'gaps.crybin', start: 0, end: 140000,
+ isComplete: true, waveformTimeRanges: [
+ { start: 0, end: 40000, sampleStart: 0, sampleEnd: 40000, step: 1 },
+ { start: 130000, end: 140000, sampleStart: 40000, sampleEnd: 50000, step: 1 }
+ ] }] }
+ mocks.loadWaveformByRange.mockImplementation(async (_path, start, end) => ({ data: new Float64Array(end - start) }))
+ const api = createApi([{ ...persistedRenderData, resultStorageMode: storage }], {
+ lazy: true, getIntervalFn: () => ({ start: 70000, end: 80000 }) })
+ await api.loadGraphicData()
+ mocks.playbackTime.value = 40000
+ await coordinator.prepare(40000)
+ expect(coordinator.errors.value.size).toBe(0)
+ expect(mocks.loadWaveformByRange).not.toHaveBeenCalled()
+ api.dispose()
+ })
+
+ it.each(['LEGACY', 'WAV_ONLY'])('waits for indexed %s active samples beyond the current timestamp frontier', async storage => {
+ vi.useFakeTimers()
+ const coordinator = createPlaybackCoordinator()
+ mocks.playbackCoordinator = coordinator
+ mocks.playbackRunning.value = true
+ const file = { filePath: 'active.crybin', start: 0, end: 1000, isComplete: false,
+ waveformTimeRanges: [{ start: 0, end: 1000, sampleStart: 0, sampleEnd: 1000, step: 1 }] }
+ mocks.indexFilesDataMap.value = { 'series-1': [file] }
+ mocks.loadWaveformByRange.mockImplementation(async (_path, start, end) => ({ data: new Float64Array(end - start) }))
+ const onDataLoaded = vi.fn()
+ const api = createApi([{ ...persistedRenderData, resultStorageMode: storage }], {
+ lazy: true, getIntervalFn: () => ({ start: 1300, end: 1600 }), onDataLoaded
+ })
+ await api.loadGraphicData({ playback: true, playbackTime: 0 })
+ mocks.playbackTime.value = 1500
+ const settled = vi.fn()
+ const pending = coordinator.prepare(1500).then(settled)
+ await vi.advanceTimersByTimeAsync(0)
+ expect(settled).not.toHaveBeenCalled()
+ file.end = 2000
+ file.waveformTimeRanges[0].end = 2000
+ file.waveformTimeRanges[0].sampleEnd = 2000
+ await vi.advanceTimersByTimeAsync(250)
+ await pending
+ expect(coordinator.errors.value.size).toBe(0)
+ expect(onDataLoaded.mock.calls.some(([data, frame]) => (
+ frame.start <= 1500 && frame.start + data.yValues.length * frame.step > 1500
+ ))).toBe(true)
+ api.dispose()
+ })
+
+ it('does not advance prefetch on another series while an indexed legacy window is still growing', async () => {
+ mocks.indexFilesDataMap.value = {
+ 'series-1': [{ filePath: 'active.crybin', start: 0, end: 1000, isComplete: false,
+ waveformTimeRanges: [{ start: 0, end: 1000, sampleStart: 0, sampleEnd: 1000, step: 1 }] }],
+ 'series-2': [{ filePath: 'complete.crybin', start: 0, end: 10000, isComplete: true }]
+ }
+ mocks.loadWaveformByRange.mockImplementation(async (_path, start, end) => ({ data: new Float64Array(end - start) }))
+ const api = createApi([persistedRenderData, { ...persistedRenderData, id: 'series-2' }], {
+ lazy: true, getIntervalFn: () => ({ start: 2000, end: 2100 })
+ })
+ await api.loadGraphicData()
+ expect(mocks.loadWaveformByRange.mock.calls.map(([path]) => path)).toEqual(['complete.crybin'])
+ mocks.loadWaveformByRange.mockClear()
+ mocks.playbackRunning.value = true
+ await api.loadGraphicData({ playback: true, playbackTime: 2000 })
+ expect(mocks.loadWaveformByRange).not.toHaveBeenCalled()
+ api.dispose()
+ })
+
beforeEach(() => {
mocks.playbackCoordinator = undefined
vi.clearAllMocks()
@@ -116,7 +260,8 @@ describe('useWaveformData', () => {
mocks.logPerf.mockReset()
})
- it.each(['LEGACY', 'WAV_ONLY'])('loads projected cross-record viewports with source coordinates (%s)', async storage => {
+ it.each([{ storage: 'LEGACY', indexed: false }, { storage: 'WAV_ONLY', indexed: false },
+ { storage: 'LEGACY', indexed: true }, { storage: 'WAV_ONLY', indexed: true }])('loads projected cross-record viewports with source coordinates ($storage, indexed=$indexed)', async ({ storage, indexed }) => {
const origin = 1793955000000000123n
const origins = { a: origin, b: origin + 10000000000n }
const renderDatas = ['a', 'b'].map(id => ({
@@ -127,6 +272,12 @@ describe('useWaveformData', () => {
{ filePath: `${id}-1.crybin`, start: 0, end: 60000, isComplete: true },
{ filePath: `${id}-2.crybin`, start: 60000, end: 120000, isComplete: true }
]]))
+ if (indexed) {
+ for (const id of ['a', 'b']) {
+ for (const file of mocks.indexFilesDataMap.value[id]) Object.assign(file, { timeOriginNs: origins[id].toString(),
+ waveformTimeRanges: [{ start: file.start, end: file.end, sampleStart: 0, sampleEnd: 60000, step: 1 }] })
+ }
+ }
mocks.loadWaveformByRange.mockImplementation(async (path, start, end) => ({
data: new Float64Array(end - start),
sourceTimestampNanos: (origins[path[0]] + BigInt((path.includes('-2') ? 60000 : 0) + start) * 1000000n).toString()
diff --git a/apps/frontend/src/modules/shared/data-graph/components/views/waveform/use-waveform-data.ts b/apps/frontend/src/modules/shared/data-graph/components/views/waveform/use-waveform-data.ts
index 8f139a8f..4156bc84 100644
--- a/apps/frontend/src/modules/shared/data-graph/components/views/waveform/use-waveform-data.ts
+++ b/apps/frontend/src/modules/shared/data-graph/components/views/waveform/use-waveform-data.ts
@@ -37,6 +37,7 @@ export type WaveformIndexFiles = Record>
export interface WaveformDataOptions {
@@ -47,6 +48,7 @@ export interface WaveformDataOptions {
getIntervalFn?: () => { start: number; end: number }
/** Source X=0 relative to the common chart origin, in milliseconds. */
getSeriesTimeOffsetFn?: (_seriesId: string | number) => number | null | undefined
+ getTimeOriginNsFn?: () => bigint | undefined
onIndexLoaded?: (_indexFiles: WaveformIndexFiles) => void
onSeriesDataComplete?: (_seriesId: string | number, _complete: boolean) => void
}
@@ -137,15 +139,26 @@ export function useWaveformData(options: WaveformDataOptions) {
onError,
getIntervalFn,
getSeriesTimeOffsetFn,
+ getTimeOriginNsFn,
onIndexLoaded,
onSeriesDataComplete
} = options
- const { indexFilesDataMap, loadIndexFilesData } = useIndexFilesData({ config })
+ const { indexFilesDataMap, loadIndexFilesData } = useIndexFilesData({ config, waveformTime: true })
const loadedCompleteFilePaths = new Set()
// Cache source coordinates so discovering an origin never makes cached coverage stale.
const loadedRangeMap = new Map()
const seriesTimeOffsets = ref>({})
+ const hasTimeIndex = (seriesId: string | number) => {
+ const files = indexFilesDataMap.value?.[seriesId]
+ return Boolean(files?.length && files.every(file => Array.isArray(file.waveformTimeRanges)))
+ }
const getSeriesTimeOffset = (seriesId: string | number) => {
+ const origin = indexFilesDataMap.value?.[seriesId]?.find(file => file.timeOriginNs)?.timeOriginNs
+ if (origin && hasTimeIndex(seriesId)) {
+ const origins = Object.values(indexFilesDataMap.value || {}).flatMap(files => files[0]?.timeOriginNs ? [BigInt(files[0].timeOriginNs)] : [])
+ const commonOrigin = getTimeOriginNsFn?.() ?? origins.reduce((min, value) => value < min ? value : min, BigInt(origin))
+ return Number(BigInt(origin) - commonOrigin) / 1000000
+ }
// Depend on the refreshed snapshot even when the chart's origin map is not reactive.
const previous = seriesTimeOffsets.value[String(seriesId)] ?? 0
const offset = getSeriesTimeOffsetFn?.(seriesId) ?? previous
@@ -155,6 +168,9 @@ export function useWaveformData(options: WaveformDataOptions) {
sourceStart?: number
sourceEnd?: number
timeOffsetMs?: number
+ sampleStart?: number
+ sampleEnd?: number
+ step?: number
}
const getIndexFiles = (seriesId: string | number): IndexedFile[] => {
const files = indexFilesDataMap.value?.[seriesId] || []
@@ -163,9 +179,22 @@ export function useWaveformData(options: WaveformDataOptions) {
return files.map(file => ({ ...file, sourceStart: file.start, sourceEnd: file.end,
timeOffsetMs: offset, start: file.start + offset, end: file.end + offset }))
}
+ const getIndexedActiveEnd = (seriesId: string | number) => hasTimeIndex(seriesId)
+ ? getIndexFiles(seriesId).find(file => file.isComplete === false)?.end
+ : undefined
+ const isPendingIndexedRange = (seriesId: string | number, end: number) => {
+ const frontier = getIndexedActiveEnd(seriesId)
+ return frontier !== undefined && end > frontier
+ }
const getProjectedIndexFiles = () => Object.fromEntries(
Object.keys(indexFilesDataMap.value || {}).map(seriesId => [seriesId, getIndexFiles(seriesId)])
)
+ const getReadFiles = (seriesId: string | number): IndexedFile[] => getIndexFiles(seriesId).flatMap(file => (
+ file.waveformTimeRanges ? file.waveformTimeRanges.map(range => ({
+ ...file, ...range, sourceStart: range.start, sourceEnd: range.end,
+ start: range.start + (file.timeOffsetMs ?? 0), end: range.end + (file.timeOffsetMs ?? 0)
+ })) : [file]
+ ))
const getSourceFile = (file: IndexedFile) => {
if (!file.timeOffsetMs) return file
const { sourceStart, sourceEnd, timeOffsetMs: _offset, ...metadata } = file
@@ -368,30 +397,16 @@ export function useWaveformData(options: WaveformDataOptions) {
return fileList
}
- const loadSingleFileWithInterval = async (item, interval, allAppend, requestGeneration) => {
- // 确保访问 .value 属性(因为是 ref)
- const fileList = getIndexFiles(item.id)
- if (!fileList || fileList.length === 0) {
- if (!isTemporaryIndexSource(item)) {
- console.warn(`文件列表为空: ${item.id}`, indexFilesDataMap.value)
- }
- return false
- }
-
- // 找出在区间内的文件
- const relevantFiles = fileList.filter(file => {
- // 检查文件区间 [file.start, file.end) 是否与显示区间 [interval.start, interval.end) 有交集
- return file.start < interval.end && file.end > interval.start
- })
+ const getSampleRanges = (item, interval) => {
// Bound each contiguous allocation to 16 MiB even for Float64 waveform files.
// Commit chunks through the existing append path instead of concatenating a large seek window.
const maxSamples = 2 * 1024 * 1024
- const ranges = relevantFiles.flatMap(file => {
+ return getReadFiles(item.id).filter(file => file.start < interval.end && file.end > interval.start).flatMap(file => {
const start = Math.max(interval.start, file.start)
const end = Math.min(interval.end, file.end)
- const samplesPerMs = item.sampleRate / 1000
- const startSamples = Math.floor((start - file.start) * samplesPerMs)
- const endSamples = Math.floor((end - file.start) * samplesPerMs)
+ const samplesPerMs = file.step ? 1 / file.step : item.sampleRate / 1000
+ const startSamples = (file.sampleStart ?? 0) + Math.floor((start - file.start) * samplesPerMs)
+ const endSamples = Math.min(file.sampleEnd ?? Infinity, (file.sampleStart ?? 0) + Math.floor((end - file.start) * samplesPerMs))
const key = getLoadedFileKey(item.id, file.filePath)
const range = { file, start, end, key, startSamples, endSamples }
if (!Number.isFinite(endSamples - startSamples) || endSamples - startSamples <= maxSamples) return [range]
@@ -406,17 +421,76 @@ export function useWaveformData(options: WaveformDataOptions) {
}
return chunks
})
+ }
+
+ const clearSeriesCoverage = seriesId => {
+ getIndexFiles(seriesId).forEach(file => loadedRangeMap.delete(getLoadedFileKey(seriesId, file.filePath)))
+ }
+
+ const trimSeriesCoverage = (seriesId, loadedEnd, offset = 0) => {
+ if (!needLazyLoad.value) return
+ // The renderer evicts old samples from its sixty-second buffer.
+ const retainedStart = loadedEnd - offset - WAVEFORM_INTERVAL_MAX_TIME
+ getIndexFiles(seriesId).forEach(file => {
+ const key = getLoadedFileKey(seriesId, file.filePath)
+ const retained = (loadedRangeMap.get(key) || [])
+ .filter(range => range.end > retainedStart)
+ .map(range => ({ ...range, start: Math.max(range.start, retainedStart) }))
+ if (retained.length) loadedRangeMap.set(key, retained)
+ else loadedRangeMap.delete(key)
+ })
+ }
+
+ const mapRangeResponse = (file: IndexedFile, item, startSamples: number,
+ res: Awaited>>, baseFileData) => {
+ const step = file.step ?? 1000 / item.sampleRate
+ const start = (file.sourceStart ?? file.start) + (startSamples - (file.sampleStart ?? 0)) * step
+ let explicitX = res.xValues
+ const timeOriginNs = file.waveformTimeRanges ? file.timeOriginNs
+ : explicitX?.length ? res.timeOriginNs ?? baseFileData.timeOriginNs
+ : resolveTimeOriginNs(res.sourceTimestampNanos, start) ?? res.timeOriginNs ?? baseFileData.timeOriginNs
+ if (explicitX?.length && file.waveformTimeRanges && timeOriginNs && res.timeOriginNs) {
+ const shift = Number(BigInt(res.timeOriginNs) - BigInt(timeOriginNs)) / 1000000
+ if (shift) explicitX = Float64Array.from(explicitX, value => value + shift)
+ }
+ const data: DataGraphSeriesData = {
+ yValues: res.data,
+ ...(explicitX?.length ? { xValues: explicitX } : {}),
+ ...(timeOriginNs ? { timeOriginNs } : {})
+ }
+ return { ...baseFileData, ...res, timeOriginNs, start, step, data }
+ }
+
+ const loadSingleFileWithInterval = async (item, interval, allAppend, requestGeneration) => {
+ // 确保访问 .value 属性(因为是 ref)
+ const fileList = getReadFiles(item.id)
+ if (!fileList || fileList.length === 0) {
+ if (!isTemporaryIndexSource(item)) {
+ console.warn(`文件列表为空: ${item.id}`, indexFilesDataMap.value)
+ }
+ return false
+ }
+
+ // 找出在区间内的文件
+ const relevantFiles = fileList.filter(file => {
+ // 检查文件区间 [file.start, file.end) 是否与显示区间 [interval.start, interval.end) 有交集
+ return file.start < interval.end && file.end > interval.start
+ })
+ // Indexed holes are known absence of samples, not unfinished reads.
+ const pending = isPendingIndexedRange(item.id, interval.end)
+ if (!relevantFiles.length && hasTimeIndex(item.id)) return !pending
+ const ranges = getSampleRanges(item, interval)
const isCompleteRangeCovered = ranges.length > 0 && ranges.every(range => (
range.file.isComplete === true
&& isRangeCovered(range.key, range.start, range.end, range.file.timeOffsetMs)
))
if (isCompleteRangeCovered) {
- return true
+ return !pending
}
// 对每个相关文件,计算加载范围并创建加载任务
let hasEmitted = allAppend
let hasEmittedData = false
- let hasAllData = ranges.length > 0
+ let hasAllData = ranges.length > 0 && !pending
for (const range of ranges) {
if (!isRangeRequestCurrent(requestGeneration)) {
return false
@@ -430,7 +504,7 @@ export function useWaveformData(options: WaveformDataOptions) {
}
// 转换为采样点
- const samplesPerMs = item.sampleRate / 1000
+ const samplesPerMs = file.step ? 1 / file.step : item.sampleRate / 1000
const { startSamples, endSamples } = range
if (endSamples <= startSamples) {
@@ -459,30 +533,12 @@ export function useWaveformData(options: WaveformDataOptions) {
// A complete integer sample range covers its requested window, including rounding at the edge.
const loadedEnd = fullyLoaded ? intersectEnd : Math.min(intersectEnd, intersectStart + waveformData.length / samplesPerMs)
hasAllData = hasAllData && fullyLoaded
- const dataStart = (file.sourceStart ?? file.start) + startSamples / samplesPerMs
- const explicitX = res.xValues
- const timeOriginNs = explicitX?.length ? res.timeOriginNs ?? baseFileData.timeOriginNs
- : resolveTimeOriginNs(res.sourceTimestampNanos, dataStart) ?? res.timeOriginNs ?? baseFileData.timeOriginNs
- const data: DataGraphSeriesData = {
- yValues: waveformData,
- ...(explicitX?.length ? { xValues: explicitX } : {}),
- ...(timeOriginNs ? { timeOriginNs } : {})
- }
-
- // 准备文件数据
- const fileData = {
- ...baseFileData,
- ...res,
- ...(timeOriginNs ? { timeOriginNs } : {}),
- start: dataStart,
- step: 1000.0 / item.sampleRate,
- data,
- isAppend: hasEmitted
- }
+ const fileData = { ...mapRangeResponse(file, item, startSamples, res, baseFileData), isAppend: hasEmitted }
+ const data = fileData.data
// 调用回调函数
if (!hasEmitted) {
- fileList.forEach(entry => loadedRangeMap.delete(getLoadedFileKey(item.id, entry.filePath)))
+ clearSeriesCoverage(item.id)
}
if (onDataLoaded) {
onDataLoaded(data, fileData)
@@ -490,17 +546,7 @@ export function useWaveformData(options: WaveformDataOptions) {
hasEmitted = true
hasEmittedData = true
markRangeLoaded(loadedFileKey, intersectStart, loadedEnd, file.timeOffsetMs)
- // The lazy waveform renderer evicts samples older than its sixty-second buffer.
- // Keep readiness aligned with retained samples so backward seeks reload evicted data.
- const retainedStart = loadedEnd - (file.timeOffsetMs ?? 0) - WAVEFORM_INTERVAL_MAX_TIME
- fileList.forEach(entry => {
- const key = getLoadedFileKey(item.id, entry.filePath)
- const retained = (loadedRangeMap.get(key) || [])
- .filter(range => range.end > retainedStart)
- .map(range => ({ ...range, start: Math.max(range.start, retainedStart) }))
- if (retained.length) loadedRangeMap.set(key, retained)
- else loadedRangeMap.delete(key)
- })
+ trimSeriesCoverage(item.id, loadedEnd, file.timeOffsetMs)
} catch (error) {
if (!isRangeRequestCurrent(requestGeneration)) {
return false
@@ -556,6 +602,7 @@ export function useWaveformData(options: WaveformDataOptions) {
&&
latestInterval.value
&& isContainInterval(displayInterval, latestInterval.value, 0.2)
+ && isLegacyIntervalCovered(displayInterval, renderDatas)
&& !hasActiveFileInView
) {
return
@@ -576,6 +623,12 @@ export function useWaveformData(options: WaveformDataOptions) {
}
}
+ const isLegacyIntervalCovered = (interval, renderDatas) => renderDatas.every(item =>
+ !isPendingIndexedRange(item.id, interval.end) && getReadFiles(item.id)
+ .filter(file => file.start < interval.end && file.end > interval.start)
+ .every(file => isRangeCovered(getLoadedFileKey(item.id, file.filePath),
+ Math.max(interval.start, file.start), Math.min(interval.end, file.end), file.timeOffsetMs)))
+
const loadDataByPlaybackTime = async (
requestGeneration,
poll,
@@ -603,7 +656,9 @@ export function useWaveformData(options: WaveformDataOptions) {
let requestInterval
let nextInterval
let allAppend = true
- if (!(interval.start <= currentTime && interval.end >= currentTime)) {
+ const step = Math.max(...renderDatas.map(item => 1000 / item.sampleRate))
+ if (!(interval.start <= currentTime && interval.end >= currentTime)
+ || !isLegacyIntervalCovered({ start: currentTime, end: currentTime + step }, renderDatas)) {
allAppend = false
requestInterval = { start: currentTime, end: currentTime + 5000 }
nextInterval = requestInterval
@@ -632,26 +687,16 @@ export function useWaveformData(options: WaveformDataOptions) {
}
}
- const getWavRanges = requestInterval => {
- return (graphConfig.value?.renderDatas || [])
- .filter(isWavOnlyRenderData)
- .flatMap(item => (getIndexFiles(item.id))
- .filter(file => file.start < requestInterval.end && file.end > requestInterval.start)
- .map(file => ({
- item,
- file,
- start: Math.max(requestInterval.start, file.start),
- end: Math.min(requestInterval.end, file.end),
- key: getLoadedFileKey(item.id, file.filePath)
- })))
- }
+ const getWavRanges = requestInterval => (graphConfig.value?.renderDatas || [])
+ .filter(isWavOnlyRenderData)
+ .flatMap(item => getSampleRanges(item, requestInterval).map(range => ({ ...range, item })))
- const getRequiredWavIntervals = (item, interval) => getIndexFiles(item.id)
+ const getRequiredWavIntervals = (item, interval) => getReadFiles(item.id)
.filter(file => file.start < interval.end && file.end > interval.start)
.map(file => ({ file, start: Math.max(interval.start, file.start), end: Math.min(interval.end, file.end) }))
const getContinuousWavCoverage = (item, interval, isCovered) => {
- if (hasSeriesTimeOffsets()) {
+ if (hasSeriesTimeOffsets() || hasTimeIndex(item.id)) {
return getRequiredWavIntervals(item, interval).every(({ file, start, end }) => isCovered(file, start, end))
}
let coveredUntil = interval.start
@@ -675,7 +720,7 @@ export function useWaveformData(options: WaveformDataOptions) {
if (hasSeriesTimeOffsets()) return false
return (graphConfig.value?.renderDatas || [])
.filter(isWavOnlyRenderData)
- .some(item => !(getIndexFiles(item.id)).some(file => (
+ .some(item => !hasTimeIndex(item.id) && !(getIndexFiles(item.id)).some(file => (
file.start < requestInterval.end && file.end > requestInterval.start
)))
}
@@ -688,100 +733,62 @@ export function useWaveformData(options: WaveformDataOptions) {
)))
)
- const getMappedWavLoadedEnd = (interval, getRanges) => {
+ // Known timestamp gaps advance the clock without waiting for nonexistent samples.
+ // Sources without a timestamp index still require continuous coverage.
+ const getWavCoverageEnd = (interval, getRanges) => {
let loadedEnd = interval.end
for (const item of (graphConfig.value?.renderDatas || []).filter(isWavOnlyRenderData)) {
+ const mapped = hasSeriesTimeOffsets() || hasTimeIndex(item.id)
+ let frontier = interval.start
for (const required of getRequiredWavIntervals(item, interval)) {
+ if (!mapped && required.start > frontier) break
let coveredUntil = required.start
const ranges = getRanges(item, required.file).slice().sort((left, right) => left.start - right.start)
for (const range of ranges) {
if (range.start > coveredUntil || coveredUntil >= required.end) break
if (range.end > coveredUntil) coveredUntil = Math.min(required.end, range.end)
}
- if (coveredUntil < required.end) loadedEnd = Math.min(loadedEnd, coveredUntil)
+ frontier = Math.max(frontier, coveredUntil)
+ if (coveredUntil < required.end) {
+ loadedEnd = Math.min(loadedEnd, coveredUntil)
+ break
+ }
+ }
+ if (!mapped) loadedEnd = Math.min(loadedEnd, frontier)
+ const frontierEnd = getIndexedActiveEnd(item.id)
+ if (frontierEnd !== undefined && frontierEnd < interval.end) {
+ loadedEnd = Math.min(loadedEnd, Math.max(interval.start, frontierEnd))
}
}
return loadedEnd
}
- const getWavLoadedEnd = interval => {
- if (hasSeriesTimeOffsets()) {
- return getMappedWavLoadedEnd(interval, (item, file) => getCachedRanges(getLoadedFileKey(item.id, file.filePath), file.timeOffsetMs))
- }
- const loadedEnds = (graphConfig.value?.renderDatas || [])
- .filter(isWavOnlyRenderData)
- .map(item => {
- let loadedUntil = interval.start
- const relevantFiles = (getIndexFiles(item.id))
- .filter(file => file.start < interval.end && file.end > interval.start)
- .sort((left, right) => left.start - right.start)
-
- for (const file of relevantFiles) {
- const start = Math.max(interval.start, file.start)
- const end = Math.min(interval.end, file.end)
- const loadedRange = getCachedRanges(getLoadedFileKey(item.id, file.filePath), file.timeOffsetMs)
- .find(range => range.start <= start && range.end > start)
- if (start > loadedUntil || !loadedRange) {
- break
- }
- loadedUntil = Math.max(loadedUntil, Math.min(end, loadedRange.end))
- if (loadedUntil < end) {
- break
- }
- }
- return loadedUntil
- })
- return loadedEnds.length ? Math.min(...loadedEnds) : interval.start
- }
+ const getWavLoadedEnd = interval => getWavCoverageEnd(interval,
+ (item, file) => getCachedRanges(getLoadedFileKey(item.id, file.filePath), file.timeOffsetMs))
const getLoadedWavRangeEnd = (range, waveformData) => {
const sampleCount = Array.isArray(waveformData) || isArrayBufferViewWithLength(waveformData)
- ? waveformData.length
- : 0
- return Math.min(range.end, range.start + sampleCount * 1000 / range.item.sampleRate)
+ ? waveformData.length : 0
+ return sampleCount >= range.endSamples - range.startSamples ? range.end
+ : Math.min(range.end, range.start + sampleCount * (range.file.step ?? 1000 / range.item.sampleRate))
}
- const getStagedWavLoadedEnd = (staged, interval) => {
- if (hasSeriesTimeOffsets()) {
- return getMappedWavLoadedEnd(interval, (item, file) => staged
- .filter(entry => entry.range.item.id === item.id && entry.range.file.filePath === file.filePath)
- .map(entry => ({ start: entry.range.start, end: entry.loadedEnd })))
- }
- const loadedEnds = (graphConfig.value?.renderDatas || [])
- .filter(isWavOnlyRenderData)
- .map(item => {
- let loadedUntil = interval.start
- const entries = staged
- .filter(entry => entry.range.item.id === item.id)
- .sort((left, right) => left.range.start - right.range.start)
-
- for (const entry of entries) {
- const start = Math.max(interval.start, entry.range.start)
- const end = Math.min(interval.end, entry.loadedEnd)
- if (start > loadedUntil || end <= loadedUntil) {
- break
- }
- loadedUntil = Math.max(loadedUntil, end)
- if (loadedUntil < Math.min(interval.end, entry.range.end)) {
- break
- }
- }
- return loadedUntil
- })
- return loadedEnds.length ? Math.min(...loadedEnds) : interval.start
- }
+ const getStagedWavLoadedEnd = (staged, interval) => getWavCoverageEnd(interval,
+ (item, file) => staged
+ .filter(entry => entry.range.item.id === item.id && entry.range.file.filePath === file.filePath)
+ .map(entry => ({ start: entry.range.start, end: entry.loadedEnd })))
const trimStagedWavEntries = (staged, loadedEnd) => {
return staged.flatMap(entry => {
const sampleCount = Math.min(
entry.data.yValues.length,
- Math.floor((loadedEnd - entry.range.start) * entry.range.item.sampleRate / 1000 + 1e-6)
+ Math.floor((loadedEnd - entry.range.start) / entry.fileData.step + 1e-6)
)
if (sampleCount <= 0) {
return []
}
const yValues = entry.data.yValues.slice(0, sampleCount)
- const committedEnd = entry.range.start + sampleCount * 1000 / entry.range.item.sampleRate
+ const committedEnd = entry.range.start + sampleCount * entry.fileData.step
return [{
...entry,
loadedEnd: committedEnd,
@@ -809,22 +816,21 @@ export function useWaveformData(options: WaveformDataOptions) {
}
const ranges = getWavRanges(requestInterval)
if (ranges.length === 0) {
- return false
+ const end = getStagedWavLoadedEnd([], requestInterval)
+ if (end <= requestInterval.start) return false
+ latestWavInterval.value = { ...nextInterval, end }
+ return true
}
for (const range of ranges) {
if (!isWavRequestCurrent(requestGeneration, requestEpoch)) {
return false
}
- const { item, file, start, end } = range
+ const { item, file, start, startSamples, endSamples } = range
if (!Number.isFinite(item.sampleRate)) {
console.warn('sampleRate is not finite', file.filePath, item.sampleRate)
return false
}
- const sampleRate = Number(item.sampleRate)
- const fileStart = Number(file.start)
- const startSamples = Math.floor((start - fileStart) * sampleRate / 1000)
- const endSamples = Math.floor((end - fileStart) * sampleRate / 1000)
if (endSamples <= startSamples) {
return false
}
@@ -845,23 +851,8 @@ export function useWaveformData(options: WaveformDataOptions) {
if (loadedEnd <= start) {
return false
}
- const dataStart = Number(file.sourceStart ?? file.start) + startSamples * 1000 / sampleRate
- const timeOriginNs = res.xValues?.length ? res.timeOriginNs ?? baseFileData.timeOriginNs
- : resolveTimeOriginNs(res.sourceTimestampNanos, dataStart) ?? res.timeOriginNs ?? baseFileData.timeOriginNs
- const data = { yValues: res.data, ...(res.xValues?.length ? { xValues: res.xValues } : {}), ...(timeOriginNs ? { timeOriginNs } : {}) }
- staged.push({
- range,
- loadedEnd,
- data,
- fileData: {
- ...baseFileData,
- ...res,
- ...(timeOriginNs ? { timeOriginNs } : {}),
- start: dataStart,
- step: 1000.0 / sampleRate,
- data
- }
- })
+ const fileData = mapRangeResponse(file, item, startSamples, res, baseFileData)
+ staged.push({ range, loadedEnd, data: fileData.data, fileData })
} catch (error) {
if (!isWavRequestCurrent(requestGeneration, requestEpoch)) {
return false
@@ -899,6 +890,7 @@ export function useWaveformData(options: WaveformDataOptions) {
return false
}
const entry = entries[index]
+ if (!isAppend && index === 0) clearSeriesCoverage(entry.range.item.id)
onDataLoaded?.(entry.data, {
...entry.fileData,
isAppend: isAppend || index > 0
@@ -907,6 +899,7 @@ export function useWaveformData(options: WaveformDataOptions) {
return false
}
markRangeLoaded(entry.range.key, entry.range.start, entry.loadedEnd, entry.range.file.timeOffsetMs)
+ trimSeriesCoverage(entry.range.item.id, entry.loadedEnd, entry.range.file.timeOffsetMs)
}
}
if (!isWavRequestCurrent(requestGeneration, requestEpoch)) {
@@ -972,7 +965,8 @@ export function useWaveformData(options: WaveformDataOptions) {
const interval = latestWavInterval.value
let loaded
- if (!interval || playbackTimeMs < interval.start || playbackTimeMs > interval.end) {
+ if (!interval || playbackTimeMs < interval.start || playbackTimeMs > interval.end
+ || !isWavViewportLoaded({ start: playbackTimeMs, end: Math.min(interval.end, playbackTimeMs + 1) })) {
const requestInterval = {
start: playbackTimeMs,
end: playbackTimeMs + WAV_PLAYBACK_RECOVERY_TIME
@@ -1038,6 +1032,17 @@ export function useWaveformData(options: WaveformDataOptions) {
publishSeriesDataComplete(item.id, false, requestGeneration)
return false
}
+ if (hasTimeIndex(item.id)) {
+ if (list.every(file => file.isComplete === true && loadedCompleteFilePaths.has(getLoadedFileKey(item.id, file.filePath)))) return true
+ const success = await loadSingleFileWithInterval(item, {
+ start: Math.min(...list.map(file => file.start)), end: Math.max(...list.map(file => file.end))
+ }, false, requestGeneration)
+ if (success && isCurrentRequest(requestGeneration)) {
+ list.filter(file => file.isComplete === true).forEach(file => loadedCompleteFilePaths.add(getLoadedFileKey(item.id, file.filePath)))
+ publishSeriesDataComplete(item.id, list.every(file => file.isComplete === true), requestGeneration)
+ }
+ return success
+ }
const list2 = list
.filter(file => (
file.isComplete !== true
@@ -1064,7 +1069,7 @@ export function useWaveformData(options: WaveformDataOptions) {
// to discover its clock before selecting ranges, otherwise no render can establish offsets.
const primeTimeOrigins = (displayInterval: { start: number; end: number }, requestGeneration: number) => {
if (!getSeriesTimeOffsetFn || (graphConfig.value?.renderDatas?.length ?? 0) < 2) return
- const candidates = (graphConfig.value?.renderDatas ?? []).filter(item => getSeriesTimeOffset(item.id) === 0
+ const candidates = (graphConfig.value?.renderDatas ?? []).filter(item => !hasTimeIndex(item.id) && getSeriesTimeOffset(item.id) === 0
&& !getIndexFiles(item.id).some(file => file.start < displayInterval.end && file.end > displayInterval.start))
if (!candidates.length) return
return (async () => {
@@ -1349,7 +1354,7 @@ export function useWaveformData(options: WaveformDataOptions) {
const normalizedOptions = typeof options === 'object' && options !== null ? options : {}
const force = options === true || normalizedOptions.force === true
const poll = !force && normalizedOptions.poll === true
- const playback = !force && !poll && normalizedOptions.playback === true
+ const playback = !force && normalizedOptions.playback === true
const { perfTraceId, ...loadOptions } = (
normalizedOptions
)
@@ -1542,9 +1547,10 @@ export function useWaveformData(options: WaveformDataOptions) {
const missingPlaybackFiles = (target: number) => (
(graphConfig.value?.renderDatas || []).filter(hasIndexFileSource).flatMap(item => {
- const files = getIndexFiles(item.id)
+ const files = getReadFiles(item.id)
const file = files.find(entry => entry.start <= target && target < entry.end)
- ?? files.find(entry => entry.end === target)
+ ?? files.find(entry => entry.end === target && (!hasTimeIndex(item.id) || target === xDataMax.value))
+ ?? getIndexFiles(item.id).find(entry => entry.isComplete === false && entry.end <= target)
// An indexed gap or a shorter channel has no sample to wait for.
if (!file) return []
const step = 1000 / item.sampleRate
@@ -1554,7 +1560,7 @@ export function useWaveformData(options: WaveformDataOptions) {
latestWavInterval.value && latestWavInterval.value.start <= sampleTime && latestWavInterval.value.end > sampleTime
)
const covered = loadedCompleteFilePaths.has(key) || (
- inCurrentWavWindow && isRangeCovered(key, sampleTime, Math.min(file.end, sampleTime + step), file.timeOffsetMs)
+ !(file.isComplete === false && target >= file.end) && inCurrentWavWindow && isRangeCovered(key, sampleTime, Math.min(file.end, sampleTime + step), file.timeOffsetMs)
)
return covered ? [] : [file]
})
diff --git a/apps/frontend/src/modules/shared/data-graph/hooks/__tests__/use-index-files-data.test.ts b/apps/frontend/src/modules/shared/data-graph/hooks/__tests__/use-index-files-data.test.ts
index 7fdb3c23..b055da69 100644
--- a/apps/frontend/src/modules/shared/data-graph/hooks/__tests__/use-index-files-data.test.ts
+++ b/apps/frontend/src/modules/shared/data-graph/hooks/__tests__/use-index-files-data.test.ts
@@ -2,8 +2,10 @@ import { computed, ref, toValue } from 'vue'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
const mocks = vi.hoisted(() => ({
- parseIndexFile: vi.fn()
+ parseIndexFile: vi.fn(),
+ loadWaveformTimeIndex: vi.fn(async files => files)
}))
+vi.mock('@/libs/file-loader', () => ({ loadWaveformTimeIndex: mocks.loadWaveformTimeIndex }))
vi.mock('../../utils/helpers', () => ({
parseIndexFile: mocks.parseIndexFile
@@ -53,6 +55,22 @@ describe('useIndexFilesData', () => {
)
})
+ it('reports a waveform index rejection without publishing a nominal timeline and allows retry', async () => {
+ const item = { id: 'series-1', fileId: 'bad-file', sampleRate: 48000 }
+ const raw = [{ filePath: 'bad.crybin', start: 0, end: 1000 }]
+ mocks.parseIndexFile.mockResolvedValue(raw)
+ const cause = new Error('Implicit sample times must increase')
+ mocks.loadWaveformTimeIndex.mockRejectedValueOnce(cause)
+ const { useIndexFilesData } = await import('../use-index-files-data')
+ const api = useIndexFilesData({ config: ref({ renderDatas: [item] }), waveformTime: true })
+ await expect(api.loadIndexFilesData()).rejects.toMatchObject({
+ name: 'WaveformTimeIndexLoadError', seriesId: item.id, cause
+ })
+ expect(api.indexFilesDataMap.value).toBeNull()
+ expect(api.isLoading.value).toBe(false)
+ await expect(api.loadIndexFilesData()).resolves.toEqual({ [item.id]: raw })
+ })
+
it('requests task-time indexing only for a historical sound-quality heatmap', async () => {
mocks.parseIndexFile.mockResolvedValue([])
const item = { id: 'series-1', fileId: 'file-a', resultCode: 'Loudness' }
diff --git a/apps/frontend/src/modules/shared/data-graph/hooks/use-index-files-data.ts b/apps/frontend/src/modules/shared/data-graph/hooks/use-index-files-data.ts
index 041d68f8..d27c9770 100644
--- a/apps/frontend/src/modules/shared/data-graph/hooks/use-index-files-data.ts
+++ b/apps/frontend/src/modules/shared/data-graph/hooks/use-index-files-data.ts
@@ -1,7 +1,10 @@
import { computed, ref, toValue } from 'vue'
+import { WaveformTimeIndexLoadError } from '../utils/waveform-time-index-error'
import { isSoundQualitySpectrogram } from '../utils/sound-quality-spectrogram'
import { parseIndexFile } from '@/modules/shared/data-graph/utils/helpers'
import { createDataSourceFingerprint } from '@/modules/shared/data-graph/utils/data-source-fingerprint'
+import { loadWaveformTimeIndex } from '@/libs/file-loader'
+import type { WaveformTimeRange } from '@/libs/file-loader/handlers/waveform-time-index'
import {
findPlaybackWindow,
getPlaybackWindowKind,
@@ -24,6 +27,8 @@ interface IndexFileEntry extends Record {
end?: number
isComplete?: boolean
playbackWindows?: PlaybackWindow[]
+ timeOriginNs?: string
+ waveformTimeRanges?: WaveformTimeRange[]
}
type IndexFilesDataMap = Record
interface IndexDataGraphConfig extends Record {
@@ -34,10 +39,12 @@ interface IndexDataGraphConfig extends Record {
export function useIndexFilesData({
config,
- windowReplay = false
+ windowReplay = false,
+ waveformTime = false
}: {
config: MaybeRefOrGetter
windowReplay?: boolean
+ waveformTime?: boolean
}) {
const graphConfig = computed(() => toValue(config))
const indexFilesDataMap = ref(null)
@@ -84,9 +91,17 @@ export function useIndexFilesData({
}
}
: diagnostics
- const fileList = Object.keys(indexOptions).length
+ let fileList: IndexFileEntry[] = Object.keys(indexOptions).length
? await parseIndexFile(renderItem, indexOptions)
: await parseIndexFile(renderItem)
+ if (waveformTime && graphConfig.value?.isRealtime !== true && fileList.length) {
+ try {
+ fileList = await loadWaveformTimeIndex(fileList, Number(item.sampleRate), perfTraceId)
+ } catch (error) {
+ // Mapping an unreadable or non-monotone recording by sample count would invent times.
+ throw new WaveformTimeIndexLoadError(item.id, error)
+ }
+ }
return {
id: item.id,
fileList
diff --git a/apps/frontend/src/modules/shared/data-graph/utils/waveform-time-index-error.ts b/apps/frontend/src/modules/shared/data-graph/utils/waveform-time-index-error.ts
new file mode 100644
index 00000000..aa40be2f
--- /dev/null
+++ b/apps/frontend/src/modules/shared/data-graph/utils/waveform-time-index-error.ts
@@ -0,0 +1,6 @@
+export class WaveformTimeIndexLoadError extends Error {
+ constructor(readonly seriesId: string | number, cause: unknown) {
+ super('Could not read the waveform time index', { cause })
+ this.name = 'WaveformTimeIndexLoadError'
+ }
+}
diff --git a/docs/crychart-integration.md b/docs/crychart-integration.md
index 1bf1e296..dfc64ba4 100644
--- a/docs/crychart-integration.md
+++ b/docs/crychart-integration.md
@@ -2,7 +2,7 @@
[简体中文](crychart-integration.zh-CN.md)
-OpenTest pins the public package `@crysound/crychart` to version `1.0.1`. This release includes the upstream fixes used in the former `1.0.1-opentest.30` package. CRYChart and OpenTest have separate version numbers.
+OpenTest pins the public package `@crysound/crychart` to version `1.0.2`. It includes the high-precision X-axis interval cap used by waveform detail charts. CRYChart and OpenTest have separate version numbers.
## Install and import
@@ -15,7 +15,7 @@ pnpm install --frozen-lockfile
To add the package or select a different release, specify an exact version:
```powershell
-pnpm --filter @opentest/frontend add --save-exact @crysound/crychart@1.0.1
+pnpm --filter @opentest/frontend add --save-exact @crysound/crychart@1.0.2
```
Commit `apps/frontend/package.json` and the root `pnpm-lock.yaml` together. Use an exact version without `^` or `~`. The lockfile records the package integrity digest. The public package can be installed without publisher credentials.
@@ -56,6 +56,6 @@ The Windows artifact audit scripts tied to the old archive validation instance s
CRYChart uses the CRYChart Community License 1.0, including its commercial-use terms. OpenTest includes both language versions of the license and lists CRYChart in `apps/frontend/public/THIRD-PARTY-NOTICES.txt`. The chart engine needs no runtime license key or license environment variable.
-- [npm release 1.0.1](https://www.npmjs.com/package/@crysound/crychart/v/1.0.1)
+- [npm release 1.0.2](https://www.npmjs.com/package/@crysound/crychart/v/1.0.2)
- [CRYChart source](https://github.com/crysound/CRYChart)
- [CRYChart npm usage guide](https://github.com/crysound/CRYChart/blob/main/docs/npm-usage.md)
diff --git a/docs/crychart-integration.zh-CN.md b/docs/crychart-integration.zh-CN.md
index 63219d97..747fbc4b 100644
--- a/docs/crychart-integration.zh-CN.md
+++ b/docs/crychart-integration.zh-CN.md
@@ -2,7 +2,7 @@
[English](crychart-integration.md)
-宿主使用 npmjs.com 的公开包 `@crysound/crychart`,固定版本为 `1.0.1`。该版本包含原 `1.0.1-opentest.30` 消费者版本中已合入上游的修复。产品版本与图表库版本分别维护。
+宿主使用 npmjs.com 的公开包 `@crysound/crychart`,固定版本为 `1.0.2`。该版本包含波形细节图使用的高精度 X 轴窗口上限修复。产品版本与图表库版本分别维护。
## 安装和导入
@@ -15,7 +15,7 @@ pnpm install --frozen-lockfile
首次接入或显式升级图表库时执行:
```powershell
-pnpm --filter @opentest/frontend add --save-exact @crysound/crychart@1.0.1
+pnpm --filter @opentest/frontend add --save-exact @crysound/crychart@1.0.2
```
提交 `apps/frontend/package.json` 和根 `pnpm-lock.yaml`。精确版本不使用 `^` 或 `~`,锁文件记录 npm 包的完整性摘要。公开包安装不需要发布凭据。
@@ -56,6 +56,6 @@ pnpm --filter @opentest/frontend build
CRYChart 采用 CRYChart Community License 1.0,公开 npm 分发保留原商业使用条件。宿主保留中英文许可文件及 `apps/frontend/public/THIRD-PARTY-NOTICES.txt` 中的声明,无需图表运行许可证或许可环境变量。
-- [npm 发行版 1.0.1](https://www.npmjs.com/package/@crysound/crychart/v/1.0.1)
+- [npm 发行版 1.0.2](https://www.npmjs.com/package/@crysound/crychart/v/1.0.2)
- [源码仓库](https://github.com/crysound/CRYChart)
- [CRYChart npm 使用说明](https://github.com/crysound/CRYChart/blob/main/docs/npm-usage.md)
diff --git a/docs/verification/waveform-timestamp-window-results.json b/docs/verification/waveform-timestamp-window-results.json
new file mode 100644
index 00000000..82fc090d
--- /dev/null
+++ b/docs/verification/waveform-timestamp-window-results.json
@@ -0,0 +1,110 @@
+{
+ "date": "2026-11-13",
+ "host": "windows-huang",
+ "instance": "time-axis-20261110",
+ "transport": "CDP only",
+ "repositories": {
+ "OpenTest": {
+ "base": "a70a64c",
+ "branch": "feature/waveform-timestamp-window"
+ },
+ "CRYChart": {
+ "base": "c2ecea0",
+ "branch": "feature/waveform-timestamp-window",
+ "package": "1.0.1-opentest.31"
+ }
+ },
+ "automated": {
+ "hostPassed": 195,
+ "chartPassed": 1222,
+ "chartSkipped": 2,
+ "contractsPassed": 31,
+ "artifactChecksPassed": 8,
+ "frontendBuild": "passed",
+ "repositoryTypecheck": "fails in unchanged files; see paired report"
+ },
+ "product": {
+ "standard": {
+ "completed": true,
+ "passed": 58,
+ "failed": 0,
+ "pageErrors": [],
+ "failedChecks": []
+ },
+ "internalGapAndReversal": {
+ "completed": true,
+ "passed": 13,
+ "failed": 0,
+ "pageErrors": [],
+ "failedChecks": []
+ },
+ "runtimeWavOnly": {
+ "completed": true,
+ "passed": 10,
+ "failed": 0,
+ "pageErrors": [],
+ "failedChecks": []
+ },
+ "originalFixturesRestored": true
+ },
+ "finalRuntime": {
+ "version": "1.0.1-opentest.31",
+ "modulesChecked": 130,
+ "modulesMatched": 130,
+ "checksSha256": "825e4d13d5a9234125e9931715d0f6d81c769d6fcfc9a737b4e68863521478ca",
+ "chartAndWorkerChecks": [
+ {
+ "file": "assets/file-processor.worker-BV1N3wbn.js",
+ "sha256": "97581f5c808ce585218938d3b51210be68d89dd483024ff9567da0b39daec37d",
+ "match": true
+ },
+ {
+ "file": "js/chart.MczxdHNS.js",
+ "sha256": "9cb23fa14553256507abed4a05b01905c225fc90c445178e4605649a62ba5aa0",
+ "match": true
+ }
+ ]
+ },
+ "performance": {
+ "CG30": [
+ {"name": "fresh-history-0","dataReadyMs": 2744.3,"valid": true,"rangeReadBytes": 11522754,"waveformLoadMs": [294.8]},
+ {"name": "fresh-history-1","dataReadyMs": 2896.1,"valid": true,"rangeReadBytes": 11522754,"waveformLoadMs": [191.6]},
+ {"name": "fresh-history-2","dataReadyMs": 2629.7,"valid": true,"rangeReadBytes": 11522754,"waveformLoadMs": [226.1]},
+ {"name": "cross-shard-1-0","dataReadyMs": 309.8,"valid": true,"rangeReadBytes": 11525068,"waveformLoadMs": [89.9]},
+ {"name": "cross-shard-2-0","dataReadyMs": 316.7,"valid": true,"rangeReadBytes": 11525068,"waveformLoadMs": [100]},
+ {"name": "tail-0","dataReadyMs": 358.4,"valid": true,"rangeReadBytes": 9603634,"waveformLoadMs": [74]},
+ {"name": "return-first-0","dataReadyMs": 278.3,"valid": true,"rangeReadBytes": 9602314,"waveformLoadMs": [58]},
+ {"name": "nearby-window-0","dataReadyMs": 27.1,"valid": true,"rangeReadBytes": 0,"waveformLoadMs": [0.2]},
+ {"name": "cross-shard-1-1","dataReadyMs": 299.6,"valid": true,"rangeReadBytes": 11525068,"waveformLoadMs": [68.1]},
+ {"name": "cross-shard-2-1","dataReadyMs": 294.1,"valid": true,"rangeReadBytes": 11525068,"waveformLoadMs": [66.3]},
+ {"name": "tail-1","dataReadyMs": 329,"valid": true,"rangeReadBytes": 9603634,"waveformLoadMs": [57.8]},
+ {"name": "return-first-1","dataReadyMs": 283.8,"valid": true,"rangeReadBytes": 9602314,"waveformLoadMs": [44.2]},
+ {"name": "nearby-window-1","dataReadyMs": 103.8,"valid": true,"rangeReadBytes": 0,"waveformLoadMs": [0.2]},
+ {"name": "cross-shard-1-2","dataReadyMs": 292.5,"valid": true,"rangeReadBytes": 11525068,"waveformLoadMs": [74.1]},
+ {"name": "cross-shard-2-2","dataReadyMs": 281.5,"valid": true,"rangeReadBytes": 11525068,"waveformLoadMs": [63.7]},
+ {"name": "tail-2","dataReadyMs": 286,"valid": true,"rangeReadBytes": 9603634,"waveformLoadMs": [57.9]},
+ {"name": "return-first-2","dataReadyMs": 262.4,"valid": true,"rangeReadBytes": 9602314,"waveformLoadMs": [47.5]},
+ {"name": "nearby-window-2","dataReadyMs": 1198.1,"valid": true,"rangeReadBytes": 0,"waveformLoadMs": [0.1]}
+ ],
+ "CG31": [
+ {"name": "fresh-history-0","dataReadyMs": 3199.6,"valid": true,"rangeReadBytes": 11522754,"indexTasks": [{"bytes": 10950,"workerMs": 26.5,"durationMs": 87.2}],"waveformLoadMs": [298.1]},
+ {"name": "fresh-history-1","dataReadyMs": 2779,"valid": true,"rangeReadBytes": 11522754,"indexTasks": [{"bytes": 10950,"workerMs": 24.6,"durationMs": 96.4}],"waveformLoadMs": [246.3]},
+ {"name": "fresh-history-2","dataReadyMs": 6496.6,"valid": true,"rangeReadBytes": 11522754,"indexTasks": [{"bytes": 10950,"workerMs": 25.1,"durationMs": 88.2}],"waveformLoadMs": [263]},
+ {"name": "cross-shard-1-0","dataReadyMs": 307.1,"valid": true,"rangeReadBytes": 11525068,"waveformLoadMs": [77.7]},
+ {"name": "cross-shard-2-0","dataReadyMs": 299.6,"valid": true,"rangeReadBytes": 11525068,"waveformLoadMs": [77.3]},
+ {"name": "tail-0","dataReadyMs": 290.4,"valid": true,"rangeReadBytes": 9603634,"waveformLoadMs": [64.1]},
+ {"name": "return-first-0","dataReadyMs": 286.6,"valid": true,"rangeReadBytes": 9602314,"waveformLoadMs": [61.1]},
+ {"name": "nearby-window-0","dataReadyMs": 176.2,"valid": true,"rangeReadBytes": 0,"waveformLoadMs": [0.3]},
+ {"name": "cross-shard-1-1","dataReadyMs": 386,"valid": true,"rangeReadBytes": 11525068,"waveformLoadMs": [66.6]},
+ {"name": "cross-shard-2-1","dataReadyMs": 292.2,"valid": true,"rangeReadBytes": 11525068,"waveformLoadMs": [70.5]},
+ {"name": "tail-1","dataReadyMs": 280.8,"valid": true,"rangeReadBytes": 9603634,"waveformLoadMs": [50.3]},
+ {"name": "return-first-1","dataReadyMs": 281.4,"valid": true,"rangeReadBytes": 9602314,"waveformLoadMs": [66.4]},
+ {"name": "nearby-window-1","dataReadyMs": 74.2,"valid": true,"rangeReadBytes": 0,"waveformLoadMs": [0.6]},
+ {"name": "cross-shard-1-2","dataReadyMs": 287.8,"valid": true,"rangeReadBytes": 11525068,"waveformLoadMs": [69.6]},
+ {"name": "cross-shard-2-2","dataReadyMs": 337.9,"valid": true,"rangeReadBytes": 11525068,"waveformLoadMs": [112.4]},
+ {"name": "tail-2","dataReadyMs": 283.6,"valid": true,"rangeReadBytes": 9603634,"waveformLoadMs": [59.6]},
+ {"name": "return-first-2","dataReadyMs": 266.4,"valid": true,"rangeReadBytes": 9602314,"waveformLoadMs": [44.8]},
+ {"name": "nearby-window-2","dataReadyMs": 31.9,"valid": true,"rangeReadBytes": 0,"waveformLoadMs": [0.4]}
+ ]
+ }
+}
diff --git a/docs/verification/waveform-timestamp-window.md b/docs/verification/waveform-timestamp-window.md
new file mode 100644
index 00000000..74b170bf
--- /dev/null
+++ b/docs/verification/waveform-timestamp-window.md
@@ -0,0 +1,92 @@
+# Timestamped waveform shards and viewport loading
+
+[简体中文](waveform-timestamp-window.zh-CN.md)
+
+Date: 2026-11-13. Changed repositories: OpenTest and CRYChart, both on `feature/waveform-timestamp-window`. Host base: `a70a64c`; chart base: `c2ecea0`. The initial verification used the `1.0.1-opentest.31` archive. Source patch, build provenance and hashes are in `vendor/crychart/manifest.json`. Backend and native binaries were not changed.
+
+## Main branch sync (2026-11-17)
+
+After merging `main` at `94d3a558`, the host uses the public `@crysound/crychart@1.0.2` package. The SDK and frontend builds passed, along with 250 targeted unit tests and 24 artifact and packaging checks. The updated frontend was run with the existing licensed backend, native libraries and plugins in the isolated `windows-huang` instance. All 58 CDP checks passed, including the 15-second detail viewport cap, gap-aware history and replay, clock labels, and the Scope unit menu. This rerun does not validate the latest backend or native binaries.
+
+## Behavior and fixes
+
+With a preview, the existing design limits the detail viewport to 15 seconds, prefetches one viewport on each side, and retains approximately 60 seconds of samples. The preview reads its own thumbnail file. Main waveform loading remains range based.
+
+Three confirmed defects are fixed:
+
+1. High precision X axes ignored `intervalMax`, allowing a 120-second detail viewport and a full-range read. CRYChart now applies the 15-second maximum to `linear-highPrecision`, including manual intervals, wheel zoom and fit.
+2. Coverage metadata could outlive the samples retained by the renderer, causing a backward seek to skip necessary reads. Replacement clears prior coverage and appends conservatively trim it. Paused views, seeks and playback also check retained coverage.
+3. The old file index used cumulative sample duration and could not select files from an acquisition timeline containing gaps. A worker scans only V1 implicit waveform block headers to map actual time ranges to physical sample offsets. Gaps between files and within a file are preserved. Payload reads remain limited to intersecting ranges.
+
+A fixed origin pairs acquisition time and task start from the same block; seeking directly into a later shard must not choose a new origin. Both clocks must be monotone, while their difference may change across real pauses. Decreasing or overlapping times, or ambiguous mixed-clock positions, fail validation. Missing acquisition timestamps do not manufacture an epoch. Explicit X, legacy formats and other layouts retain their existing entry points.
+
+Waveform header indexes share an 8 MiB cache budget. Growing files resume from the last stable block boundary and recheck the mutable tail. A replaced or truncated file is rescanned. Invalid time indexes show a file-read error in the waveform view. `WAV_ONLY` retains staged commits, cancellation and retries while using the shared time-to-sample mapping. A failed range cannot partially commit the other shards. Known gaps do not block playback; future growing ranges still wait. Paused target recovery preserves its playback intent.
+
+`s` and `h:m:s` change labels only; h:m:s uses the machine's local timezone. Straight connections across gaps are allowed; validation checks actual sample X coordinates. Monitor Scope continues to offer only `s`.
+
+## Automated validation
+
+- Six related host suites: 195 passed, including 130 waveform hook tests. Coverage includes internal gaps, multiple origins, failed atomic staging and retry, eviction, paused recovery, growing tails and interval boundaries.
+- Regression tests failed on defective code. Removing the gap-boundary and active-frontier guards produced three failures; restoring the fix passed.
+- CRYChart: 1222 passed, two skipped; 31 OpenTest contract tests passed; chart typecheck and build passed.
+- Eight host artifact delivery checks passed. Frontend build and ESLint/Prettier for the changed Vue file passed.
+- Repository frontend typecheck remains failing on two `unknown.length` errors in unchanged `use-grpc-exec.ts:677`. Test typecheck also reports existing adjacent-plugin path, fixture type and readonly assignment errors. No changed file remains in the diagnostics; repository-wide typecheck is not reported as passing.
+
+## Windows product verification
+
+Environment: `windows-huang`, instance `time-axis-20261110`, using the existing licensed backend. HTTP ports 21021/21022, gRPC 21023, CDP 49303. All interaction used CDP, without moving the operating system mouse or taking desktop focus. Loaded chart, host modules and file worker were individually checked against final local build SHA-256 hashes.
+
+Backend JAR SHA-256: `5099848836d364c44dcd0d153902af8d92a54864a28f951bc55efca919bba291`. Chart tgz SHA-256: `da280efc1398671f5b609c4d57be4947e76d0713fa841d96e524d1863fae60d1`.
+
+Isolated synthetic project `2121156923942064129`: three real crybin files per record, 48 kHz, 40 seconds each, 5.76 million samples total, and a 24,000-point thumbnail. The continuous record spans 0–120 seconds. The gapped record occupies 0–40, 130–170 and 195–235 seconds. Epoch origin: `1794326399250123456 ns`, or 2026-11-10 23:59:59.250123456 in Shanghai.
+
+The product's history interface loads these inputs. The original project import did not restore `.idx`; this isolated fixture was supplemented with an index and generated thumbnail. This verifies real-format file loading and playback in the complete product, not an unmodified import workflow or hardware recording throughput.
+
+All 58 standard checks passed without page errors: continuous and gapped history, both units, wheel and oversized 15-second limits, backward loading after manually removing the cap and evicting data, local timezone across midnight, playback through a gap, subsequent-shard seeking, final waveform retention at 235 seconds, and Scope offering only s. All 131 loaded JavaScript modules and the worker matched final-build hashes.
+
+An additional full-product check temporarily selected WAV_ONLY through the isolated record's runtime storage flag while reading the same real files. Ten checks passed for shard crossings, eviction recovery, direct late-window seeks, empty gaps and return to the first shard. Persisted results were not changed; a reload cleared the runtime override. Hook regressions cover failure injection for atomic staging, cancellation and growing tails.
+
+The internal-gap test temporarily changes the first physical file to cover 0–20 and 28–48 seconds:
+
+| Viewport | Expected samples | Result |
+| --- | ---: | --- |
+| 35–45 s | 480000 | Passed in s and h:m:s |
+| 25–35 s | 336000 | Passed in s and h:m:s |
+| 20–25 s | 0 | Passed in s and h:m:s |
+| 18–30 s | 192000 | Passed in s and h:m:s |
+| 1–5 s | 192000 | Passed in s and h:m:s |
+
+Decreasing timestamps fail the `waveform-index` worker and leave the main waveform with zero samples. All 13 internal-file checks passed without page errors. Main and thumbnail files were restored in finally and both original SHA-256 hashes verified. Screenshot capture timed out on the occluded renderer; desktop focus was not taken. Evidence uses actual product series samples, axis intervals, UI operations and worker events.
+
+## Review follow-up (2026-11-16)
+
+The follow-up kept rejection of invalid timestamps and added a visible file-read error. The loader and both charts share one reactive origin. Growing files reuse stable headers, and the legacy waveform waits beyond the committed frontier. Focused regression: 704 passed, one skipped; host artifact tests: eight passed. The rebuilt frontend passed 83 CDP checks on `windows-huang`: 58 standard, 15 internal-gap and invalid-index checks (including alert and recovery), and 10 WAV_ONLY. Backend and native binaries were unchanged. Repository-wide typecheck still reports pre-existing errors outside the touched files.
+
+## Performance
+
+CG30 and final CG31 were tested serially on the same instance, each with three fresh-history loads and 15 window operations. CG31 was restored afterward; all 130 modules and the worker loaded at that point matched the final build again. Every data-coverage assertion passed.
+
+| Metric | CG30 control | Final CG31 |
+| --- | ---: | ---: |
+| Median readiness, 12 ordinary windows | 293.3 ms | 289.1 ms |
+| Ordinary window readiness range | 262.4–358.4 ms | 266.4–386.0 ms |
+| Median initial waveform load hook | 226.1 ms | 263.0 ms |
+| History selection to initial sample readiness | 2629.7–2896.1 ms | 2779.0–6496.6 ms |
+| Additional main-file reads for a nearby cached window | 0 bytes | 0 bytes |
+| Reads for a 10-second viewport crossing a shard | 11525068 bytes | 11525068 bytes |
+| Additional time-index reads | None | 10950 bytes per load |
+| Additional index worker processing | None | 24.6–26.5 ms |
+
+Remote scheduling affected cached readiness: 27.1–1198.1 ms in the control and 31.9–176.2 ms in CG31, both without file reads. CG31 had a 6.50-second initial-load outlier while its waveform hook took 263 ms. The full UI wait cannot be attributed to indexing, and this sample does not establish unchanged first-screen performance. It does establish approximately 25 ms of additional header processing for this fixture and comparable ordinary-window loading.
+
+The problematic 120-second request now becomes a 15-second viewport at 52.5–67.5 seconds, prefetching 37.5–82.5 seconds. It reads 17287646 bytes and retains 2.16 million points; the previous request read approximately 46090902 bytes. Both units passed. Check totals, key artifact hashes and per-run A/B figures are in the [JSON summary](waveform-timestamp-window-results.json).
+
+Opening history scans block headers without reading the full payload to build an index. Subsequent window loading uses the existing range reader. A nearby cached window requires no additional main-file reads. A 10-second viewport normally prefetches 30 seconds; the 15-second limit prefetches at most 45 seconds. Edges and known gaps reduce actual data reads.
+
+The remote renderer's requestAnimationFrame was throttled to approximately 1 Hz while occluded by other desktop windows. Data readiness was measured with 25 ms polling and includes the existing 200 ms debounce; it is not pixel presentation latency or FPS. Initial history loading includes UI, historical configuration and chart creation, so its whole duration cannot be attributed to header indexing. These measurements do not establish general large-file, multichannel or hardware-capture performance.
+
+## Reproduction material
+
+Local raw evidence remains under `OpenTest/.runtime/time-axis-chunks/fixed/`: `acceptance.mjs/json/log`, `internal-acceptance.mjs/json/log`, `wav-only-acceptance.mjs/json/log`, `performance-probe.mjs/log`, `performance-report.json` and the A/B baseline report, fixture inputs and deployment scripts. Outputs contain no licensing material.
+
+Run final-build deployment, internal fixture checks with restoration, standard acceptance and performance measurement in that order. Set `TIME_AXIS_CDP_URL` to the test instance; serialize operations on that Windows instance. Never replace files in real user projects. Both the preceding frontend and the original CG30 deployment were backed up.
diff --git a/docs/verification/waveform-timestamp-window.zh-CN.md b/docs/verification/waveform-timestamp-window.zh-CN.md
new file mode 100644
index 00000000..90f7e65d
--- /dev/null
+++ b/docs/verification/waveform-timestamp-window.zh-CN.md
@@ -0,0 +1,92 @@
+# 带时间戳的波形分片与按窗口加载验证
+
+[English](waveform-timestamp-window.md)
+
+日期:2026-11-13。修改仓库:OpenTest、CRYChart,分支均为 `feature/waveform-timestamp-window`。宿主基线 `a70a64c`,图表基线 `c2ecea0`。初次验证使用 `1.0.1-opentest.31` 压缩包;源码补丁、构建来源及摘要见 `vendor/crychart/manifest.json`。后端和原生库没有改动。
+
+## 同步主分支复测(2026-11-17)
+
+合入 `main` 的 `94d3a558` 后,宿主改用公开包 `@crysound/crychart@1.0.2`。SDK 与前端构建通过,250 项相关单元测试及 24 项制品和打包检查通过。更新的前端在 `windows-huang` 隔离实例运行,保留现有已授权后端、原生库和插件。58 项 CDP 检查全部通过,包括细节窗口 15 秒上限、带空档的历史和回放、时钟标签及 Scope 单位菜单。本轮未验证最新后端或原生制品。
+
+## 行为与修复
+
+有预览时,原有设计是细节窗口最多 15 秒,按可见窗口及左右各一个窗口预读,最多保留约 60 秒的样本缓存。预览使用独立的缩略文件。这次不将主文件改成全量读取。
+
+已确认的三个问题及修复:
+
+1. 高精度 X 轴没有执行 `intervalMax`,120 秒请求可以进入细节图,进而触发全段读取。CRYChart 现在对 `linear-highPrecision` 同样执行 15 秒限制,覆盖手工设定、滚轮和 fit。
+2. 缓存覆盖记录可能超过图表实际保留的样本,回到被淘汰的窗口时误判为已加载。替换数据时清除旧覆盖,追加时保守裁剪覆盖;暂停、定位和回放判断同时检查实际覆盖。
+3. 原索引以累计样本时长表示分片位置,无法用包含真实空档的窗口直接选片。新 worker 只扫描 V1 隐式波形的块头,建立“实际时间范围—文件内样本位置”映射。分片间和同一文件内部的空档均保留;区间读取仍只读命中范围。
+
+索引采用同一块的采集时间戳与任务起点建立固定原点。不能用首次进入的晚期分片重新确定原点。采集时间和任务时间分别校验单调性,允许两者差值因实际暂停改变;递减、重叠或无法确定位置的混合时钟数据会报错。缺少源时间戳的数据不虚构绝对时刻,显式 X、旧格式及非目标布局沿用原加载入口。
+
+波形块头索引使用 8 MiB 缓存。活动文件从已确认的块边界继续扫描,最后一个可能回填的块会重新校验。文件被替换或截断时重新扫描。无效时间索引会在波形区显示文件读取错误。`WAV_ONLY` 保留原有分阶段提交、取消和重试逻辑,使用同一时间到样本映射。某个读取失败不会先提交其余分片;已知空档不阻塞回放,仍在写入的未来范围继续等待。暂停后的目标补读保留回放意图。
+
+`s` 和 `h:m:s` 仅改变标注,h:m:s 使用运行机器本地时区。允许跨空档的直线连接;校验依据为样本实际 X 坐标。Monitor Scope 单位仍只有 `s`。
+
+## 自动验证
+
+- 宿主相关 6 个测试文件:195 项通过,其中波形 hook 130 项。覆盖文件内空档、多个时间原点、原子提交失败及重试、缓存淘汰、暂停补读、活动尾部和时间边界。
+- 新测试曾在缺陷代码上失败;去掉空档边界与活动前沿保护的负向验证也触发了 3 项失败,恢复修复后通过。
+- CRYChart:1222 项通过、2 项跳过;OpenTest 合同 31 项通过;图表类型检查、构建通过。
+- 宿主制品交付检查 8 项通过;前端构建、改动 Vue 文件的 ESLint 和 Prettier 检查通过。
+- 全仓前端类型检查未通过:未修改的 `use-grpc-exec.ts:677` 有两处 `unknown.length` 错误。测试类型检查还包含既有的相邻插件路径、测试 fixture 类型及只读赋值错误。本次改动文件未再报错;不将全仓类型检查记为通过。
+
+## Windows 完整产品实测
+
+环境:`windows-huang`,实例 `time-axis-20261110`,现有授权后端;HTTP 21021/21022,gRPC 21023,CDP 49303。所有交互通过 CDP,不操作系统鼠标,也未抢占桌面焦点。实际加载的图表、宿主模块和文件 worker 与最终本地构建逐个比对 SHA-256。
+
+后端 JAR SHA-256:`5099848836d364c44dcd0d153902af8d92a54864a28f951bc55efca919bba291`。图表 tgz SHA-256:`da280efc1398671f5b609c4d57be4947e76d0713fa841d96e524d1863fae60d1`。
+
+使用隔离合成工程 `2121156923942064129`,每条记录包含 3 个真实 crybin 文件、48 kHz、每片 40 秒,共 576 万样本;缩略文件为 24000 点。连续记录范围为 0–120 秒;空档记录实际范围为 0–40、130–170、195–235 秒。绝对起点为 `1794326399250123456 ns`,上海时区为 2026-11-10 23:59:59.250123456。
+
+这些输入通过产品历史界面加载,但原工程导入未恢复 `.idx`,本轮在隔离工程中补齐索引并生成缩略文件。因此这是完整产品对真实格式文件的加载与回放验证,不是未补充材料的导入验收,也不是设备采集写盘性能测试。
+
+标准验收 58 项全部通过,无页面异常:连续与非连续历史数据、两种单位、滚轮及过大区间的 15 秒上限、手工取消限制后缓存淘汰的回退读取、跨午夜本地时区、空档内回放、下一分片定位、235 秒自然结束保留末段,以及 Scope 仅显示 s。最终构建的 131 个已加载 JavaScript 模块及 worker 哈希均匹配。
+
+另在完整产品中临时将隔离记录的运行时存储标志设为 WAV_ONLY,使用相同真实文件验证:跨分片、缓存淘汰后的回退、带空档的晚期直接定位、空窗口与回到首片,共 10 项通过。此检查不改持久化结果;页面重载后清除运行时覆盖。原子提交失败、取消和增长尾部的故障注入由 hook 回归测试覆盖。
+
+文件内空档验证临时将首个物理文件改为 0–20 秒、28–48 秒:
+
+| 可见窗口 | 应有样本数 | 结果 |
+| --- | ---: | --- |
+| 35–45 秒 | 480000 | s / h:m:s 均通过 |
+| 25–35 秒 | 336000 | s / h:m:s 均通过 |
+| 20–25 秒 | 0 | s / h:m:s 均通过 |
+| 18–30 秒 | 192000 | s / h:m:s 均通过 |
+| 1–5 秒 | 192000 | s / h:m:s 均通过 |
+
+递减时间戳输入导致 `waveform-index` worker 失败,主波形样本数为 0。文件内测试共 13 项通过,无页面异常;原始主文件与缩略文件已在 finally 中恢复并核对两个 SHA-256。截图在被遮挡的远端渲染器上超时,未通过抢占桌面解决;本次判断依据为产品图表中的实际样本、轴范围、UI 操作和 worker 事件。
+
+## 评审后复测(2026-11-16)
+
+继续拒绝无效时间戳并显示文件读取错误,加载器、主图和预览共用响应式原点。活动文件复用稳定块头,LEGACY 在已写入边界外继续等待。相关回归 704 项通过、1 项跳过,宿主制品检查 8 项通过。重新构建前端后,在 `windows-huang` 通过 83 项 CDP 实测:标准验收 58 项、文件内空档和无效索引 15 项(含提示及恢复)、WAV_ONLY 10 项。后端和原生库未改动;全仓类型检查仍有改动文件之外的既有错误。
+
+## 性能
+
+同一实例串行切换 CG30 与最终 CG31,各测 3 次初次历史加载和 15 次窗口操作;结束后恢复 CG31,并再次校验 130 个当时已加载的模块及 worker,全部匹配。所有数据覆盖判定均通过。
+
+| 指标 | CG30 对照 | CG31 最终版本 |
+| --- | ---: | ---: |
+| 12 次普通窗口就绪中位数 | 293.3 ms | 289.1 ms |
+| 普通窗口就绪范围 | 262.4–358.4 ms | 266.4–386.0 ms |
+| 初次主波形加载 hook 中位数 | 226.1 ms | 263.0 ms |
+| 初次历史选择到样本就绪 | 2629.7–2896.1 ms | 2779.0–6496.6 ms |
+| 附近窗口新增主文件读取 | 0 字节 | 0 字节 |
+| 10 秒跨分片窗口实际读取 | 11525068 字节 | 11525068 字节 |
+| 新增时间索引读取 | 无 | 10950 字节 / 次 |
+| 新增时间索引 worker 处理 | 无 | 24.6–26.5 ms |
+
+受远端调度影响,缓存命中就绪时间对照为 27.1–1198.1 ms,新版为 31.9–176.2 ms,均没有文件读取。初次打开新版有 6.50 秒离群值,而该次主波形加载 hook 为 263 ms;不能把整个 UI 等待时间归因于索引,也不能据这组数宣称首屏性能无回退。可确认的是该样本的新增块头处理约 25 ms,普通窗口加载与对照相近。
+
+曾触发问题的 120 秒请求现在被限制为 52.5–67.5 秒的 15 秒窗口,预读 37.5–82.5 秒,实际读取 17287646 字节,保留 216 万点;修复前同类请求读取约 46090902 字节。两种单位均验证通过。检查计数、关键制品校验和逐轮 A/B 数字见 [JSON 摘要](waveform-timestamp-window-results.json)。
+
+首次打开会扫描块头,而不会为建立索引读取全部样本。持续窗口读取使用既有范围 reader;附近窗口命中缓存时不新增主文件读取。10 秒可见窗口通常预读 30 秒,15 秒上限对应最多 45 秒。边缘或空档处按实际有效数据减少。
+
+被其他桌面窗口遮挡时,远端渲染器的 requestAnimationFrame 约为 1 Hz。上述就绪时间使用 25 ms 的样本就绪轮询;它包含既有 200 ms 防抖,不等同于像素呈现延迟或帧率。初次历史加载包含 UI、历史配置和图表创建,不能全部归因于块头索引。不据此宣称大文件、多通道或硬件采集场景的普遍性能结论。
+
+## 复测材料
+
+本机保留原始材料:`OpenTest/.runtime/time-axis-chunks/fixed/` 中的 `acceptance.mjs/json/log`、`internal-acceptance.mjs/json/log`、`wav-only-acceptance.mjs/json/log`、`performance-probe.mjs/log`、`performance-report.json` 和 A/B 基线报告、测试输入和部署脚本。输出不包含授权材料。
+
+复测依次使用最终构建部署、文件内输入验证并恢复、标准验收、性能测量。CDP 入口通过 `TIME_AXIS_CDP_URL` 指定;只有同一个 Windows 测试实例操作串行执行。不要对真实用户工程替换测试文件。制品部署前一版与最初 CG30 均已保留备份。
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 6767208e..f8147f8c 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -140,8 +140,8 @@ importers:
specifier: 2.1.2
version: 2.1.2(@antv/x6@2.18.1)(vue@3.5.13(typescript@5.9.3))
'@crysound/crychart':
- specifier: 1.0.1
- version: 1.0.1
+ specifier: 1.0.2
+ version: 1.0.2
'@element-plus/icons-vue':
specifier: 2.3.1
version: 2.3.1(vue@3.5.13(typescript@5.9.3))
@@ -652,8 +652,8 @@ packages:
resolution: {integrity: sha512-Ir+AOibqzrIsL6ajt3Rz3LskB7OiMVHqltZmspbW/TJuTVuyOMirVqAkjfY6JISiLHgyNqicAC8AyHHGzNd/dA==}
engines: {node: '>=0.1.90'}
- '@crysound/crychart@1.0.1':
- resolution: {integrity: sha512-DVrresNxQW/I+he03LduSNDw125OW61vX+0vvsPtUxhYpACy9CxQmmdZDMrcJ0XWvPH6xp3u5+9t+MpTDZfE0w==}
+ '@crysound/crychart@1.0.2':
+ resolution: {integrity: sha512-qE//vmWlBnniGeubaRA6r2PtDCHHkQ7279rJBFGhwjoMbnpB7dZoEWJ5GHFVzF6/AKuOE0Dr5656R0/uLarAzQ==}
engines: {node: '>=20'}
'@csstools/color-helpers@5.0.2':
@@ -6011,7 +6011,7 @@ snapshots:
'@colors/colors@1.6.0': {}
- '@crysound/crychart@1.0.1': {}
+ '@crysound/crychart@1.0.2': {}
'@csstools/color-helpers@5.0.2': {}
diff --git a/vendor/crychart/README.md b/vendor/crychart/README.md
index 93d3edd3..e1214b5e 100644
--- a/vendor/crychart/README.md
+++ b/vendor/crychart/README.md
@@ -1,8 +1,10 @@
# CRYChart 制品
-本目录保留压缩包接入时期的历史制品、补丁和验证记录。宿主当前通过 pnpm 使用 npmjs.com 的 `@crysound/crychart@1.0.1`。安装、升级和构建校验见[CRYChart 接入说明](../../docs/crychart-integration.zh-CN.md)。下文只描述历史消费者版本。
+本目录保留压缩包接入时期的历史制品、补丁和验证记录。宿主当前通过 pnpm 使用 npmjs.com 的 `@crysound/crychart@1.0.2`。安装、升级和构建校验见[CRYChart 接入说明](../../docs/crychart-integration.zh-CN.md)。下文只描述历史消费者版本。
-宿主固定消费`manifest.json`指定的`1.0.1-opentest.30` tgz,上游基线已更新到 main 的 639ba3a;本次修复位于`fix/monitor-projection-stall-20261112`,由用户指令授权直接修复并验证。源码补丁、制品、运行入口与分支提交摘要均列于清单。新增上游提交只包含 CI 和 CODEOWNERS,没有图表运行代码变化。
+`manifest.json`记录曾用于波形窗口实测的 `1.0.1-opentest.31` 压缩包及源码补丁。对于使用 npm 版本的构建,以本次构建记录和锁文件为准。
+
+历史 CG30 集成曾使用 `1.0.1-opentest.30` 压缩包,上游基线已更新到 main 的 639ba3a;本次修复位于`fix/monitor-projection-stall-20261112`,由用户指令授权直接修复并验证。源码补丁、制品、运行入口与分支提交摘要均列于清单。新增上游提交只包含 CI 和 CODEOWNERS,没有图表运行代码变化。
CG30 修复长时间滚动波形的 Float32 横坐标精度退化:保留摘要缓存,重设投影原点,仅重算显示点;严格顺序守卫保留。192kHz、60秒窗口的重复精度边界、分页与 arena 路径、尖峰及间断、后续增量更新和不可恢复回退均有回归覆盖。源码1221通过、2跳过,消费合同31/31,类型检查与构建通过;宿主波形59项、制品检查8项通过。Windows `kyle-opt1` 已部署并完成同尺寸、同缩放的80秒CDP复测:无全量回退、无超过100ms长任务,最大帧间隔66.7ms。源码补丁与制品摘要见清单。 [CRYChart PR #4](https://github.com/crysound/CRYChart/pull/4) 已同步最新主分支并补齐示例目录的版本号;上述源码测试数基于该 PR 的最新源码。本目录继续记录已在 Windows 部署验收的制品与构建来源。
diff --git a/vendor/crychart/crychart-1.0.1-opentest.31.tgz b/vendor/crychart/crychart-1.0.1-opentest.31.tgz
new file mode 100644
index 00000000..9562113f
Binary files /dev/null and b/vendor/crychart/crychart-1.0.1-opentest.31.tgz differ
diff --git a/vendor/crychart/manifest.json b/vendor/crychart/manifest.json
index 6506c409..8bdbbc19 100644
--- a/vendor/crychart/manifest.json
+++ b/vendor/crychart/manifest.json
@@ -1,25 +1,25 @@
{
"schemaVersion": 1,
"packageName": "crychart",
- "version": "1.0.1-opentest.30",
- "file": "crychart-1.0.1-opentest.30.tgz",
+ "version": "1.0.1-opentest.31",
+ "file": "crychart-1.0.1-opentest.31.tgz",
"sourceRepository": "https://github.com/crysound/CRYChart",
- "sourceCommit": "639ba3a4c53277964c22a73f3c64c219d769888b",
- "sha256": "391cd1f49519c5668f4c7e693dc78c92252c379c217e24d34727815662fdfec2",
+ "sourceCommit": "c2ecea01621b0f09f8971fac53097ce0132dae39",
+ "sha256": "da280efc1398671f5b609c4d57be4947e76d0713fa841d96e524d1863fae60d1",
"upstreamBuild": "version/v1.0/manifest.json",
- "entrySha256": "3c170a57ead660f3345c32713b95c7fdf00aef452f4ae6844319b32654d9e068",
+ "entrySha256": "6b0e5fdfe5e950d12404d302162e4ca46241d25bc81e975d170fbad2eb802303",
"sourceModified": true,
- "validation": "CG30: rolling Float32 X recovery retains min/max summaries and rebuilds display coordinates only. PR #4 source tests after gallery-version metadata alignment: 1221 passed, 2 skipped; contracts: 31 passed; typecheck/build passed; targeted host waveform tests: 59 passed; delivery checks: 8 passed. Clean upstream plus recorded patch reproduces all four runtime entries byte-for-byte. Deployed kyle-opt1 to windows-huang, release 20261112T033024Z-903209e2; deployed artifact/entry hashes match. CDP: 80s with original 2560x1392 viewport, DPR 1.5 and 192kHz/60s/two-channel retention: 0 full-geometry fallbacks, 0 tasks >=100ms, max frame gap 66.7ms, p99 17.3ms. Each observed rebase scanned only 9600 new samples. Existing host browser-smoke fixture cannot start because its calibrator-realtime-chart.vue import is absent; real Windows verification completed. The pinned deployment artifact predates the PR-only gallery catalog version correction; runtime entries are unchanged.",
+ "validation": "CG31: intervalMax now applies to linear-highPrecision waveform axes. Source: 1222 passed, 2 skipped; OpenTest contracts: 31 passed; typecheck/build passed. Host: 195 related tests, 8 artifact checks, frontend build passed. windows-huang time-axis-20261110: 58 full-product CDP checks, 13 internal-gap/reversal checks, and 10 WAV_ONLY runtime checks passed; 131 loaded JS modules/worker matched final local SHA256. See docs/verification/waveform-timestamp-window.md for scope and typecheck limitations.",
"distributionBasis": "CRYChart Community License 1.0 (LicenseRef-CRYChart-Community-1.0); upstream artifact includes LICENSE.md and LICENSE.zh-CN.md.",
"buildTools": {
"node": "v24.20.0",
"typescript": "5.9.3",
"esbuild": "0.25.12"
},
- "sourceBranch": "fix/monitor-projection-stall-20261112",
- "sourcePatch": "opentest-consumer-639ba3a-cg30.patch",
- "sourcePatchSha256": "c9a4219e75bd8f3f0b6def09accd3b9a4f4496a2153f59851c10e6f2bd4725f1",
- "buildSourceTreeSha256": "c9a4219e75bd8f3f0b6def09accd3b9a4f4496a2153f59851c10e6f2bd4725f1",
- "sourceBranchCommit": "1a225b87791c4a197623dde09cb793b490b87742",
- "sourcePullRequest": "https://github.com/crysound/CRYChart/pull/4"
+ "sourceBranch": "feature/waveform-timestamp-window",
+ "sourcePatch": "opentest-consumer-c2ecea0-cg31.patch",
+ "sourcePatchSha256": "af23afb38f045a70a8ea926254f0d0546293b212bad2b69506392a9b25307270",
+ "buildSourceTreeSha256": "af23afb38f045a70a8ea926254f0d0546293b212bad2b69506392a9b25307270",
+ "sourceBranchCommit": "bd21e0861187596a1fbe99619c403f51734c7dd7",
+ "sourcePullRequest": "https://github.com/crysound/CRYChart/pull/5"
}
diff --git a/vendor/crychart/opentest-consumer-c2ecea0-cg31.patch b/vendor/crychart/opentest-consumer-c2ecea0-cg31.patch
new file mode 100644
index 00000000..0ef1b480
--- /dev/null
+++ b/vendor/crychart/opentest-consumer-c2ecea0-cg31.patch
@@ -0,0 +1,95 @@
+diff --git a/docs/reference-examples.json b/docs/reference-examples.json
+index 689cd8d..a3c9294 100644
+--- a/docs/reference-examples.json
++++ b/docs/reference-examples.json
+@@ -2,7 +2,7 @@
+ "schemaVersion": 2,
+ "identity": {
+ "name": "CRYChart",
+- "packageVersion": "1.0.1-opentest.30",
++ "packageVersion": "1.0.1-opentest.31",
+ "entry": "examples/official/index.html"
+ },
+ "count": 167,
+diff --git a/package-lock.json b/package-lock.json
+index 851d1df..59c2b34 100644
+--- a/package-lock.json
++++ b/package-lock.json
+@@ -1,12 +1,12 @@
+ {
+ "name": "crychart",
+- "version": "1.0.1-opentest.30",
++ "version": "1.0.1-opentest.31",
+ "lockfileVersion": 3,
+ "requires": true,
+ "packages": {
+ "": {
+ "name": "crychart",
+- "version": "1.0.1-opentest.30",
++ "version": "1.0.1-opentest.31",
+ "devDependencies": {
+ "@types/node": "24.10.0",
+ "esbuild": "0.25.12",
+diff --git a/package.json b/package.json
+index 7e0d905..21f8077 100644
+--- a/package.json
++++ b/package.json
+@@ -1,6 +1,6 @@
+ {
+ "name": "crychart",
+- "version": "1.0.1-opentest.30",
++ "version": "1.0.1-opentest.31",
+ "description": "CRYChart chart engine with streaming data, interactive axes and WebGL rendering",
+ "type": "module",
+ "main": "./dist/crychart.cjs",
+diff --git a/src/axis.ts b/src/axis.ts
+index a51415e..ef625a1 100644
+--- a/src/axis.ts
++++ b/src/axis.ts
+@@ -660,7 +660,7 @@ export class Axis {
+ /** Only the finite positive constant object maximum used by Preview is enforced.
+ * Other restriction fields and callback enforcement retain their existing behavior. */
+ private supportedIntervalMax(): number | undefined {
+- if(this.type!=='linear'||this.chart.supportsAxisIntervalMaxRestrictions?.()!==true)return undefined;
++ if((this.type!=='linear'&&this.type!=='linear-highPrecision')||this.chart.supportsAxisIntervalMaxRestrictions?.()!==true)return undefined;
+ const value=this.intervalRestriction;
+ if(!value||typeof value!=='object'||Array.isArray(value))return undefined;
+ const maximum=value.intervalMax;
+diff --git a/src/index.ts b/src/index.ts
+index 99e92a1..2005aa6 100644
+--- a/src/index.ts
++++ b/src/index.ts
+@@ -79,7 +79,7 @@ export function cryChart(_options: Record = {}) {
+ getChartCount: () => owned.size,
+ };
+ }
+-export const version = "1.0.1-opentest.30";
++export const version = "1.0.1-opentest.31";
+ export class Dashboard {
+ readonly root: HTMLDivElement;
+ private cells = new Map();
+diff --git a/tests/interval-max.test.ts b/tests/interval-max.test.ts
+index f4bb3bf..73c8fff 100644
+--- a/tests/interval-max.test.ts
++++ b/tests/interval-max.test.ts
+@@ -3,6 +3,20 @@ import assert from 'node:assert/strict';
+ import {ChartXY,Chart3D,Polar} from '../src/chart.js';
+
+ const fixture=()=>{const chart=new ChartXY(),axis=chart.getDefaultAxisX();axis.setScrollStrategy(undefined);return{chart,axis};};
++test('high precision waveform axes cap manual, fit and wheel ranges with preview enabled',()=>{
++ const chart=new ChartXY({defaultAxisX:{type:'linear-highPrecision'}}),axis=chart.getDefaultAxisX();
++ try{
++ axis.setScrollStrategy(undefined).setIntervalRestrictions({intervalMax:15000});
++ axis.setInterval({start:0,end:120000});
++ assert.deepEqual(axis.getInterval(),{start:52500,end:67500});
++ axis.setInterval({start:35000,end:45000});
++ assert.equal(axis.limitIntervalZoomFactor(2),1.5);
++ const series=chart.addLineSeries();series.appendSamples({x:[0,120000],y:[1,2]});
++ axis.fit();assert.ok(axis.getInterval().end-axis.getInterval().start<=15000);
++ axis.setIntervalRestrictions(undefined).setInterval({start:0,end:120000});
++ assert.deepEqual(axis.getInterval(),{start:0,end:120000});
++ }finally{chart.dispose();}
++});
+ test('restriction setter is deferred; manual interval caps around the requested midpoint',()=>{
+ const {chart,axis}=fixture();try{
+ axis.setInterval({start:0,end:10000,stopAxisAfter:true});let changes=0;axis.on('intervalchange',()=>changes++);