← 中文资源

简体中文版本

构建外部批量排序

构建外部批量排序:完整覆盖 external sorting,含 Chunk reader、In-memory sorter 与测试的端到端实现。

阅读英文原文

项目概述

本项目实现一个面向 external sorting 的完整系统,核心要解决的问题是 sorting a dataset larger than memory by chunking, sorting in memory, and merging runs from disk。整体由 Chunk reader、In-memory sorter、Run writer、K-way merger、Spill manager 五个模块组成,每个模块单一职责、可独立测试,最后通过集成测试验证端到端正确性。设计上把 a comparator that is inconsistent and produces runs that do not merge into a globally sorted output 作为第一类需求先行处理,而非事后再补。

架构与关键决策

数据模型为 a set of sorted run files on disk, merged through a k-way heap that streams the smallest head until all runs are exhausted。Chunk reader 定义其余阶段共同依赖的数据形状并在边界处校验输入;In-memory sorter 承载 external sorting 的正确性逻辑;Run writer 专门处理 a comparator that is inconsistent and produces runs that do not merge into a globally sorted output,在失败路径上给出明确的拒绝、重试或降级策略;K-way merger 提供可观测性,每次操作输出带关联 id 的结构化事件;Spill manager 在过载时按既定方式降级,避免过载演变为数据损坏。配置与代码分离,使风险变更可经 diff 审阅。

实施与测试

按五个阶段依次实现 Chunk reader、In-memory sorter、Run writer、K-way merger、Spill manager,每阶段配套聚焦单测。集成测试组合各模块并驱动真实 external sorting 场景:先验证正常路径,再刻意触发 a comparator that is inconsistent and produces runs that do not merge into a globally sorted output 并断言系统降级而非损坏。所有依赖均在进程内或被桩替换,用例在 CI 中确定可复现。

限制与后续

  • 单区域设计,多区域复制超出范围。
  • Chunk reader 默认进程内,未水平共享。
  • 无鉴权层,假定部署在强制身份的边缘之后。

代码示例

# setup for external-sort-batch
pnpm init
pnpm add fastify lmdb
pnpm add -D typescript tsx vitest
external_sort_batch/
├── src/index.ts
├── src/chunk-reader.ts
├── src/in-memory-sorter.ts
├── tests/external_sort_batch.test.ts
└── package.json
// Chunk reader: external sorting core
export function chunkreader(input: ChunkreaderInput): ChunkreaderResult {
  // Build the chunk reader that anchors external sorting and defines the core data shape.
  return processChunkreader(input);
}
// In-memory sorter — handles external sorting Add the in-memory sorter so
export class Inmemorysorter {
  constructor(private opts: InmemorysorterOptions) {}
  async run(ctx: Context): Promise<InmemorysorterOutput> {
    return this.execute(ctx);
  }
}
// Run writer: external sorting stage
export const runwriter = (next: Next) => async (req: Request) => {
  const out = await transform(req);
  return next(out);
};
// K-way merger for external sorting
export async function kwaymerger(stream: AsyncIterable<Chunk>): Promise<Aggregate> {
  let acc = init();
  for await (const c of stream) acc = merge(acc, c);
  return acc;
}
// Spill manager: external sorting finalization
export function spillmanager(state: State): Result {
  validate(state);
  return finalize(state);
}
# run the external sorting test suite
pnpm vitest run