dsh-memu-memory 1.4.3 → 1.4.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +3 -1
- package/CHANGELOG.md +15 -0
- package/README.md +34 -15
- package/README.zh.md +35 -13
- package/assets/screenshots/drawer.jpg +0 -0
- package/assets/screenshots/libraries.jpg +0 -0
- package/assets/screenshots/mobile.jpg +0 -0
- package/assets/screenshots/relations.jpg +0 -0
- package/assets/screenshots/settings.jpg +0 -0
- package/assets/screenshots/webui-dark.jpg +0 -0
- package/assets/screenshots/webui-memory.jpg +0 -0
- package/docs/client-conventions.md +19 -3
- package/docs/contributing.md +4 -2
- package/docs/env-and-commands.md +9 -1
- package/docs/graph-scale.md +214 -0
- package/docs/lexicon-recall.md +100 -0
- package/docs/mcp-porting.md +8 -6
- package/docs/memory-semantics.md +35 -3
- package/docs/pending-work.md +3 -1
- package/docs/retention.md +83 -0
- package/docs/rt-index.md +452 -0
- package/docs/scale-performance.md +101 -0
- package/docs/token-budget.md +92 -0
- package/docs/troubleshooting.md +50 -11
- package/lib/auto-link/apply.js +7 -2
- package/lib/auto-link/candidates.js +32 -10
- package/lib/backup.js +67 -32
- package/lib/binding-diagnostics.js +1 -1
- package/lib/bounded-cache.js +80 -0
- package/lib/client.js +2096 -409
- package/lib/consolidation-ledger.js +21 -4
- package/lib/consolidation-worker.js +14 -1
- package/lib/cycle.js +16 -11
- package/lib/diagnostic-context.js +372 -0
- package/lib/diagnostics.js +147 -61
- package/lib/embedding-download.js +7 -8
- package/lib/engine-sources.js +286 -0
- package/lib/engine.js +23 -10
- package/lib/entity-repair.js +43 -13
- package/lib/entity-review.js +64 -0
- package/lib/environment-check.js +348 -36
- package/lib/feedback.js +25 -0
- package/lib/global-graph.js +46 -2
- package/lib/graph-adjacency-index.js +525 -0
- package/lib/graph-overview.js +293 -0
- package/lib/graph.js +658 -105
- package/lib/inbound.js +44 -15
- package/lib/index-pages.js +57 -0
- package/lib/index.js +44 -6
- package/lib/inject.js +119 -50
- package/lib/lexicon-rt-source.js +25 -0
- package/lib/lexicon-rt-worker.js +26 -0
- package/lib/lexicon-rt.js +224 -0
- package/lib/lexicon-scope.js +56 -5
- package/lib/lexicon.js +143 -54
- package/lib/local-vector-service.js +3 -0
- package/lib/maintenance-ledger.js +542 -12
- package/lib/managed-runtime.js +260 -80
- package/lib/media.js +1 -1
- package/lib/memory.js +564 -131
- package/lib/port-surface.js +96 -11
- package/lib/preset-mount.js +13 -7
- package/lib/private.js +47 -21
- package/lib/recall-cache.js +20 -34
- package/lib/retention.js +173 -0
- package/lib/rpc.js +135 -52
- package/lib/rt-index/builder.js +209 -0
- package/lib/rt-index/format.js +231 -0
- package/lib/rt-index/manifest.js +105 -0
- package/lib/rt-index/reader.js +673 -0
- package/lib/rt-index-retention.js +151 -0
- package/lib/rt-index-service.js +283 -0
- package/lib/rt-index-worker.js +21 -0
- package/lib/salient-wake.js +55 -4
- package/lib/state.js +195 -24
- package/lib/temporal.js +39 -13
- package/lib/token-measurement.js +126 -0
- package/lib/tools.js +101 -6
- package/lib/turn-log.js +108 -3
- package/lib/webui/graph-layout-worker.js +68 -0
- package/lib/webui/graph-local-physics.js +390 -0
- package/lib/webui/graph-spatial-grid.js +64 -0
- package/lib/webui/graph-view.bundle.js +6 -1
- package/lib/webui/graph-view.js +478 -135
- package/lib/webui/graph-webgl-renderer.js +74 -0
- package/lib/webui/standalone.js +1 -1
- package/lib/worker-pool.js +38 -7
- package/package.json +3 -2
- package/scripts/acceptance-local.mjs +4 -10
- package/scripts/bench-all-libraries.mjs +47 -0
- package/scripts/check-classic-graph-browser.mjs +189 -0
- package/scripts/check-client-browser.mjs +929 -0
- package/scripts/check-graph-browser.mjs +6 -0
- package/scripts/check-graph-elastic-browser.mjs +139 -0
- package/scripts/check-memory-review-browser.mjs +124 -0
- package/scripts/entity-dedupe.mjs +19 -3
- package/scripts/graph-artifact-provenance.mjs +30 -0
- package/scripts/graph-freeze-manifest.mjs +129 -0
- package/scripts/graph-geometry-fixture.mjs +40 -0
- package/scripts/graph-physics-bench.mjs +218 -0
- package/scripts/graph-scale-bench.mjs +213 -0
- package/scripts/graph-scale-memory.mjs +48 -0
- package/scripts/graph-service-bench.mjs +72 -0
- package/scripts/make-readme-shots.mjs +17 -5
- package/scripts/preview.mjs +1 -0
- package/scripts/rebuild-rt.mjs +18 -0
- package/scripts/scale-bench.mjs +183 -0
- package/scripts/simulate-injection.mjs +47 -8
- package/scripts/verify-host-fixtures.mjs +108 -0
- package/scripts/verify-host-recovery.mjs +565 -0
- package/scripts/verify-vector-recovery.mjs +740 -0
- package/tests/auto-link-candidates.test.mjs +20 -0
- package/tests/browser.test.mjs +16 -2
- package/tests/client-export.test.mjs +16 -1
- package/tests/client-pagination.test.mjs +1495 -0
- package/tests/client-render.test.mjs +223 -28
- package/tests/consolidation-fork.test.mjs +97 -13
- package/tests/consolidation-ledger.test.mjs +17 -1
- package/tests/diagnostic-entity-candidates.test.mjs +54 -0
- package/tests/diagnostic-report.test.mjs +429 -0
- package/tests/diagnostic-wiring.test.mjs +88 -0
- package/tests/diagnostics.test.mjs +27 -0
- package/tests/embedding-download.test.mjs +44 -0
- package/tests/engine-source-settings.test.mjs +69 -0
- package/tests/engine-sources.test.mjs +145 -0
- package/tests/entity-dedupe.test.mjs +143 -0
- package/tests/entity-merge-review.test.mjs +363 -0
- package/tests/entity-merge.test.mjs +12 -4
- package/tests/entity-review.test.mjs +87 -0
- package/tests/environment-check.test.mjs +51 -1
- package/tests/feedback.test.mjs +95 -0
- package/tests/graph-adjacency-index.test.mjs +536 -0
- package/tests/graph-cascade.test.mjs +229 -0
- package/tests/graph-import-diagnostic.test.mjs +25 -0
- package/tests/graph-overview.test.mjs +709 -0
- package/tests/graph-session-authorization.test.mjs +419 -0
- package/tests/graph-view-geometry.test.mjs +426 -0
- package/tests/graph-view-scale.test.mjs +88 -0
- package/tests/graph-view.test.mjs +444 -5
- package/tests/graph.test.mjs +43 -0
- package/tests/help-page.test.mjs +128 -54
- package/tests/inbound.test.mjs +19 -0
- package/tests/index-pagination.test.mjs +113 -0
- package/tests/index-read-view.test.mjs +212 -0
- package/tests/inject-guide.test.mjs +9 -0
- package/tests/injection-dedupe.test.mjs +213 -0
- package/tests/lexicon-recall.test.mjs +641 -0
- package/tests/lexicon-rt-lifecycle.test.mjs +196 -0
- package/tests/lexicon-rt.test.mjs +468 -0
- package/tests/local-embedding-worker.test.mjs +38 -0
- package/tests/local-vector-service.test.mjs +32 -3
- package/tests/maintenance-compat.test.mjs +128 -0
- package/tests/maintenance-settlement.test.mjs +1003 -0
- package/tests/managed-memory.test.mjs +39 -11
- package/tests/managed-runtime.test.mjs +109 -0
- package/tests/memory-fields.test.mjs +24 -12
- package/tests/observed-evidence.test.mjs +52 -0
- package/tests/port-surface.test.mjs +93 -1
- package/tests/preset-mount.test.mjs +12 -4
- package/tests/recall-cache.test.mjs +56 -3
- package/tests/recall-dedup.test.mjs +63 -2
- package/tests/retention.test.mjs +260 -0
- package/tests/rt-index-cross-library.test.mjs +230 -0
- package/tests/rt-index-integration.test.mjs +194 -0
- package/tests/rt-index-retention.test.mjs +552 -0
- package/tests/rt-index-scale.test.mjs +204 -0
- package/tests/rt-index.test.mjs +705 -0
- package/tests/salient-date-boundaries.test.mjs +121 -0
- package/tests/salient-wake.test.mjs +29 -0
- package/tests/scale-bench.test.mjs +53 -0
- package/tests/settings-plumbing.test.mjs +25 -0
- package/tests/simulate-injection.test.mjs +15 -1
- package/tests/standalone-navigation.test.mjs +44 -0
- package/tests/state.test.mjs +51 -0
- package/tests/temporal-precision.test.mjs +102 -0
- package/tests/temporal.test.mjs +10 -6
- package/tests/token-measurement.test.mjs +98 -0
- package/tests/tool-schema.test.mjs +41 -5
- package/tests/tools.test.mjs +6 -3
- package/tests/turn-token-budget.test.mjs +149 -0
- package/tests/webui-auth.test.mjs +57 -1
- package/tests/webui.test.mjs +40 -15
- package/tests/worker-lifecycle.test.mjs +2 -1
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# Retention pass
|
|
2
|
+
|
|
3
|
+
`runRetentionPass(ctx, { now, log })` is called by the cycle sweep. It is housekeeping for caches and metadata only; it never deletes memory entries or library content.
|
|
4
|
+
|
|
5
|
+
## Safety gates
|
|
6
|
+
|
|
7
|
+
- `retentionDryRun` defaults to `true` and is the global apply gate.
|
|
8
|
+
- Bound turn-log cleanup, settled maintenance metadata cleanup, and vector/RT artifact pruning can be inspected in dry-run mode.
|
|
9
|
+
- Orphan turn-log deletion additionally requires `retentionOrphanTurnLogsEnabled: true` and a positive `retentionOrphanTurnLogDays`; default is disabled with a 90-day retention.
|
|
10
|
+
- Orphan planning and each unlink require a reliable current session registry. A quarantined or unreadable `state.json` is reported in `errors` and never treated as an empty binding catalog, including a failure after preview.
|
|
11
|
+
- Session-binding deletion additionally requires `retentionSessionBindingsEnabled: true`, a positive retention period, an old `lastTurnAt`, no live host Agent, and no unexpired consolidation lease. The binding and liveness check are repeated during apply under the state write lock.
|
|
12
|
+
- Vector artifact cleanup delegates to `pruneVectorArtifacts({ apply: false })` in dry-run mode; it preserves active/pending paths and the keep-generations policy from the existing vector-profile module.
|
|
13
|
+
- The same `retentionVectorPruneEnabled` switch and `retentionVectorDays` period also control memory and lexicon RT artifacts through `result.rtIndex`. The vector generation count policy remains specific to vector artifacts.
|
|
14
|
+
- Maintenance-ledger cleanup removes only aged `settled` metadata with a reliable `settledAt`, without `applyIntent` or an unexpired lease. It never touches memory entries.
|
|
15
|
+
|
|
16
|
+
## Settlement dates and library lifecycle
|
|
17
|
+
|
|
18
|
+
The retention clock is a strictly validated UTC ISO `settledAt`, not `createdAt`, `lastCheckedAt`, or a historical review date. Invalid calendar dates, missing legacy dates and future settlement dates are retained. A new settlement starts a full retention period; reopening clears its clock, while rescanning an already settled row neither renews it nor invents a missing date. Rows exactly on the retention cutoff remain until a later pass.
|
|
19
|
+
|
|
20
|
+
Expired settled metadata may be removed for both existing and deleted libraries. Classification uses the current `state.listLibrariesAll()` registry; archived libraries still exist. `ledger.libraries` contains historical fairness clocks and is never used as a live registry. The result keeps the existing `candidates` and `removed` arrays and adds `orphanedCandidates`, `orphanedCandidateCount`, `orphanedRemoved` and `orphanedRemovedCount` for deleted-library metadata. These are subsets of the corresponding totals, not extra removals.
|
|
21
|
+
|
|
22
|
+
Apply rereads the ledger and library registry under the maintenance lock. A changed item revision or library classification is skipped and reported in `revalidated`, even if its `settledAt` has stayed the same. Registry read failures abort this step rather than treating the registry as empty. `runRetentionPass` reports the step error and continues the other independent steps. No new nested state write lock is introduced.
|
|
23
|
+
|
|
24
|
+
## RT artifact lifecycle
|
|
25
|
+
|
|
26
|
+
`pruneRtArtifacts()` recognizes only checksum-verified `memory` and `lexicon` manifests whose `namespace`, document version, `libraryId`, identity and published references agree. Under the same `current.json` publication lock used by RT writers, it rereads the current library registry (including archived libraries) and checks the namespace's canonical truth path. An unregistered library is an orphan only when that truth path is also absent. Global memory RT is never an orphan. Missing or corrupt pointers, unknown identities, unreadable registries and linked or nonordinary artifact trees cannot authorize deletion. Truth files are never cleanup targets.
|
|
27
|
+
|
|
28
|
+
Old unreferenced generations/segments are eligible in both preview and apply. An orphan's published generation, referenced segments and pointer become eligible together only after every known artifact and the pointer are strictly older than the cutoff; a newer unused artifact keeps the ownership pointer for a later pass. Apply removes known artifacts and then the pointer while holding the publication lock. It releases that lock before attempting nonrecursive removal of empty `segments` and identity directories. Unknown files and newly acquired locks keep their directories intact.
|
|
29
|
+
|
|
30
|
+
The `lexicon` namespace uses separate truth at `lexicon/<libraryId>.json` and the string `global` for its global library; memory uses `index/<libraryId>.json` and null for global. Old unreferenced lexicon generations/segments can retire under the same age policy while current references remain. Global lexicon is never orphaned, even without a canonical global file. An unregistered lexicon with a remaining or linked truth path is retained; missing memory truth alone never proves lexicon orphanhood. Tests in `tests/rt-index-retention.test.mjs` verify active/archived/global libraries, dry-run/apply parity, actual recall, truth preservation and dangling truth links. Automatic cleanup still defaults to dry-run and never deletes memory entries or lexicon terms.
|
|
31
|
+
|
|
32
|
+
## Maintenance journal
|
|
33
|
+
|
|
34
|
+
`maintenance.json` remains a complete version-1 checkpoint (`version`, `items`, `libraries` and any unknown root metadata). An optional `_journal` anchor adds a random generation, the canonical SHA-256 of that checkpoint, the exact previous journal token, and an anchor checksum. Old JSON images without an anchor are accepted. The memory fact indexes and their source-of-truth contract are unchanged.
|
|
35
|
+
|
|
36
|
+
Current mutations append only changed item/library/root values to `maintenance.journal.jsonl`, under the same `maintenance.json.lock` used by reads, checkpoints, retention and restore. Each newline-terminated record contains its generation, base hash, physical baseline-file identity, consecutive sequence, parent hash, patch and SHA-256 checksum. Writes use a verified explicit append offset, loop over short writes and require file `fsync` before returning. On Windows this uses a read/write handle so an uncommitted suffix can be truncated safely. Mutation callbacks must be synchronous and cannot nest another write, restore or checkpoint. A no-op appends nothing; an exception cannot persist the callback's partial edits.
|
|
37
|
+
|
|
38
|
+
Maintenance uses a dedicated same-path lock: elapsed age never evicts a verified live PID, and writes verify the owner's unique token. A displaced owner refuses its stale append and cannot remove a replacement owner's lock. Empty/invalid lock payloads become recoverable after a grace period, while a verified dead PID can be reclaimed immediately.
|
|
39
|
+
|
|
40
|
+
`loadMaintenanceLedger()` validates the snapshot and every committed record before replay. It returns a complete logical version-1 image without `_journal`, so existing before-effect and after-effect crash-image recovery remains supported. `applyIntent` is durable before a memory effect and is not dropped by checkpoint, retention or replay; live leases and unknown metadata also survive. Incremental disk writes do not imply O(1) CPU or reads: loading/replay and mutation diffing still scan the checkpoint and bounded journal.
|
|
41
|
+
|
|
42
|
+
### Commit and checkpoint recovery
|
|
43
|
+
|
|
44
|
+
- A newline is the record commit marker. Only the final suffix lacking a newline is uncommitted, even if that suffix happens to be valid JSON. Readers warn and leave it intact; the next successful append truncates only that suffix. Complete malformed/blank/invalid-UTF-8 lines, bad patches, checksum/sequence/parent failures and mismatched anchors block reads, mutations, backups and checkpoints. Errors use `DSH_MEMU_MAINTENANCE_JOURNAL_INVALID` or `DSH_MEMU_MAINTENANCE_JOURNAL_IO`, with a warning; the committed bytes remain available for recovery.
|
|
45
|
+
- Checkpoint runs at 128 records or 1 MiB, whichever is reached first (one larger patch may cross the byte limit). It uses atomic `writeJson` with file `fsync`, then atomically rotates to a synced empty journal. Directory `fsync` is best effort where unsupported. The initial journal is created before publishing the first anchored snapshot. A subsequently missing journal, a missing baseline with an existing journal (even an empty one), or an existing JSON `null` is never treated as an empty queue. Existing `readFailure` quarantine/write protection is preserved.
|
|
46
|
+
- Failure before snapshot rename leaves the previous snapshot and committed journal usable. Failure after rename but before rotation is recognized only by the new anchor's exact previous generation/base/sequence/head token; those covered records are not reapplied. Other journal generations are refused. If automatic checkpoint fails after a durable append, the commit remains successful with a warning; the next mutation must checkpoint before appending more.
|
|
47
|
+
- Physical baseline identity additionally detects raw replacement of an anchored JSON file followed by reuse of a matching-generation journal. Copying a checkpoint over the live file is not a restore operation. Use managed restore or `restoreMaintenanceSnapshot()` so a fresh generation is published. Hash chains detect damaged or reordered records that remain in the file; they are not a substitute for backups against removal of an entire valid trailing suffix or deletion of both store files.
|
|
48
|
+
|
|
49
|
+
### Backup, restore and compatibility
|
|
50
|
+
|
|
51
|
+
`state.backupDatabases()` supplies the synchronous checkpoint hook to `backup.createBackup()`. `writeStores()` also provides the same hook by default for direct callers. While holding `maintenance.json.lock`, backup checkpoints and copies the complete `maintenance.json` into staging. The existing inventory checksum covers it; no live journal is included. This makes each new managed backup self-contained and avoids a snapshot/journal copy race. A corrupt or unreadable live store aborts publication instead of making an incomplete backup.
|
|
52
|
+
|
|
53
|
+
Restore validates the entire inventory and maintenance anchor before replacing live files, then creates the existing protected safety backup. Under the maintenance lock it writes the requested queue with a fresh generation and rotates the live journal. The lock is released before copying the remaining stores to keep maintenance contention bounded. Old journal records cannot reappear after restore, even when the restored backup has the same data/hash as an earlier checkpoint. A backup predating maintenance snapshots preserves and checkpoints the current queue rather than clearing it. A later copy failure still reports the safety backup, whose full checkpoint can restore the prior pending intents and leases. Restore is recoverable, not an atomic transaction across all stores; stop concurrent writers for a manual transfer. If a damaged live ledger prevents a reliable safety backup, managed restore refuses as well; preserve/repair the damaged bytes before retrying rather than silently bypassing `readFailure`.
|
|
54
|
+
|
|
55
|
+
Backup lock reentrancy belongs to one asynchronous operation, tracked with `AsyncLocalStorage`. A restore can await its own safety-backup hook, but unrelated same-process create/delete/prune calls receive `DSH_MEMU_STORE_BUSY` until it completes. An empty lock left by a crash before the PID write is recoverable after the grace period instead of blocking backups permanently.
|
|
56
|
+
|
|
57
|
+
The new lock direction is `backup -> maintenance(file)`. No maintenance operation acquires the backup lock, no index commit hook is added, and no state write lock is acquired under the maintenance lock. `state.js` integration is confined to `backupDatabases()`.
|
|
58
|
+
|
|
59
|
+
For compatibility, an explicitly supplied complete legacy JSON image without `_journal` is treated as an import, never as a baseline for replaying a newer journal. A warning is emitted; before the next checkpoint/write, the verified superseded journal is durably preserved as `maintenance.journal.jsonl.superseded-<uuid>`. It is not automatically deleted. This supports the existing logical crash-image consumers without silently erasing their recovery evidence. Damaged journals are still refused before an import can proceed.
|
|
60
|
+
|
|
61
|
+
Old readers can read the version-1 checkpoint, but it may lag the journal. Before raw export, stop writers and call `checkpointMaintenanceLedger()` under the same lock, then copy the complete checkpoint. For an older full-image writer, export the complete logical image returned by `loadMaintenanceLedger()` (without `_journal`) after checkpointing; keep the now-empty journal. Do not pass an anchored image to an old writer: if it edits data while preserving the old anchor, the next upgrade will correctly refuse that stale checksum. Do not run old and new writers concurrently. Managed backup/restore is the supported transfer path; copying only a live, uncheckpointed `maintenance.json` is not a complete backup. Tests in `tests/maintenance-settlement.test.mjs` cover incremental persistence, process restart/concurrency, torn tails, committed corruption, checkpoint failures, stale replay, legacy downgrade/upgrade, backup hooks and safety-backup rollback; the original prepared-effect recovery tests also remain in `tests/maintenance.test.mjs`.
|
|
62
|
+
|
|
63
|
+
## Date boundary contract
|
|
64
|
+
|
|
65
|
+
Salient date checks used by passive injection and scheduled wake share `normalizeSalientDate`, `salientDaysAhead` and `salientDateFires`. A short `MM-DD` must be a real month-day: `02-29` is allowed, but `02-30` and `04-31` are rejected. An anniversary fires only on its own calendar day, with no lead day; a leap-day anniversary fires only on an actual February 29, never on February 28 or March 1 in a common year. `salientDaysAhead` remains `null` for anniversaries because they have no specific due year.
|
|
66
|
+
|
|
67
|
+
A one-off `YYYY-MM-DD` keeps its actual year and the existing day-before/day-of reminder window. Invalid one-off dates remain invalid in both the firing and distance functions, so `2027-02-29` cannot roll over into March. Month/year prose preserves month/year precision without manufacturing an exact day; relative year boundaries such as `明年年底` resolve against the scene year. Tests cover the 2100 common-year and 2400 leap-year rules as well as agreement between injection and scheduled delivery.
|
|
68
|
+
|
|
69
|
+
## Schedule list capability
|
|
70
|
+
|
|
71
|
+
Salient wake reconciliation reads the full task catalog before creating or deleting anything. It uses the public `catalog()` method when present; otherwise it pages the global list with `{ limit, offset }`, validating page offsets, totals, IDs, and page progress. The reference API verified from the DSH 0.2.3-alpha.2 source mirror exposes this shape; that source mirror is not proof of the running installation. An older host that ignores or rejects offset is diagnosed and the pass stops before side effects.
|
|
72
|
+
|
|
73
|
+
## Turn-log durability
|
|
74
|
+
|
|
75
|
+
Turn-log append and atomic rewrite create/use files with mode `0600`, fsync file content before close/rename, and best-effort fsync the containing directory after atomic replacement. Directory fsync may be unsupported on a filesystem/platform; file fsync remains mandatory.
|
|
76
|
+
|
|
77
|
+
## Configuration
|
|
78
|
+
|
|
79
|
+
The state settings are surfaced through `updateSettings`, the settings RPC allowlists and reset action, and the bilingual settings UI. Retention durations must be positive; `retentionVectorKeepGenerations` must be 1–100. No background setting enables orphan cleanup or session binding deletion by itself.
|
|
80
|
+
|
|
81
|
+
## Limits and operational notes
|
|
82
|
+
|
|
83
|
+
The settings affect the periodic cycle pass, not a manual one-shot command. Dry-run candidates are diagnostics, not proof that a concurrent binding cannot appear after an orphan check; orphan cleanup should therefore stay opt-in and use generous retention. The DSH API reference came from a source checkout at 0.2.3-alpha.2 and must be checked against the actual runtime when host pagination behavior changes.
|
package/docs/rt-index.md
ADDED
|
@@ -0,0 +1,452 @@
|
|
|
1
|
+
# Disposable retrieval index
|
|
2
|
+
|
|
3
|
+
JSON indexes remain the only source of truth. The `rt/` directory contains
|
|
4
|
+
rebuildable heads, inverted postings and raw UTF-8 body shards. It contains no
|
|
5
|
+
second serialized entry database. Deleting or corrupting derived data must
|
|
6
|
+
produce source results and an observable rebuild request on that same query.
|
|
7
|
+
|
|
8
|
+
## Controller And Source
|
|
9
|
+
|
|
10
|
+
```js
|
|
11
|
+
import { createRtIndex } from '../lib/rt-index/reader.js'
|
|
12
|
+
|
|
13
|
+
const controller = createRtIndex({
|
|
14
|
+
directory, libraryId, // null identifies the global library
|
|
15
|
+
namespace: 'memory',
|
|
16
|
+
mode: 'shadow', // off | shadow | on; also DSH_MEMU_RT_INDEX; default shadow
|
|
17
|
+
logger,
|
|
18
|
+
onSignal: event => scheduleRebuild(event),
|
|
19
|
+
})
|
|
20
|
+
const source = { index, revision, count, fingerprint: revision }
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
`index.entries` contains the existing authoritative entries, with canonical IDs
|
|
24
|
+
as keys. `revision` is a nonempty data revision supplied by the caller, normally
|
|
25
|
+
`state.indexDataRevision(index)`. It is not calculated by hashing hot-query
|
|
26
|
+
bodies. `fingerprint` is optional and defaults to revision. An explicit integer
|
|
27
|
+
`count` avoids `Object.keys(entries)` in `sourceInfo`; otherwise only frozen
|
|
28
|
+
entry collections cache their count. Do not mutate an admitted source snapshot
|
|
29
|
+
without assigning a new revision.
|
|
30
|
+
|
|
31
|
+
The service uses `indexReadRevision(index)` separately in permission/view cache
|
|
32
|
+
keys because day, expiry and authorization changes can change eligibility
|
|
33
|
+
without changing the indexed data revision. The caller owns visibility, read
|
|
34
|
+
scope freshness and permission cache keys. Do not reuse another role's view.
|
|
35
|
+
|
|
36
|
+
`documentText(entry)` optionally replaces the default body/tags/attachment-caption
|
|
37
|
+
projection. Supply a different `documentVersion` when its semantics change.
|
|
38
|
+
Titles are passed separately to the shared `buildCorpus`. The ruler fingerprint
|
|
39
|
+
also covers the shared retrieval, tokenizer and curator-policy source files.
|
|
40
|
+
|
|
41
|
+
## Query Views
|
|
42
|
+
|
|
43
|
+
```js
|
|
44
|
+
const view = controller.createView(source, {
|
|
45
|
+
isVisible: (entry, id) => eligible(entry, id),
|
|
46
|
+
// Or visibleIds: prequalifiedIds. Both can be supplied to intersect them.
|
|
47
|
+
})
|
|
48
|
+
const result = view.score(tokens) // tokens may also be a query string
|
|
49
|
+
// { hits:[{id,score}], corpus:{size,avgdl,df:Map}, stats,
|
|
50
|
+
// backend:'rt'|'source', mode, fallback, comparison }
|
|
51
|
+
const postings = view.queryPostings(tokens)
|
|
52
|
+
// { docs:Map<id,{id,len,tf:Map,order}>, totalLen,
|
|
53
|
+
// corpus:{size,avgdl,df:Map}, visited, backend, mode, fallback, shadow }
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
Eligibility is evaluated once when a view is created, before N, document
|
|
57
|
+
frequency and average document length are calculated. No rich memory file
|
|
58
|
+
objects are built for the whole library. All selected documents contribute to
|
|
59
|
+
N and total length, including documents with no matching query term. Only query
|
|
60
|
+
terms occur in the returned `df` and per-document `tf` maps.
|
|
61
|
+
|
|
62
|
+
Default candidates are the union of **every matching query-term posting**.
|
|
63
|
+
Single-word and single-CJK-character candidates are preserved. `dfCap` and
|
|
64
|
+
`minShared` are explicit opt-ins to `view.candidates(tokens, options)` and
|
|
65
|
+
`candidatesFromPostings`; recall does not enable them. The original shared
|
|
66
|
+
`bm25` remains responsible for its own frequency gate, 64-term policy, formula
|
|
67
|
+
and repeated query term handling. Score/date ties retain source selection
|
|
68
|
+
order. Date boosts, evidence scoring and final recall ranking remain in memory
|
|
69
|
+
consumers.
|
|
70
|
+
|
|
71
|
+
Derived `score` may avoid allocating document/tf maps for a term that the shared
|
|
72
|
+
`bm25` frequency gate proves contributes zero. It still reads and validates every
|
|
73
|
+
query posting, counts authorized active df exactly, preserves the complete union
|
|
74
|
+
in `stats.candidates`, and returns df for gated terms too. A temporary bitset uses
|
|
75
|
+
one bit per eligible ID; it is not cached. `stats.materialized` reports the number
|
|
76
|
+
of document maps actually scored. Low-frequency posting spans remain single-pass.
|
|
77
|
+
If a raw posting count suggests gating but permissions or superseded segments
|
|
78
|
+
lower the true df enough to score, only that term is read a second time before
|
|
79
|
+
materialization. `stats.postingsVisited` includes those physical repeat visits.
|
|
80
|
+
The shared scorer still owns the frequency gate, 64-term policy, repetition and
|
|
81
|
+
all numeric contributions; the final call uses the original query token sequence.
|
|
82
|
+
|
|
83
|
+
This allocation optimization applies only to single-corpus derived `score`.
|
|
84
|
+
`queryPostings` and default `candidates` always return the complete posting union,
|
|
85
|
+
including every locally gated term. Cross-library consumers must retain these
|
|
86
|
+
postings until the joint corpus df is known. The no-snapshot source oracle is
|
|
87
|
+
unchanged and continues its document-at-a-time projection.
|
|
88
|
+
|
|
89
|
+
For cross-library BM25, combine the filtered `size`, **integer `totalLen`** and
|
|
90
|
+
per-term `df` from every eligible library, including small/unavailable derived
|
|
91
|
+
libraries through source views. Calculate `avgdl = totalLen / size` once. Score
|
|
92
|
+
query-posting documents using that one corpus and composite `[libraryId,id]`
|
|
93
|
+
identities. Do not fuse independently normalized per-library BM25 scores or
|
|
94
|
+
recover integer lengths by multiplying floating-point `avgdl * size`.
|
|
95
|
+
|
|
96
|
+
`createQueryView(source, visibility)` is the pure source oracle, with the same
|
|
97
|
+
API and no filesystem access. Its source fallback tokenizes one document at a
|
|
98
|
+
time; it does not cache a whole source corpus. A snapshot may be passed as
|
|
99
|
+
`{snapshot,...visibility}` for low-level derived queries. Such low-level views
|
|
100
|
+
and snapshots are caller-owned and require explicit validation and bounded
|
|
101
|
+
lifetimes.
|
|
102
|
+
|
|
103
|
+
Every controller view query (`score`, `queryPostings`, `candidates`, heads) checks
|
|
104
|
+
the current pointer, manifest and high-resolution artifact stamps. There is no
|
|
105
|
+
TTL window for detecting missing directories, same-size writes or corruption.
|
|
106
|
+
SHA-256 checks stream all artifacts at **cold admission only**. Query term reads
|
|
107
|
+
also check their stamps after reading. A cached view can be refreshed using
|
|
108
|
+
`view.validate(freshSource)`; a revision mismatch never continues using the old
|
|
109
|
+
snapshot. Source fallback applies during that call and emits a signal.
|
|
110
|
+
|
|
111
|
+
Reuse the same source wrapper for repeated calls on the same index. Refreshing
|
|
112
|
+
with a different index object updates entry references and rebuilds the derived
|
|
113
|
+
view even when its semantic revision is unchanged; this costs O(selected IDs),
|
|
114
|
+
without rerunning a predicate for unchanged source metadata. It ensures score
|
|
115
|
+
tie-breaks, heads and fallback use the current authoritative entries. The upper
|
|
116
|
+
service stabilizes source wrappers with a WeakMap keyed by index identity.
|
|
117
|
+
|
|
118
|
+
`controller.validate(source)` returns `{ok,generation,revision}` or `{ok:false,code}`.
|
|
119
|
+
`controller.open(source)` returns `{ok,snapshot,validate}` and reuses the bounded
|
|
120
|
+
snapshot cache. It does not recompute the visibility selection. It deliberately
|
|
121
|
+
returns a strong caller-owned snapshot reference. Never retain arbitrary many
|
|
122
|
+
such objects in application caches.
|
|
123
|
+
|
|
124
|
+
## Storage And Bounds
|
|
125
|
+
|
|
126
|
+
Format version **2** contains immutable segments:
|
|
127
|
+
|
|
128
|
+
- `heads.bin`: 16-byte header plus one 64-byte little-endian record per document.
|
|
129
|
+
- `metadata.json`: canonical IDs and interned domain/layer/status/visibility.
|
|
130
|
+
- `postings.bin`: header and sorted `(uint32 slot,uint16 tf,padding)` records.
|
|
131
|
+
- `terms.bin`: sorted JSON-line term/offset/count rows; no full dictionary Map.
|
|
132
|
+
- `terms.json`: one sparse anchor per 128 terms, with checked byte/posting bounds.
|
|
133
|
+
- `removed.json`: incremental tombstones; no memory bodies or second fact store.
|
|
134
|
+
- `bodies/NNNNNNNN.bin`: raw UTF-8 content, byte offsets from heads.
|
|
135
|
+
|
|
136
|
+
Default body shards are 16MiB, with streaming writes and individual-document
|
|
137
|
+
range reads; this does not allocate a 16MiB read buffer. Explicit `shardBytes`
|
|
138
|
+
still overrides the default. Existing v2 segments with 1MiB shards remain fully
|
|
139
|
+
readable. Their artifact count changes only after rebuilding, not on a read.
|
|
140
|
+
|
|
141
|
+
Postings are written in 64KiB buffers. A query reads its term dictionary block
|
|
142
|
+
and corresponding posting spans, at most 64KiB per posting buffer. Snapshots
|
|
143
|
+
retain heads, metadata, sparse anchors and active document references, **not**
|
|
144
|
+
entire posting files or full vocabulary maps. Process-wide caches have 96MiB
|
|
145
|
+
estimated snapshot capacity and an additional 8MiB estimated term-block
|
|
146
|
+
capacity; both have entry caps and non-sliding 60-second TTL. Cache byte counts
|
|
147
|
+
are estimates, not RSS measurements. Oversized snapshots are refused, which is
|
|
148
|
+
observable in `rtIndexCacheStats().oversized`; arbitrary document sizes are not
|
|
149
|
+
promised to fit.
|
|
150
|
+
|
|
151
|
+
Before cold allocation, a conservative heads/JSON/active-reference working-set
|
|
152
|
+
estimate above 128MiB produces `RT_READ_LIMIT` and source fallback. This protects
|
|
153
|
+
cold admission separately from the 96MiB resident-cache limit; it is still an
|
|
154
|
+
estimate rather than an exact V8/RSS measurement.
|
|
155
|
+
|
|
156
|
+
Full builds split into bounded segments, normally at 96MiB estimated working
|
|
157
|
+
data or 8192 documents. `maxBuildBytes` defaults to 192MiB and is an estimate /
|
|
158
|
+
single-document safety guard, not a hard V8 heap reservation. `segmentDocs`
|
|
159
|
+
can lower the batch document cap. At most 128 segments, 7 incremental segments,
|
|
160
|
+
256MiB per artifact and 16MiB per document are accepted. Unsupported bounds
|
|
161
|
+
produce a rebuild/fallback signal rather than silently truncated data. `tf`
|
|
162
|
+
overflow above uint16 is rejected, never saturated.
|
|
163
|
+
|
|
164
|
+
Controller views hold only WeakRefs to cached derived snapshots. Eviction can
|
|
165
|
+
release them even if the upper service caches its permission view. Source
|
|
166
|
+
entries and predicates never enter the process-wide derived caches. Term blocks
|
|
167
|
+
have a separate bounded LRU and no source references. Reads close descriptors
|
|
168
|
+
in `finally`; no persistent handles or body cache are retained.
|
|
169
|
+
|
|
170
|
+
A derived view held through a WeakRef may itself be collected even while its
|
|
171
|
+
binary snapshot remains cached. The next call then reconstructs its selected-ID
|
|
172
|
+
map without rerunning the caller predicate. This is a remaining O(selected IDs)
|
|
173
|
+
allocation after collection, rather than a guarantee of allocation-free hot
|
|
174
|
+
requests. The nine-query scale loop does not force GC between query samples.
|
|
175
|
+
|
|
176
|
+
## Builds And Recovery
|
|
177
|
+
|
|
178
|
+
```js
|
|
179
|
+
controller.rebuild(source)
|
|
180
|
+
controller.afterCommit({
|
|
181
|
+
source, previousRevision, previousFingerprint,
|
|
182
|
+
changedIds, removedIds,
|
|
183
|
+
})
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
Builds are synchronous primitives: the upper service schedules worker builds.
|
|
187
|
+
Incremental input must be a complete, already-committed delta, serialized per
|
|
188
|
+
library. It retokenizes only changed entries, appends immutable segments and
|
|
189
|
+
shadows old slots by ID; removed entries receive tombstones. At the delta cap,
|
|
190
|
+
`RT_COMPACTION_REQUIRED` requests a full rebuild. There is no claim that JSON
|
|
191
|
+
truth-store serialization, diff discovery or a full memory write is O(1).
|
|
192
|
+
|
|
193
|
+
Long construction runs outside the `current.json` lock. All new segments remain
|
|
194
|
+
in this build's private staging directories until publication. Under the shared
|
|
195
|
+
pointer lock, the builder rechecks the starting pointer/base revision, promotes
|
|
196
|
+
segments, publishes a fsynced generation manifest and atomically replaces the
|
|
197
|
+
pointer. A concurrent publication produces `RT_BUILD_STALE`; it is never
|
|
198
|
+
overwritten by the older build. Failed builds retain the previous pointer.
|
|
199
|
+
Cleanup removes only validated, randomly named staging paths owned by that
|
|
200
|
+
build. A failure after promotion can leave unreferenced immutable artifacts for
|
|
201
|
+
retention; builder never deletes production generations or source data.
|
|
202
|
+
|
|
203
|
+
`controller.invalidate(code)` / `quarantine(code)` perform **logical** quarantine,
|
|
204
|
+
evict this library's caches and reject its current generation until a new one
|
|
205
|
+
is published. They do not rename or delete disk directories. Failure signals:
|
|
206
|
+
|
|
207
|
+
```js
|
|
208
|
+
{ code, operation, fallback:true, rebuildRequired:true,
|
|
209
|
+
action:'schedule-rebuild' }
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
The upper service must schedule rebuild/backoff and expose the failure in recall
|
|
213
|
+
diagnostics. Warnings and counters do not contain bodies, API keys or IDs.
|
|
214
|
+
`compareFinal(expectedHits,actualHits)` checks exact IDs, score equality and
|
|
215
|
+
order for final shadow results. Default shadow returns the oracle result.
|
|
216
|
+
|
|
217
|
+
The cross-library consumer additionally calls service `noteRtComparison` once
|
|
218
|
+
per joint shadow comparison, using only composite identity and lexical score.
|
|
219
|
+
This updates the service counters exposed by `getState.rtIndex`. Score/order
|
|
220
|
+
and evidence mismatches also propagate `RT_SHADOW_MISMATCH` through recall
|
|
221
|
+
errors and binding diagnostics; source files remain the returned result.
|
|
222
|
+
Evidence-only failures remain explicit errors even when lexical-score parity
|
|
223
|
+
alone is equal. Synthetic fault tests prove signaling, not a gold-corpus rate.
|
|
224
|
+
|
|
225
|
+
## Heads, Bodies And Retention
|
|
226
|
+
|
|
227
|
+
`getSortedHeads(source,{visibleIds/isVisible,sortBy,descending,offset,limit,fields})`
|
|
228
|
+
exists on the controller, and without `source` on a view. It returns lightweight
|
|
229
|
+
projected `heads`, `total` and `snapshotRevision`. Only the selected page is
|
|
230
|
+
decoded into projected head objects; sorting still costs O(N log N). It is not
|
|
231
|
+
an O(1) paging index. `view.orderOf(id)` provides the existing source tie order
|
|
232
|
+
without copying every selected ID on each query.
|
|
233
|
+
|
|
234
|
+
`readBody(source,id,{visibleIds:[id],isVisible})` checks authorization before IO,
|
|
235
|
+
reads that one UTF-8 body span and returns `{body,backend,fallback}`. Source
|
|
236
|
+
content wins after any missing/corrupt derived body.
|
|
237
|
+
|
|
238
|
+
`listArtifacts(options)` / `controller.listArtifacts()` are read-only inventories
|
|
239
|
+
of generations and segments. `referenced:false` means unreferenced by a valid
|
|
240
|
+
current manifest; unreadable metadata produces `referenced:null` for safe
|
|
241
|
+
retention. Manifests include checked `namespace` and `libraryId` alongside the
|
|
242
|
+
hash identity. Unknown older manifests cannot prove orphan ownership and must
|
|
243
|
+
be retained. The separate retention module owns deletion, rechecking inventory
|
|
244
|
+
and liveness under the `current.json` lock.
|
|
245
|
+
|
|
246
|
+
## Verification
|
|
247
|
+
|
|
248
|
+
Run targeted tests with complete logs:
|
|
249
|
+
|
|
250
|
+
```powershell
|
|
251
|
+
node --import ./tests/loader-register.mjs --test tests/rt-index.test.mjs tests/rt-index-cross-library.test.mjs tests/rt-index-integration.test.mjs tests/rt-index-retention.test.mjs > logs/rt-index-targeted.log 2>&1
|
|
252
|
+
$env:DSH_MEMU_RT_SCALE_COUNT='100000'
|
|
253
|
+
node --expose-gc --import ./tests/loader-register.mjs --test tests/rt-index-scale.test.mjs > logs/rt-index-scale-100k.log 2>&1
|
|
254
|
+
# Optional extra profiling queries, separate from the unchanged nine hot samples:
|
|
255
|
+
$env:DSH_MEMU_RT_PROFILE='1'
|
|
256
|
+
node --expose-gc --max-old-space-size=768 --import ./tests/loader-register.mjs --test tests/rt-index-scale.test.mjs > logs/rt-index-profile-100k.log 2>&1
|
|
257
|
+
```
|
|
258
|
+
|
|
259
|
+
The scale test is opt-in and uses independent temporary data, seed 1444,
|
|
260
|
+
40-600-character random content with 60-95% CJK. It measures construction, cold
|
|
261
|
+
admission, cached rare-word queries, a frequent single-character posting union,
|
|
262
|
+
source-oracle time, authorized-view creation/first-query time, cache estimates
|
|
263
|
+
and process memory. Source-oracle and first-view times are single observations,
|
|
264
|
+
not P95 values. It asserts exact source/derived scores and filtered corpus
|
|
265
|
+
statistics, records start/end implementation hashes, and checks that hot
|
|
266
|
+
queries never rehash all artifacts or reread complete postings. This is a
|
|
267
|
+
foundation measurement, not end-to-end memory recall, host latency, retrieval
|
|
268
|
+
quality evidence, a general 100k guarantee or an overall memory bound.
|
|
269
|
+
|
|
270
|
+
### Measured 100k Evidence, 2026-11-30
|
|
271
|
+
|
|
272
|
+
`logs/rt-index-scale-100k-r4.log` completed with 1 test / 1 pass / 0 fail / 0 skip,
|
|
273
|
+
exit 0, Node v24.15.0 on Windows, `--max-old-space-size=768 --expose-gc`.
|
|
274
|
+
The source fixture uses flat strings, with the same random content distribution
|
|
275
|
+
and seed; it does not retain a large rope-string allocation from fixture setup.
|
|
276
|
+
Timing occurred in a shared development environment, not an isolated host.
|
|
277
|
+
|
|
278
|
+
| Measurement | Observed |
|
|
279
|
+
|---|---:|
|
|
280
|
+
| Documents / visible documents | 100000 / 66666 |
|
|
281
|
+
| Immutable base segments | 20 |
|
|
282
|
+
| Build | 57489.88ms |
|
|
283
|
+
| Total artifact bytes / postings bytes | 506875189 / 335728832 |
|
|
284
|
+
| First query with cold admission | 1338.21ms |
|
|
285
|
+
| Cached rare-word P50 / P95, 9 samples | 56.44ms / 63.41ms |
|
|
286
|
+
| Frequent single-character union, 66666 candidates | 235.40ms |
|
|
287
|
+
| Snapshot cache estimate / term-block estimate | 38845494 / 443928 bytes |
|
|
288
|
+
| Oversized cache refusals | 0 |
|
|
289
|
+
| Total posting bytes for first + 9 cached rare queries | 80 |
|
|
290
|
+
| Whole-artifact hashes during those cached queries | 0 |
|
|
291
|
+
| Source fixture RSS before build / whole-process peak RSS | 304214016 / 596316160 bytes |
|
|
292
|
+
| Heap used before build / after build + explicit GC | 100089056 / 98674072 bytes |
|
|
293
|
+
|
|
294
|
+
The earlier r1 log records successful 50-segment construction with a 391.77ms
|
|
295
|
+
rare-query P95; r2 records buffered dictionary writes and fewer repeated stats,
|
|
296
|
+
with 164.43ms P95. R3 increased the bounded batch estimate to 96MiB to reduce
|
|
297
|
+
validation fanout and recorded 77.93ms P95. R4 includes the cold-admission
|
|
298
|
+
working-set guard and recorded 63.41ms P95. These are successive measurements,
|
|
299
|
+
not comparable isolated microbenchmark trials; R4 does not prove the guard
|
|
300
|
+
itself improved query latency.
|
|
301
|
+
|
|
302
|
+
**The pre-packing checkpoint did not meet 50ms.** Validation still stats every
|
|
303
|
+
referenced artifact on every call, and a high-frequency query must enumerate its
|
|
304
|
+
entire posting union. No validation TTL, default df-cap or two-term pruning was
|
|
305
|
+
introduced to hide those costs. A source fallback/default-shadow query still
|
|
306
|
+
tokenizes all eligible source documents. Full service/final memory recall,
|
|
307
|
+
cross-library 100k latency, larger vocabularies, shadow parity on a representative
|
|
308
|
+
gold corpus and host behavior remain separate central acceptance work. Cache
|
|
309
|
+
estimates and the observed heap recovery do not prove a universal derived-RSS
|
|
310
|
+
limit or the end-to-end write target.
|
|
311
|
+
|
|
312
|
+
### Hot-Path Profiling
|
|
313
|
+
|
|
314
|
+
`logs/rt-index-profile-100k-baseline-r1.log` uses the same 100000 documents, seed
|
|
315
|
+
1444 and nine uninstrumented hot samples as above. Source entries, visibility,
|
|
316
|
+
query terms and the frequent 66666-candidate union are unchanged. Additional
|
|
317
|
+
profiling queries use synchronous-fs timing and V8 CPU sampling, and do not
|
|
318
|
+
replace any of the original nine samples.
|
|
319
|
+
|
|
320
|
+
The baseline contained 216 artifacts and recorded rare-query P95 78.01ms.
|
|
321
|
+
Across nine extra profiling queries, 2016 `lstat` calls consumed 580.33ms
|
|
322
|
+
(224 calls / 64.48ms per query). CPU sampling also identifies native `lstat`
|
|
323
|
+
as the dominant query work; manifest parsing and BM25 were small by comparison.
|
|
324
|
+
The first bounded optimization therefore changes only default body-shard
|
|
325
|
+
packing from 1MiB to 16MiB. Every pointer/manifest/artifact validation remains,
|
|
326
|
+
with no validation TTL or reduced candidate set. Reader and scoring code do
|
|
327
|
+
not change for this optimization. Baseline source scan took 23691.80ms including
|
|
328
|
+
view creation; an authorized view's first call over an admitted snapshot took
|
|
329
|
+
287.22ms including creation. These are foundation timings, not service timings.
|
|
330
|
+
|
|
331
|
+
`logs/rt-index-profile-100k-shards-r2.log` then completed 1 test / 1 pass / 0 fail /
|
|
332
|
+
0 skip, exit 0, with only the builder default changed. Artifact count dropped
|
|
333
|
+
from 216 to 140, while total artifact bytes (506875189), posting bytes (335728832),
|
|
334
|
+
segment count (20), source data and every candidate remained unchanged. Nine
|
|
335
|
+
additional profiling queries made 1332 `lstat` calls in 394.47ms: 148 calls /
|
|
336
|
+
43.83ms per query. The original nine uninstrumented hot samples recorded
|
|
337
|
+
40.87ms P50 / 44.17ms P95. This run crosses 50ms only for that stable-hot rare
|
|
338
|
+
query, not for full recall or every query class.
|
|
339
|
+
|
|
340
|
+
The same run's source scan was 13547.58ms including source-view creation; the
|
|
341
|
+
authorized view's first call was 227.67ms (87.00ms creation + 140.68ms query over
|
|
342
|
+
an admitted snapshot). Cold admission plus first query took 1309.79ms, excluding
|
|
343
|
+
the initial permission-view creation. The frequent union still contained 66666
|
|
344
|
+
candidates and took 147.31ms. Build took 78606.26ms. Source-path and build-time
|
|
345
|
+
variation is reported as observed, not attributed to a reader/scorer change:
|
|
346
|
+
neither was modified. Exact source/derived scores and filtered corpus statistics
|
|
347
|
+
matched. Stable-hot samples do not include rebuilding a WeakRef view after GC.
|
|
348
|
+
|
|
349
|
+
An independent repeat, `logs/rt-index-profile-100k-shards-r3.log`, also completed
|
|
350
|
+
1 test / 1 pass / 0 fail / 0 skip, exit 0. All four runtime source fingerprints
|
|
351
|
+
match r2, and each run checks that they remain unchanged through measurement.
|
|
352
|
+
The original nine stable-hot samples are logged individually in r3; their range
|
|
353
|
+
was 41.05-46.89ms. No samples or candidates were removed.
|
|
354
|
+
|
|
355
|
+
| Foundation phase | Pre-packing r1 | 16MiB r2 | Independent 16MiB r3 |
|
|
356
|
+
|---|---:|---:|---:|
|
|
357
|
+
| Source view creation + one source scan | 23691.80ms | 13547.58ms | 13371.00ms |
|
|
358
|
+
| Authorized view creation, admitted snapshot | 92.03ms | 87.00ms | 88.76ms |
|
|
359
|
+
| First query on that authorized view | 195.18ms | 140.68ms | 145.02ms |
|
|
360
|
+
| Authorized first total | 287.22ms | 227.67ms | 233.78ms |
|
|
361
|
+
| Stable-hot rare P50 / P95, nine samples | 67.17 / 78.01ms | 40.87 / 44.17ms | 42.75 / 46.89ms |
|
|
362
|
+
| Frequent union, all 66666 candidates | 185.72ms | 147.31ms | 180.14ms |
|
|
363
|
+
| Cold admission + first query, view creation excluded | 1582.34ms | 1309.79ms | 1517.20ms |
|
|
364
|
+
| Artifact count / per-query lstat count | 216 / 224 | 140 / 148 | 140 / 148 |
|
|
365
|
+
|
|
366
|
+
Both optimized stable-hot rare-query runs measured below 50ms. This is not an
|
|
367
|
+
end-to-end service/recall guarantee: first permission views, GC reconstruction,
|
|
368
|
+
source fallback, cold admission and frequent unions remain slower. Nine-sample
|
|
369
|
+
P95 here is the largest of the nine measurements, not a long production trace.
|
|
370
|
+
The profiling sampler and fs timers run only in nine additional queries, outside
|
|
371
|
+
the nine uninstrumented latency samples. R3's diagnostic lstat time was 468.00ms
|
|
372
|
+
across those extra queries; instrumented timing is reported separately, not
|
|
373
|
+
substituted for the latency measurements. Rebuild existing 1MiB generations to
|
|
374
|
+
obtain the lower file count; no read-time migration or source mutation occurs.
|
|
375
|
+
|
|
376
|
+
### Score-Only Frequency-Gate Profiling
|
|
377
|
+
|
|
378
|
+
Set `DSH_MEMU_RT_GATE_PROFILE=1` in addition to the scale-count flag to measure
|
|
379
|
+
nine uninstrumented scores for `['海']` and `['海','needle1','needle1']` on the same
|
|
380
|
+
fixed 100000-document fixture. The original nine rare-query measurements and the
|
|
381
|
+
full 66666-candidate `queryPostings(['海'])` measurement remain. If profiling is
|
|
382
|
+
also enabled, each query class receives nine additional instrumented calls. A
|
|
383
|
+
separate streaming source-postings scan plus the shared scorer checks exact
|
|
384
|
+
scores, eligible corpus statistics and the complete frequent ID union. This
|
|
385
|
+
extra oracle scan is outside the reported single source-query timing.
|
|
386
|
+
|
|
387
|
+
`logs/rt-index-gate-100k-baseline-r1.log` recorded frequent-score P95 156.68ms and
|
|
388
|
+
mixed-score P95 189.29ms. In nine extra single-term profiling calls, posting-query
|
|
389
|
+
CPU self samples totalled 666.29ms, GC 68.78ms and BM25 33.53ms, with 440.20ms in
|
|
390
|
+
1674 `lstat` calls. These diagnostics identify full candidate document/tf-map
|
|
391
|
+
construction as avoidable work in addition to the mandatory artifact checks.
|
|
392
|
+
|
|
393
|
+
The score-only optimization leaves artifacts, full union queries and the source
|
|
394
|
+
oracle unchanged. In `logs/rt-index-gate-100k-optimized-r2.log`, frequent and mixed
|
|
395
|
+
P95 were 83.02ms and 85.45ms. Their union counts remained 66666 and their physical
|
|
396
|
+
posting visits remained 100000 / 100001; only 0 / 1 document maps were materialized.
|
|
397
|
+
The single-term profile's posting CPU samples fell to 281.18ms; it still performed
|
|
398
|
+
1674 `lstat` calls, this time taking 366.66ms. Filesystem timing also improved, so
|
|
399
|
+
the entire wall-time reduction must not be attributed to allocation changes.
|
|
400
|
+
The full frequent union itself still took 128.06ms in that run and remains an
|
|
401
|
+
independent, unchanged cross-library building block.
|
|
402
|
+
|
|
403
|
+
Both r1 and r2 completed 1 test / 1 pass / 0 fail / 0 skip, exit 0. Each used the
|
|
404
|
+
same source seed, 100000 documents, 66666 visible documents, 20 segments, 140
|
|
405
|
+
artifacts, 506875189 artifact bytes and 335728832 posting bytes. R1's rare hot P95
|
|
406
|
+
was 44.29ms; r2's was 35.89ms. These are nine-sample foundation observations,
|
|
407
|
+
not service guarantees, and frequent scores still exceed 50ms.
|
|
408
|
+
|
|
409
|
+
The independent `logs/rt-index-gate-100k-optimized-r3.log` also passed 1 / 1 with
|
|
410
|
+
0 failures / 0 skips, exit 0. Its runtime fingerprints match r2; both runs check
|
|
411
|
+
their start/end fingerprints. R3 rare samples ranged 31.53-40.92ms, so its strict
|
|
412
|
+
nine-sample P95 is 40.92ms, not an average across runs. Frequent-score P95 rose to
|
|
413
|
+
111.86ms and mixed-score P95 to 96.21ms; all samples remain in the logs. Candidate
|
|
414
|
+
counts, posting visits and 0 / 1 materialized maps match r2 exactly.
|
|
415
|
+
|
|
416
|
+
| Foundation phase | Baseline r1 | Optimized r2 | Independent r3 |
|
|
417
|
+
|---|---:|---:|---:|
|
|
418
|
+
| Source view creation + one source scan | 11849.67ms | 10858.60ms | 10163.67ms |
|
|
419
|
+
| Authorized view creation, admitted snapshot | 123.52ms | 66.92ms | 82.98ms |
|
|
420
|
+
| First query on that authorized view | 208.89ms | 131.06ms | 158.01ms |
|
|
421
|
+
| Authorized first total | 332.41ms | 197.98ms | 240.99ms |
|
|
422
|
+
| Stable-hot rare P95, nine samples each | 44.29ms | 35.89ms | 40.92ms |
|
|
423
|
+
| Frequent score P95, nine samples each | 156.68ms | 83.02ms | 111.86ms |
|
|
424
|
+
| Mixed score P95, nine samples each | 189.29ms | 85.45ms | 96.21ms |
|
|
425
|
+
| Full frequent posting union, one observation | 146.01ms | 128.06ms | 130.87ms |
|
|
426
|
+
|
|
427
|
+
The full frequent union still has 66666 documents. Artifact bytes, fixture and
|
|
428
|
+
sample counts match all three runs; no candidate cap, segmentation or tokenizer
|
|
429
|
+
changes were used. Source/build/first-view variation is not attributed to the
|
|
430
|
+
score optimization. R3 cold admission plus first query was 1146.56ms, excluding
|
|
431
|
+
initial permission-view creation. Process peak RSS was 635248640 bytes across
|
|
432
|
+
build, source scans and profiling; it is not a derived-layer memory bound. The
|
|
433
|
+
review found no new retained document maps, source references, caches or open
|
|
434
|
+
descriptors: bitsets and span arrays are query-local and range reads keep their
|
|
435
|
+
existing `finally`-close path. This structural review is not a universal leak
|
|
436
|
+
proof. Full service latency, frequent queries below 50ms, GC view reconstruction
|
|
437
|
+
and representative gold/shadow parity remain separate unproven requirements.
|
|
438
|
+
|
|
439
|
+
The final nine-file regression command (rt-index, cross-library, integration,
|
|
440
|
+
retention, scale with its normal opt-in skip, managed-memory, memory-fields,
|
|
441
|
+
observed-evidence and index-pagination) passed in
|
|
442
|
+
`logs/rt-index-gate-final-regression-r4.log`: 194 tests / 193 pass / 0 fail /
|
|
443
|
+
1 skip, exit 0. The earlier r2 regression log is retained: six files failed to
|
|
444
|
+
load while the shared graph module imported a not-yet-created
|
|
445
|
+
`graph-adjacency-index.js`; r4 reran the same command after that file appeared,
|
|
446
|
+
without changing P2 source. Independent foundation validation passed 102 tests /
|
|
447
|
+
101 pass / 0 fail / 1 skip in `logs/rt-index-gate-final-foundation-r3.log`.
|
|
448
|
+
Syntax, UTF-8/CRLF, scoped diff checks and the three-run workload/fingerprint
|
|
449
|
+
comparison are recorded in `logs/rt-index-gate-final-syntax-format.log`,
|
|
450
|
+
`logs/rt-index-gate-final-diff-check.log` and
|
|
451
|
+
`logs/rt-index-gate-evidence-check.log`. Full npm/acceptance/check and host
|
|
452
|
+
validation remain centrally coordinated; this is a scoped P2 close-out.
|