@chkit/plugin-backfill

中文文档
0.2.0-beta.16发布于 2026/11/09MITTypeScriptES Module构建来源已验证近 30 天下载 1.2万

Time-windowed data backfill with checkpoints for chkit

原始使用文档
文档目录9 节
  1. Install
  2. Usage
  3. Documentation
  4. SDK
  5. Plan a backfill
  6. Execute chunks against a target
  7. Plan persistence
  8. Logging
  9. License

@chkit/plugin-backfill

Beta plugin for checkpointed SQL backfill operations in chkit. Its API, configuration, and CLI flags may change between releases.

Part of the chkit monorepo. This plugin extends the chkit CLI with data backfill commands.

Install

bun add -d @chkit/plugin-backfill

Usage

Register the plugin in your config:

// clickhouse.config.ts
import { defineConfig } from '@chkit/core'
import { backfill } from '@chkit/plugin-backfill'

export default defineConfig({
  schema: './src/db/schema/**/*.ts',
  outDir: './chkit',
  plugins: [
    backfill(),
  ],
  clickhouse: {
    url: process.env.CLICKHOUSE_URL ?? 'http://localhost:8123',
  },
})

Documentation

See the backfill plugin documentation (beta).

SDK

The package root is limited to the plugin registration API. Everything used by the CLI itself — the chunk planner, SQL builders, async executor, logging — is also exported from the @chkit/plugin-backfill/sdk subpath so you can build your own backfill scripts without going through the CLI.

import {
  generateChunkPlan,
  buildChunkExecutionSql,
  executeBackfill,
  getBackfillLogger,
  type ChunkPlan,
  type PlannerQuery,
} from '@chkit/plugin-backfill/sdk'

The pipeline has three stages, and you can use any subset:

  1. Plan — generateChunkPlan(...) introspects a table and returns a ChunkPlan describing how to partition the work into roughly equal-sized chunks.
  2. Build SQL — buildChunkExecutionSql(...) turns a single Chunk into an INSERT … SELECT statement.
  3. Execute — executeBackfill(...) submits chunks against a real ClickHouseExecutor with deterministic query IDs, polling, and resume support.

Plan a backfill

generateChunkPlan is decoupled from any ClickHouse client. You pass in a query function with the PlannerQuery shape and the planner uses it for every introspection / probe / split query. This makes the planner trivial to instrument or run against alternative clients.

import { createClient } from '@clickhouse/client'
import { generateChunkPlan, type PlannerQuery } from '@chkit/plugin-backfill/sdk'

const client = createClient({ url: process.env.CLICKHOUSE_URL })

const query: PlannerQuery = async (sql, settings) => {
  const result = await client.query({
    query: sql,
    format: 'JSONEachRow',
    clickhouse_settings: settings as Record<string, string | number | boolean>,
  })
  return result.json()
}

const plan = await generateChunkPlan({
  database: 'analytics',
  table: 'events',
  from: '2025-01-01T00:00:00Z',
  to: '2025-02-01T00:00:00Z',
  targetChunkBytes: 1_000_000_000, // ~1 GiB per chunk
  query,
  // 'count' is exact but slower; 'explain-estimate' is faster but approximate
  rowProbeStrategy: 'count',
})

console.log(`${plan.chunks.length} chunks, ${plan.totalRows.toLocaleString()} rows`)

Execute chunks against a target

buildChunkExecutionSql produces the per-chunk INSERT … SELECT and executeBackfill runs them with concurrency, polling, and progress callbacks. Persist the progress argument anywhere you like to support resume.

import { createClickHouseExecutor } from '@chkit/clickhouse'
import {
  buildChunkExecutionSql,
  executeBackfill,
  type BackfillProgress,
} from '@chkit/plugin-backfill/sdk'

const executor = createClickHouseExecutor({
  url: process.env.CLICKHOUSE_URL!,
  username: 'default',
  password: process.env.CLICKHOUSE_PASSWORD!,
  database: 'analytics',
})

const chunksById = new Map(plan.chunks.map((chunk) => [chunk.id, chunk]))
let saved: BackfillProgress | undefined // load from disk for resume

const result = await executeBackfill({
  executor,
  planId: plan.planId,
  chunks: plan.chunks,
  buildQuery: ({ id }) =>
    buildChunkExecutionSql({
      planId: plan.planId,
      chunk: chunksById.get(id)!,
      target: 'analytics.events_backfill',
      table: plan.table,
    }),
  concurrency: 4,
  pollIntervalMs: 5_000,
  resumeFrom: saved,
  onProgress: async (progress) => {
    saved = progress
    // persist to disk / state store
  },
})

console.log(`done=${result.completed} failed=${result.failed}`)

Plan persistence

Plans contain string boundaries that may include non-UTF-8 bytes (the planner uses latin1-encoded byte ranges for string sort keys), so JSON-serializing a ChunkPlan directly will lose information. Use the codec helpers when you need to round-trip a plan through storage:

import {
  encodeChunkPlanForPersistence,
  decodeChunkPlanFromPersistence,
} from '@chkit/plugin-backfill/sdk'

const json = JSON.stringify(encodeChunkPlanForPersistence(plan))
// later …
const plan2 = decodeChunkPlanFromPersistence(JSON.parse(json))

Logging

The planner emits structured logs via @logtape/logtape under the ['chkit', 'backfill'] category. Configure a sink at process start to see them — slow-query warnings (>5 s) are emitted at warning level, planning progress at info, and per-strategy decisions at debug.

import { configureSync, getConsoleSink, getTextFormatter } from '@chkit/plugin-backfill/sdk'

configureSync({
  sinks: { console: getConsoleSink({ formatter: getTextFormatter({ timestamp: 'time' }) }) },
  loggers: [{ category: 'chkit', sinks: ['console'], lowestLevel: 'info' }],
  reset: true,
})

To capture every SQL statement the planner runs (with timing, server-side stats, and per-strategy classification), wrap your query function instead of relying solely on logging — the wrapper sees the raw SQL and settings on every call and can record query IDs, response headers, and durations alongside the structured logs.

License

MIT

版本与发布记录

@chkit/plugin-backfill 共发布 43 个版本,首次发布于 2026/02/16;过去 12 个月发布了 43 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.2.0-beta.16latest2026/11/09今天
0.2.0-beta.142026/11/081 天前
0.2.0-beta.132026/11/081 天前
0.2.0-beta.122026/11/045 天前
0.2.0-beta.112026/10/1228 天前
0.2.0-beta.82026/09/291 个月前

关于 @chkit/plugin-backfill 的常见问题

@chkit/plugin-backfill 是什么?

Time-windowed data backfill with checkpoints for chkit

如何安装 @chkit/plugin-backfill?

在项目目录运行 npm install @chkit/plugin-backfill,或使用 pnpm add / yarn add / bun add。

@chkit/plugin-backfill 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@chkit/plugin-backfill 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@chkit/plugin-backfill 可以商用吗?

@chkit/plugin-backfill 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@chkit/plugin-backfill 的下载量有多少?

根据 npm 官方下载统计,@chkit/plugin-backfill 在 2026/10/10 – 2026/11/08 这 30 天内被下载 11,677 次,日均约 389 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@chkit/plugin-backfill 还在维护吗?

最新版本 0.2.0-beta.16 发布于 2026/11/09(今天);至今共发布 43 个版本,其中过去 12 个月发布了 43 个;首次发布于 2026/02/16。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。