Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,20 @@ All notable changes to **billion-context** are documented here.
Versions follow the merge of a `*_release-v*` branch; CI publishes to npm on tag.

## [Unreleased]
- **Storage: review-fix pass for #2690 (blocking findings from the owner review)** —
refs and blocks rows are now authoritatively replaced per ingest (a renumbered ref ledger no longer
trips the `(session_id, ord)` PK — ghost rows and destroyed-substrate block rows are deleted instead
of lingering; upsert-only zombies from #2695 can no longer resurrect); the unused `conversations`
table is dropped from the schema before v1 ships; a corrupt `index.db` degrades to legacy-only with
one warn instead of bricking the proxy (guarded open in shadow.ts); SQLite transactions now take
`BEGIN IMMEDIATE` at top level (multi-process SQLITE_BUSY_SNAPSHOT guard for the #394 topology);
`restoreReplica` refuses to overwrite a live session id (`409` at the HTTP layer) and materializes
the restored id's content-store sidecar so CCR originals survive later live saves (buildRecord drops
`forkContentStore` without a fork receipt); `exportSession`/`listSessions` close their one-shot
handles (Windows EPERM regression) and `--jsonl` degrades to the legacy renderer on an unreadable or
encrypted index. PLUGIN.md now shows the v2 fork registration example. Tests: renumbered-refs
re-ingest, zombie-block deletion, corrupt-index degradation, restore 409 + CCR sidecar round-trip
(tests/storage-review-fixes.test.ts).
- **Storage Phase 2c: `bili export --jsonl` — deterministic dump rendered from the unified tables (#2671)** —
one JSON record per line: a session header, then messages ordered by seq, then blocks ordered by ord, then
dead-ref tombstones. When the session lives in the unified index the dump comes from the tables (`source:
Expand Down
2 changes: 1 addition & 1 deletion CONFIGURATION.md
Original file line number Diff line number Diff line change
Expand Up @@ -1737,7 +1737,7 @@ File keys resolve only when the matching env var is unset. Defaults in parenthes
| `BILI_PERSIST_DEBOUNCE_MS` | Debounce window for persistence writes to disk, in ms (default `500`). |
| `BILI_PERSIST_TAIL_TOKENS` | Token budget for the persisted conversation snapshot (#401). The disk record stores the **folded view** (block summaries in place of compressed ranges) truncated to the newest messages within this budget — never the raw full history. Default `16384`; `0` disables message persistence entirely (block summaries and compressed originals still persist; `bili export` falls back to block-only rendering). Live in-memory sessions are unaffected — `bili export` of a live session is always complete. |
| `BILI_PERSIST_ZSTD` | Set `1`/`true` to enable zstd compression of session files (#1080, owner decision: **default off** — plain JSON maximizes recoverability: jq/grep-debuggable, and immune to the downgrade tail risk). When enabled, every session file that actually shrinks is written as `BILIZSTD1` — a small header (magic + format version + mode byte) over the JSON body, zstd-compressed on Node ≥ 22.15 and stored raw on older runtimes; readers accept both bodies (native zstd, else the bundled WASM fallback), so files stay readable across runtimes and versions. Payloads the framing cannot shrink (tiny sessions) and key-less raw bodies stay bare JSON on disk. Independent of `BILI_ENCRYPTION_KEY` — with both active, the compression choice is recorded in the mode byte inside `BILIENC1`. Existing plain-JSON files are NEVER rewritten at boot (downgrade safety — a mass re-encode would make rolling back to an older bili read its own writes as "corrupt"); they convert organically on their next save. Note: once a session has been saved as `BILIZSTD1`, an OLDER bili (< 0.1.135) cannot read it — this caveat applies only to deployments that opted in; unset or any other value keeps plain JSON. |
| `BILI_STORAGE_UNIFIED` | Tiered storage-migration switch (#2671). Config-file tier: `{"storage":{"unified":"legacy|shadow|full"}}` selects the same modes (strict spellings) and applies whenever the env is unset; `BILI_STORAGE_UNIFIED` (which also accepts `1`/`true` = shadow and `unified` = full) always wins over the file. The mode is resolved once per lane boot — hot edits to the file take effect on the next restart. Set `1`/`true` to enable the **unified SQLite storage dry-run** (Phase 1). Every session write is double-ingested into `<sessions-dir>/index.db` (better-sqlite3 primary, `node:sqlite` fallback) and the unified replay is digest-reconciled against the legacy load view — a mismatch logs `[storage] unified shadow DIGEST DRIFT …` and never blocks or alters the write path (legacy files stay the single source of truth). Set `full`/`unified` to enable the **drop-in read path** (Phase 1.5): `loadSync`/`boot`/`loadAll`/`loadStateForSearch` go unified-first — a legacy-file session is organically imported into the index on first open (`[storage] unified import on first open: …`) and later loads are served from `index.db`, with automatic fallback to the legacy file on any unified failure. Legacy files keep being double-written, so **rollback = unset the knob** (env and/or file value). Hard encryption opt-out: while `BILI_ENCRYPTION_KEY` is active the whole sidecar refuses to open (index.db would hold cleartext ingest payloads; a `unified sidecar DISABLED` warning is logged and the store stays legacy-only). Enumeration/GC and the web session list remain file-backed; `removeLegacyFile` now also deletes the index rows and releases CAS refcounts. Digests treat the last-writer `biliVersion` stamp and wall-clock timestamps as environment (`__VER__`/`__TS__`), everything else must match byte-for-byte. The shadow self-disables after 3 consecutive internal failures (in full mode that also flips reads back to legacy-only). **Replica/checkpoint REST (Phase 2)**: on any unified lane (shadow or full), `POST /__bili/replicas {sessionId, label?, pinned?}` freezes the session's persisted state as one content-addressed checkpoint blob + row (the resident session is flushed first), `GET /__bili/replicas[?sessionId=]` lists them, `GET /__bili/replicas/<cpId>` returns detail + byte length, `POST /__bili/replicas/<cpId>/restore {sessionId?}` materializes the checkpoint as a NEW first-class session through the normal dual write path (JSON + unified ingest; `meta.restoredFrom`/`restoredCheckpoint` record provenance), and `DELETE /__bili/replicas/<cpId>` drops it. Pinned checkpoints hold a CAS refcount and survive `deleteSession` GC (the whole point: a copy taken before a destructive experiment outlives it); explicit DELETE still removes even pinned ones. Legacy-only lanes answer 501 with the knob hint. Routes are loopback-only like the rest of `__bili`. Default off. |
| `BILI_STORAGE_UNIFIED` | Tiered storage-migration switch (#2671). Config-file tier: `{"storage":{"unified":"legacy|shadow|full"}}` selects the same modes (strict spellings) and applies whenever the env is unset; `BILI_STORAGE_UNIFIED` (which also accepts `1`/`true` = shadow and `unified` = full) always wins over the file. The mode is resolved once per lane boot — hot edits to the file take effect on the next restart. Set `1`/`true` to enable the **unified SQLite storage dry-run** (Phase 1). Every session write is double-ingested into `<sessions-dir>/index.db` (better-sqlite3 primary, `node:sqlite` fallback) and the unified replay is digest-reconciled against the legacy load view — a mismatch logs `[storage] unified shadow DIGEST DRIFT …` and never blocks or alters the write path (legacy files stay the single source of truth). Set `full`/`unified` to enable the **drop-in read path** (Phase 1.5): `loadSync`/`boot`/`loadAll`/`loadStateForSearch` go unified-first — a legacy-file session is organically imported into the index on first open (`[storage] unified import on first open: …`) and later loads are served from `index.db`, with automatic fallback to the legacy file on any unified failure. Legacy files keep being double-written, so **rollback = unset the knob** (env and/or file value). Hard encryption opt-out: while `BILI_ENCRYPTION_KEY` is active the whole sidecar refuses to open (index.db would hold cleartext ingest payloads; a `unified sidecar DISABLED` warning is logged and the store stays legacy-only). Enumeration/GC and the web session list remain file-backed; `removeLegacyFile` now also deletes the index rows and releases CAS refcounts. Digests treat the last-writer `biliVersion` stamp and wall-clock timestamps as environment (`__VER__`/`__TS__`), everything else must match byte-for-byte. The shadow self-disables after 3 consecutive internal failures (in full mode that also flips reads back to legacy-only). **Replica/checkpoint REST (Phase 2)**: on any unified lane (shadow or full), `POST /__bili/replicas {sessionId, label?, pinned?}` freezes the session's persisted state as one content-addressed checkpoint blob + row (the resident session is flushed first), `GET /__bili/replicas[?sessionId=]` lists them, `GET /__bili/replicas/<cpId>` returns detail + byte length, `POST /__bili/replicas/<cpId>/restore {sessionId?}` materializes the checkpoint as a NEW first-class session through the normal dual write path (JSON + unified ingest; `meta.restoredFrom`/`restoredCheckpoint` record provenance), and `DELETE /__bili/replicas/<cpId>` drops it. Pinned checkpoints hold a CAS refcount and survive `deleteSession` GC (the whole point: a copy taken before a destructive experiment outlives it); explicit DELETE still removes even pinned ones. Disk expectation: shadow/full roughly doubles unique-content bytes (every session has a JSON file AND index.db rows sharing a content CAS with no dedup across the two stores) and there is no auto-VACUUM — size the sessions dir accordingly while the migration runs. Legacy-only lanes answer 501 with the knob hint. Routes are loopback-only like the rest of `__bili`. Default off. |
| `BILI_PERSIST_EPERM_ALERT_THRESHOLD` | N consecutive persist write failures (`EPERM`/`EBUSY`/`EACCES`) on one session before the one-time "add this dir to antivirus exclusions" alert fires (default `5`). Windows only. See [Windows: exclude the sessions dir](#windows-exclude-the-sessions-dir-from-antivirus-362). |
| `BILI_PERSIST_EPERM_ALERT_REPEAT_MS` | Re-alert window for the persist EPERM alert, in ms. `0` (default) = alert once then stay silent; `>0` = re-alert at most every that many ms while the failures continue. |
| `BILI_TUNNEL_ALLOWED_HOSTS` | `/bili/<absolute-url>` tunnel admission for **remote clients** (#409): comma-separated `host` or `host:port` entries that unlock loopback/private destinations (e.g. a LAN relay or the machine's own sglang) for non-loopback clients. The proxy itself and link-local/metadata addresses are always denied; local (loopback) clients always pass. |
Expand Down
4 changes: 2 additions & 2 deletions PLUGIN.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# billion-context Cooperative Plugin Protocol

> Status: protocol v1, experimental. Implemented by the proxy (`src/plugin.ts`), exercised by `tests/plugin-protocol.test.ts`. Issue: dog/billion-context#1 ("内外呼应" — inside/outside cooperation).
> Status: protocol v2, experimental. Implemented by the proxy (`src/plugin.ts`), exercised by `tests/plugin-protocol.test.ts`. Issue: dog/billion-context#1 ("内外呼应" — inside/outside cooperation).

## Why

Expand Down Expand Up @@ -30,7 +30,7 @@ Fetch once at plugin startup.
```json
{
"ok": true,
"protocolVersion": 1,
"protocolVersion": 2,
"proxy": "billion-context",
"version": "0.1.42",
"toolNames": ["compress", "decompress", "search_context", "acp_status"],
Expand Down
34 changes: 26 additions & 8 deletions src/export.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,11 @@ function fmtDate(ms: number | undefined): string {

export async function listSessions(opts: ExportOptions = {}): Promise<SessionSummary[]> {
const store = new SessionStore({ dir: opts.dir, enabled: true });
// One-shot store: the constructor opens index.db in unified modes, and
// long-running callers (server exposure tick, web sessions index, plugin
// lineage) would leak one SQLite connection per call and re-break the
// Windows EPERM fix closeQuietly gave exportSession (#2690 review 4).
try {
const sessions = [...(await store.loadAll()).values()];
sessions.sort((a, b) => latestBlockTime(b) - latestBlockTime(a));
return sessions.map((s) => ({
Expand All @@ -44,6 +49,9 @@ export async function listSessions(opts: ExportOptions = {}): Promise<SessionSum
contextTokens: s.stats.contextTokens,
blocks: s.state.blocks.length,
}));
} finally {
store.closeQuietly();
}
}

function latestBlockTime(s: Session): number {
Expand Down Expand Up @@ -318,16 +326,26 @@ export async function exportSession(selector: string | undefined, opts: ExportOp
}
if (opts.jsonl) {
const index = path.join(store.dir, "index.db");
if (existsSync(index)) {
const unified = UnifiedStore.open(index);
const encrypted = process.env.BILI_ENCRYPTION_KEY !== undefined && process.env.BILI_ENCRYPTION_KEY !== "";
if (existsSync(index) && !encrypted) {
// Guarded open: a corrupt/foreign index.db must degrade to the
// legacy-tail renderer, not fail the export (#2690 review notes).
// Encryption gates the read for the same reason the ingest side
// does — index.db holds cleartext payloads, so an encrypted lane
// must never read from it.
try {
if (unified.getSessionRow(matches[0]!.id)) {
const disk = store.loadContentStore(matches[0]!);
const extra = disk ? new Map(Object.entries(disk.byRef).map(([ref, e]) => [ref, disk.byHash[e.hash] ?? ""] as const)) : undefined;
return renderSessionJsonlFromTables(unified, matches[0]!.id, opts.full ?? false, extra);
const unified = UnifiedStore.open(index);
try {
if (unified.getSessionRow(matches[0]!.id)) {
const disk = store.loadContentStore(matches[0]!);
const extra = disk ? new Map(Object.entries(disk.byRef).map(([ref, e]) => [ref, disk.byHash[e.hash] ?? ""] as const)) : undefined;
return renderSessionJsonlFromTables(unified, matches[0]!.id, opts.full ?? false, extra);
}
} finally {
unified.close();
}
} finally {
unified.close();
} catch (err) {
process.stderr.write(`[export] unified index unreadable (${String(err)}) — falling back to the legacy-tail renderer\n`);
}
}
return renderSessionJsonlFromSession(matches[0]!, opts.full ?? false, store.loadContentStore(matches[0]!));
Expand Down
Loading
Loading