docs: 新增设计决策文档并实现数组追踪器校验

- 新增决策文档:移除 preset 指令,将其合并到 create 指令中,以简化生命周期和系统复杂度
- 新增决策文档:确立 SDK 侧影子状态校验机制,实现快速失败和最小必要状态原则
- 在 ArrayTracer 中实现影子状态校验,维护数组长度并进行索引边界检查
This commit is contained in:
2026-02-06 01:56:52 +08:00
parent 7b1c87f2a4
commit 5cc4f96b46
3 changed files with 117 additions and 0 deletions

View File

@@ -12,8 +12,20 @@ export const createArrayTracer = <T extends JsonValue[]>(
const { description = 'ArrayTracer', array } = options;
const tracer = crypto.randomUUID();
// 优化:仅维护数组长度作为影子状态,这在 C++/Java 等强类型语言中也极易实现(仅需一个 int 变量)
// 这种“最小必要状态”策略既能实现越界校验,又避免了在强类型语言中处理泛型存储的复杂性,且内存开销极低。
let arrayLength = array ? array.length : 0;
const { command } = getTracerContext();
const validateIndex = (index: number) => {
if (index < 0 || index >= arrayLength) {
throw new Error(
`[ArrayTracer] Index out of bounds: index ${index} is not within [0, ${arrayLength})`,
);
}
};
command({
type: 'ArrayTracer',
tracer: tracer,
@@ -24,7 +36,15 @@ export const createArrayTracer = <T extends JsonValue[]>(
},
});
// size 为正时,数组长度增加;为负时,数组长度减少(但不能小于 0
const scale = (size: number) => {
arrayLength += size;
if (arrayLength < 0) {
throw new Error(
`[ArrayTracer] Invalid size: ${size}, array length cannot be negative`,
);
}
command({
type: 'ArrayTracer',
tracer: tracer,
@@ -36,6 +56,8 @@ export const createArrayTracer = <T extends JsonValue[]>(
};
const pick = (index: number) => {
validateIndex(index);
command({
type: 'ArrayTracer',
tracer: tracer,
@@ -47,6 +69,8 @@ export const createArrayTracer = <T extends JsonValue[]>(
};
const drop = (index: number) => {
validateIndex(index);
command({
type: 'ArrayTracer',
tracer: tracer,
@@ -58,6 +82,8 @@ export const createArrayTracer = <T extends JsonValue[]>(
};
const patch = (index: number, value: T[number]) => {
validateIndex(index);
command({
type: 'ArrayTracer',
tracer: tracer,
@@ -70,6 +96,8 @@ export const createArrayTracer = <T extends JsonValue[]>(
};
const unset = (index: number) => {
validateIndex(index);
command({
type: 'ArrayTracer',
tracer: tracer,