@push.rocks/smartdb 5.0.0 → 5.0.2

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.
@@ -59,4 +59,4 @@ export const normalizeSmartDbResourceFenceError = (errorArg) => {
59
59
  }
60
60
  return new SmartDbResourceFenceError(match[1], match[2], error);
61
61
  };
62
- //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2VydmljZS10eXBlcy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uL3RzL3RzX3NtYXJ0ZGIvc2VydmljZS10eXBlcy50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiQUErQ0EsTUFBTSxDQUFDLE1BQU0sOEJBQThCLEdBQUc7SUFDNUMsaUJBQWlCO0lBQ2pCLGNBQWM7SUFDZCx1QkFBdUI7SUFDdkIsb0JBQW9CO0lBQ3BCLDBCQUEwQjtJQUMxQiwyQkFBMkI7SUFDM0Isc0JBQXNCO0lBQ3RCLHNCQUFzQjtJQUN0QixhQUFhO0lBQ2IseUJBQXlCO0lBQ3pCLDRCQUE0QjtJQUM1QixpQkFBaUI7SUFDakIsc0NBQXNDO0lBQ3RDLHNCQUFzQjtJQUN0QixzQkFBc0I7SUFDdEIsa0NBQWtDO0lBQ2xDLDJCQUEyQjtDQUNuQixDQUFDO0FBdUdYLE1BQU0sQ0FBQyxNQUFNLDBDQUEwQyxHQUFHO0lBQ3hELHdCQUF3QjtJQUN4Qiw0QkFBNEI7SUFDNUIsaUJBQWlCO0lBQ2pCLHdCQUF3QjtJQUN4QiwwQkFBMEI7Q0FDbEIsQ0FBQztBQUtYLE1BQU0sT0FBTyxxQ0FBc0MsU0FBUSxLQUFLO0lBRzlELFlBQ0UsT0FBbUQsRUFDbkQsVUFBa0IsRUFDbEIsUUFBa0I7UUFFbEIsS0FBSyxDQUFDLEdBQUcsT0FBTyxLQUFLLFVBQVUsRUFBRSxFQUF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.rocks/smartdb",
3
- "version": "5.0.0",
3
+ "version": "5.0.2",
4
4
  "private": false,
5
5
  "description": "A MongoDB-compatible embedded database server with wire protocol support, backed by a high-performance Rust engine.",
6
6
  "exports": {
@@ -42,6 +42,12 @@
42
42
  "readme.md",
43
43
  "third-party-notices.md"
44
44
  ],
45
+ "publishConfig": {
46
+ "executableFiles": [
47
+ "./dist_rust/rustdb_linux_amd64",
48
+ "./dist_rust/rustdb_linux_arm64"
49
+ ]
50
+ },
45
51
  "keywords": [
46
52
  "mongodb-compatible",
47
53
  "wire protocol",
package/readme.md CHANGED
@@ -540,6 +540,7 @@ const db = new LocalSmartDb({
540
540
  | `getServer()` | `SmartdbServer` | Access the underlying server |
541
541
  | `running` | `boolean` | Whether the server is running |
542
542
  | `LocalSmartDb.inspectOfflineStringValue(input, options?)` | `Promise<TLocalSmartDbOfflineStringValueInspectionResult>` | Read one exact top-level string value from stopped file storage without starting or mutating the engine |
543
+ | `LocalSmartDb.inspectOfflinePhysicalNamespaces(input, options?)` | `Promise<ILocalSmartDbOfflinePhysicalNamespaceInspectionResult>` | Validate stopped physical file storage and return only deterministic database and collection names |
543
544
 
544
545
  #### Offline String-Value Inspection
545
546
 
@@ -593,6 +594,67 @@ The TypeScript API enforces these bounds before creating the sidecar or serializ
593
594
 
594
595
  All numeric limits must be positive safe integers. The caller must stop and retain external ownership of the `LocalSmartDb` daemon for the full call. Current storage roots additionally enforce this through SmartDB's storage-owner lock. Roots created before that lock existed rely on the caller's external single-owner coordination plus descriptor and stability validation. One `timeoutMs` budget covers sidecar lookup/spawn, readiness, and the command. Cancellation or timeout kills and reaps the disposable sidecar before the call rejects.
595
596
 
597
+ #### Offline Physical Namespace Inspection
598
+
599
+ `inspectOfflinePhysicalNamespaces()` is a Linux-only management API for validating and listing the physical database and collection namespaces in a stopped SmartDB file-storage root. It uses Linux `openat2` descriptor traversal and starts only the disposable Rust management sidecar. It never calls `SmartdbServer.start()`, opens a database listener, initializes the storage adapter, runs migration or recovery, repairs a tail, truncates a WAL, compacts data, or persists a hint.
600
+
601
+ ```typescript
602
+ import { LocalSmartDb } from '@push.rocks/smartdb';
603
+
604
+ const namespaces = await LocalSmartDb.inspectOfflinePhysicalNamespaces({
605
+ folderPath: '/var/lib/myapp/smartdb',
606
+ limits: {
607
+ maximumEntries: 100_000,
608
+ maximumDatabases: 4096,
609
+ maximumCollections: 10_000,
610
+ maximumIndexes: 100_000,
611
+ maximumDataFileBytes: 256 * 1024 * 1024,
612
+ maximumWalFileBytes: 64 * 1024 * 1024,
613
+ maximumIndexFileBytes: 16 * 1024 * 1024,
614
+ maximumTotalFileBytes: 1024 * 1024 * 1024 * 1024,
615
+ maximumRecordsPerCollection: 1_000_000,
616
+ maximumRecordBytes: 17 * 1024 * 1024,
617
+ maximumResultBytes: 16 * 1024 * 1024,
618
+ },
619
+ }, {
620
+ timeoutMs: 30_000,
621
+ });
622
+
623
+ // {
624
+ // schemaVersion: 1,
625
+ // databases: [
626
+ // { name: 'myapp', collections: ['MetadataDoc', 'system.views'] },
627
+ // ],
628
+ // }
629
+ ```
630
+
631
+ The result is exactly `{ schemaVersion: 1, databases: Array<{ name, collections }> }`. Databases and each database's collections are sorted by physical name, empty database directories are retained, and no documents, index definitions, record identifiers, or values cross the management boundary.
632
+
633
+ The accepted root must contain the current `.__rustdb_internal/storage-owner.lock`; legacy roots without that lock are rejected. The sidecar takes the shared owner lock, so an active engine causes the call to fail. Every reported collection must have the canonical complete profile of regular `data.rdb`, `wal.rdb`, and `indexes.json` files. A regular `keydir.hint` is optional and is treated only as an allowed cache file. Missing canonical files, unexpected collection entries, malformed index metadata, invalid data or WAL records, symlinks, cross-filesystem traversal, resource-limit exhaustion, and changes observed during inspection fail the complete operation. No partial result is returned and the storage tree is not mutated.
634
+
635
+ Inspection performs two full bounded passes and returns only if their namespace results and retained filesystem observations agree. The entry, database, collection, index, file-byte, and record limits are enforced independently on each pass, so total validation work is at most twice the corresponding caller cap. The result-size cap applies to the single serialized result. This is a contract for the current owner-locked canonical SmartDB file-storage profile, not a claim of compatibility with arbitrary MongoDB layouts, legacy SmartDB roots, or unspecified future storage formats.
636
+
637
+ All limits are required; this API supplies no defaults or compatibility aliases. TypeScript validates the following bounds before creating the sidecar and revalidates `folderPath` after resolving it to an absolute path:
638
+
639
+ | Input | Enforced range |
640
+ |---|---|
641
+ | `folderPath` | 1 to 4096 UTF-8 bytes before and after absolute resolution; no control characters |
642
+ | Complete serialized request | At most 2,097,152 bytes |
643
+ | `timeoutMs` | 1 to 2,147,483,647 milliseconds |
644
+ | `maximumEntries` | 1 to 100,000 directory entries per pass |
645
+ | `maximumDatabases` | 1 to 4,096 databases per pass |
646
+ | `maximumCollections` | 1 to 10,000 collections per pass |
647
+ | `maximumIndexes` | 1 to 100,000 index definitions per pass |
648
+ | `maximumDataFileBytes` | 64 to 268,435,456 bytes per data file |
649
+ | `maximumWalFileBytes` | 64 to 67,108,864 bytes per WAL file |
650
+ | `maximumIndexFileBytes` | 2 to 16,777,216 bytes per index file |
651
+ | `maximumTotalFileBytes` | 1 to 1,099,511,627,776 aggregate canonical collection-file bytes per pass |
652
+ | `maximumRecordsPerCollection` | 1 to 1,000,000 data records plus WAL records/commit markers per collection per pass |
653
+ | `maximumRecordBytes` | 22 to 17,825,792 bytes per record |
654
+ | `maximumResultBytes` | 32 to 16,777,216 serialized result bytes |
655
+
656
+ Every numeric value must be a safe integer. One optional `timeoutMs` budget and `AbortSignal` cover sidecar lookup/spawn, readiness, both inspection passes, and response delivery; timeout or cancellation kills and reaps the sidecar before rejection. For a point-in-time ownership proof, the caller must exclude every engine start and other storage lifecycle change continuously from before invocation through acceptance or handoff of the returned result. The owner lock proves that the engine was stopped during inspection, but it cannot replace that caller-held lifecycle exclusion after the sidecar releases its lock.
657
+
596
658
  ### SmartdbDebugServer
597
659
 
598
660
  Web-based debug dashboard served via `@api.global/typedserver`. Import from the `debugserver` subpath:
@@ -853,6 +915,18 @@ const names = await collection.distinct('name');
853
915
 
854
916
  Advertises MongoDB wire protocol versions 0–21. The documented command surface is tested with the official `mongodb` Node.js driver version 7.5.x.
855
917
 
918
+ ### Read and Write Concerns
919
+
920
+ SmartDB 5.x does not implement MongoDB `readConcern` or `writeConcern`
921
+ semantics. A command containing either top-level field is rejected with
922
+ `InvalidOptions` (code 72) before authentication, session creation, transaction
923
+ preparation, publication-gate acquisition, or database mutation. Callers must not
924
+ interpret a successful SmartDB 5.x response as a majority or replica-backed
925
+ acknowledgement. The exact `writeConcern: { w: 0 }` envelope used by the official
926
+ driver for `endSessions`, and the equivalent envelope on `killSessions`, are
927
+ accepted only to preserve best-effort session cleanup; neither is a database-write
928
+ acknowledgement.
929
+
856
930
  ---
857
931
 
858
932
  ## Rust Crate Architecture 🦀
package/readme.plan.md CHANGED
@@ -1,101 +1,296 @@
1
- # smartdb advancement plan
1
+ # SmartDB advancement plan
2
2
 
3
- Status: canonical direction, approved 2026-07-21. Reread before starting any engine work.
4
- Baseline: @push.rocks/smartdb 2.13.2 (TypeScript API + rustdb Rust engine, ~36k Rust LOC, 255 test fns).
3
+ Status: canonical direction, approved 2026-08-17. Reread before starting engine or
4
+ managed-service work.
5
5
 
6
- ## North star
6
+ Baseline: `@push.rocks/smartdb` 5.0.1. SmartDB is a Rust database engine with a
7
+ TypeScript lifecycle facade, a MongoDB wire-protocol command surface, file and
8
+ memory storage, authentication, transactions, resource fencing, and official
9
+ MongoDB Node.js driver integration.
7
10
 
8
- Make smartdb a boring database:
11
+ ## Product objective
9
12
 
10
- - **provably crash-consistent** — recovery behavior is a written contract, enforced by a harness, not an aspiration
11
- - **cost proportional to change** — a write that changes nothing costs nothing; a small change costs a small amount of WAL, oplog, index, and CPU
12
- - **bounded** — memory, cursors, sessions, scans, and on-disk growth all have enforced ceilings
13
- - **self-describing** — the engine can explain its own resource usage and slow operations without external tooling
13
+ Build SmartDB into a commercially operated, MongoDB-driver-compatible managed
14
+ database service in this order:
14
15
 
15
- ## Evidence base (incident ledger)
16
+ 1. truthful and provable single-node engine
17
+ 2. certified compatibility profile
18
+ 3. managed single-node service
19
+ 4. replicated high-availability service
20
+ 5. whole-database placement and migration
21
+ 6. intra-database sharding only when customer scale requires it
16
22
 
17
- Every track below traces to a production incident on the dcrouter hub:
23
+ Reimplementing MongoDB-compatible server behavior is the fixed strategy. It does
24
+ not require inventing every persistence primitive: SmartDB owns the wire,
25
+ semantic, execution, topology, and service contracts while the storage-substrate
26
+ decision remains evidence-driven.
18
27
 
19
- 1. **Immortal cursors / unreaped sessions** — cursors and transaction sessions accumulated without bound. Fixed in 2.13.x (`CursorOwner`, per-cursor and global byte caps in `rustdb-commands/src/context.rs`, `remove_connection_cursors`, `take_expired_sessions`). The class stays closed only if bounded-lifecycle remains a tested invariant.
20
- 2. **Query-vs-storage divergence** — an empty `_id_` query index was created at restart while the storage KeyDir still held documents. Queries said "not found"; inserts hit the storage-layer duplicate check (`rustdb-storage/src/memory.rs` / `file.rs` `AlreadyExists`) and threw "already exists: document '<sha>'". Mitigated in 2.13.x (index rebuild at startup, quarantine of invalid legacy unique indexes). The invariant — query layer and storage layer must never disagree after recovery — is not yet machine-checked.
21
- 3. **Write amplification on unchanged saves** — callers re-saving identical documents caused full document rewrites plus full before/after images in the oplog (10k entries / 64MB), driving rustdb to 45–82% CPU. Currently mitigated caller-side only (change-gated persistence in the main consumer). The engine still trusts callers not to churn.
22
- 4. **Bulk-operation ceilings** — deleteMany batch limits and command-size caps made a large startup migration exceed its deadline and forced a rollback. Bulk work is client-paced, non-resumable, and dies with its connection.
23
- 5. **Memory disproportion** — steady-state PSS reached 40–100× live data bytes at points (dual tree+hash indexes per field, allocator retention, oplog images). No ceiling is asserted anywhere.
28
+ ## Legal and provenance gate
24
29
 
25
- ## Track 1 Provable durability (foundation, non-negotiable)
30
+ The official MongoDB wire-protocol documentation and specifications carry terms
31
+ that expressly restrict commercial database and database-as-a-service adaptation.
32
+ This plan does not interpret those terms. Before expanding compatibility work:
26
33
 
27
- - Write the **recovery contract**: for a process kill at any byte offset — during WAL append, compaction, or hint write — state exactly what is durable, what may be lost, and what is rebuilt.
28
- - Build a **crash-fuzz harness**: property-based runner that executes randomized workloads, kills the engine at random points, restarts, and asserts the invariants:
29
- 1. every acknowledged write is present
30
- 2. no phantom documents
31
- 3. query indexes agree exactly with the storage KeyDir (incident 2 becomes a permanent regression class)
32
- 4. unique constraints hold
33
- 5. cursor/session tables are empty after recovery
34
- - Make the harness a **CI gate**: no release ships without it green.
34
+ - obtain written legal guidance for interoperability, clean-room implementation,
35
+ product claims, and trademarks
36
+ - audit the provenance of existing compatibility code and tests
37
+ - classify disputed material for retention, independent rewrite, or quarantine
38
+ - document which behavioral evidence and test sources implementation teams may use
39
+ - market the service under an approved SmartDB identity and compatibility claim
35
40
 
36
- Provable property: "kill -9 at any moment loses at most unacknowledged writes, and recovery always converges to a consistent index/storage view."
41
+ No compatibility feature enters a commercial release without passing this gate.
37
42
 
38
- ## Track 2 — Write-path economics: cost proportional to change
43
+ ## Maintenance policy
44
+
45
+ SmartDB 5.x is the maintenance lane for existing consumers:
39
46
 
40
- - **Engine-side no-op write detection** — SHIPPED in 2.14.0: update/findAndModify post-images that equal the stored document (or differ only in the volatile `_updatedAt` metadata field) skip storage, WAL, index, and oplog entirely and report `matched=1, modified=0`. Counters in `serverStatus.writes`. Caller-side gating remains defense in depth, not the architecture.
41
- - **Oplog diet**: replace full before/after images with `{ns, id, opType, generation, optional patch}`. Consumers that need images read storage at the generation.
42
- - **Background compaction** (bitcask merge) with cooldown and rate limit, bounding `data.rdb` growth under update churn.
43
- - **Group commit**: coalesce WAL fsyncs across concurrent writers.
47
+ - accept security fixes, data-correctness fixes, explicit rejection of unsupported
48
+ behavior, and bounded operability improvements
49
+ - do not add broad MongoDB surface area or introduce a second durability model
50
+ - keep persisted 5.x behavior supported until a tested offline conversion or
51
+ snapshot/restore migration into Storage VNext exists
52
+ - release small fixes independently when their invariants and compatibility impact
53
+ can be verified in isolation
44
54
 
45
- Provable property: "N identical saves cost O(1) WAL bytes and O(1) oplog bytes after the first."
55
+ Storage VNext is developed behind explicit format and capability boundaries. It
56
+ must never dual-write through both the legacy and VNext commit paths.
46
57
 
47
- ## Track 3 — Read-path economics
58
+ ## North-star architecture
48
59
 
49
- - **Index-assisted top-k**: extend the bounded sorted-scan work (2.13.2) so the planner walks an index in sort order instead of scanning and heap-selecting.
50
- - **Maintained aggregates**: per-collection counts and sizes served from maintained state, never full scans.
51
- - **Reads never schedule writes**: engine principle — no read path may enqueue hint rewrites, stat persistence, or any other write work.
60
+ ### Wire gateway
52
61
 
53
- Provable property: "a monitoring read loop at any frequency produces zero engine writes."
62
+ - parse and encode the declared wire profile exactly
63
+ - validate complete command schemas before acquiring resources or mutating state
64
+ - advertise only capabilities and limits proven by target-driver handshake tests
65
+ - reject every unsupported command, concern, or option explicitly
54
66
 
55
- ## Track 4 — Server-side bulk and migration primitives
67
+ ### BSON semantic core
56
68
 
57
- - **Uncapped bulk operations**: deleteMany/updateMany execute engine-side with internal checkpointing (by generation / seek offset), not client-paced batches under command-size caps.
58
- - **Streaming IPC frames** for large results, retiring the command-size failure class.
59
- - **Re-attachable maintenance sessions**: a migration survives client disconnect; the client re-attaches by operation id and polls progress. The incident-4 rollback class becomes impossible.
60
-
61
- Provable property: "a 10M-row migration survives a client restart and completes exactly once."
62
-
63
- ## Track 5 — Memory model: bounded and measured
64
-
65
- - **k-factor target**: steady-state PSS live data bytes (observed today: 40–100× under some workloads).
66
- - **Single index representation** per field where one suffices; lazy-build the second form on demand.
67
- - KeyDir compaction / shrink-to-fit after mass deletes.
68
- - **Soak-test CI gate**: 24h synthetic churn workload asserting PSS plateaus within the k-factor.
69
- - Verify mimalloc purge/decommit settings under the soak test.
70
-
71
- Provable property: "PSS is a function of live data, not of history."
72
-
73
- ## Track 6 Operability and compatibility
74
-
75
- - **serverStatus counters**: no-op writes skipped, WAL bytes written, compaction stats, live cursors/sessions, per-collection sizes — the next incident gets diagnosed from the database, not from strace.
76
- - **Slow-op log** with thresholds.
77
- - **Offline toolbox**: `rustdb verify | dump | compact | repair-doc | backup` against a data directory.
78
- - **On-disk format manifest** with versioning and an N-1 rollback contract: any release can downgrade one release; format changes require a migration note.
79
-
80
- Allocation fencing exception: once a database name has an allocation-managed resource-lock marker, pre-allocation binaries intentionally fail closed. N-1 rollback must restore an allocation-aware binary; deleting or rewriting provider allocation metadata is not a supported downgrade path.
81
-
82
- Provable property: "any resource question an operator asks during an incident is answerable from serverStatus or the toolbox."
83
-
84
- ## Fork in the road (decision rule, written now)
85
-
86
- Keep hardening the owned engine **while the Track 1 harness stays green**. If, after Tracks 1–2 land, the harness keeps finding structural durability holes, evaluate rebasing the storage layer on a proven embedded core (redb or fjall) behind the unchanged command surface. Revisit this rule once Track 1 is merged — not before, not on gut feeling.
87
-
88
- ## Sequencing
89
-
90
- - **Done**: Track 2 no-op write detection + its serverStatus counters (2.14.0).
91
- - **Now** (after the current consumer release wave is verified in production): Track 1 harness + recovery contract.
92
- - **Next**: Track 2 oplog diet + compaction; Track 4 bulk primitives.
93
- - **Mid-term**: Track 3 read economics; Track 5 k-factor + soak gate; Track 6 toolbox + format manifest.
94
-
95
- Format-affecting changes (oplog diet, manifest) target a major version; everything else lands in 2.14+.
96
-
97
- ## Non-goals
98
-
99
- - clustering or replication beyond the current oplog consumers
100
- - MongoDB API parity
101
- - multi-process writers
69
+ - own one implementation of BSON equality, ordering, hashing, numeric promotion,
70
+ null/missing behavior, array traversal, typed identifiers, projections,
71
+ expressions, and updates
72
+ - feed the same semantics into queries, indexes, transactions, aggregation,
73
+ uniqueness checks, and change streams
74
+
75
+ ### Planner and executor
76
+
77
+ - use one planner for find, count, update, delete, aggregate, and explain
78
+ - stream storage-backed cursors instead of materializing complete result sets
79
+ - enforce deadlines, cancellation, admission, and work accounting at every loop
80
+
81
+ ### Transactional storage kernel
82
+
83
+ - own one authoritative, checksummed, monotonically ordered commit log
84
+ - assign a stable timeline and LSN to every committed mutation
85
+ - commit documents, DDL, catalogs, index definitions, users, retryable-write
86
+ outcomes, and transaction outcomes through the same atomic boundary
87
+ - serve database-wide MVCC snapshots and deterministic checkpoint-plus-log recovery
88
+
89
+ ### Replication
90
+
91
+ - replicate the committed Storage VNext log through a reviewed consensus design
92
+ - use consensus terms to fence leaders; allocation fencing controls placement and
93
+ publication but never substitutes for data-plane consensus
94
+ - derive majority acknowledgement, failover, snapshot installation, causal times,
95
+ and retry outcomes from the replicated commit history
96
+
97
+ ### Administration and control plane
98
+
99
+ - keep RBAC-protected database administration such as `currentOp`, `killOp`,
100
+ `explain`, and user management available through the certified wire surface
101
+ - keep service administration such as provisioning, placement, billing, backup,
102
+ restore, upgrades, and incident actions on a separate privileged API
103
+ - start with one process per tenant or isolated replica group; shared-process
104
+ tenancy requires hard per-tenant admission and noisy-neighbor proof
105
+
106
+ ## Phase 0: contract and measurement
107
+
108
+ - complete the legal and provenance gate
109
+ - select the first exact driver, ODM, topology, command, option, and error profile
110
+ - maintain raw-wire and target-driver handshake tests
111
+ - publish an out-of-band machine-readable compatibility manifest
112
+ - version engine build, wire profile, storage format, and service API independently
113
+ - establish baseline latency, memory, disk amplification, and restart benchmarks on
114
+ Linux amd64 and arm64
115
+
116
+ Gate: approved implementation sources and claims, an exact compatibility profile,
117
+ and reproducible baseline measurements.
118
+
119
+ ## Phase 1: truthful single-node behavior
120
+
121
+ - stop over-advertising MongoDB version, wire behavior, and batch limits
122
+ - reject ignored concerns, options, commands, and successful administrative stubs
123
+ - validate OP_MSG required flags, checksums, and no-response behavior
124
+ - preserve complete BSON type and value identity for document and index keys
125
+ - reconcile ambiguous point-write failures before returning control to callers
126
+ - journal DDL and sync every required file and parent directory
127
+ - distinguish incomplete final records from interior corruption and fail closed
128
+ - isolate or secure all debug and privileged management surfaces
129
+ - add an operation registry, deadlines, cancellation, real `currentOp`/`killOp`, and
130
+ truthful metrics
131
+ - write acknowledgement, recovery, corruption, and supported-filesystem contracts
132
+
133
+ Gate: deterministic failpoints and randomized crashes produce no acknowledged-write
134
+ loss, phantom documents, query/storage divergence, or unique-constraint violations
135
+ within the declared single-node fault model.
136
+
137
+ ## Phase 2: conformance foundation
138
+
139
+ - build a legally approved behavioral comparison harness
140
+ - fuzz raw wire framing, flags, malformed BSON, and command boundaries
141
+ - validate commands into typed internal representations before execution
142
+ - add exact response, error-code, error-label, and side-effect contracts
143
+ - generate semantic corpora across BSON types, boundaries, arrays, null/missing,
144
+ NaN, Decimal128, projections, paths, expressions, and identifiers
145
+ - prevent any advertised capability from expanding without associated tests
146
+
147
+ Gate: no known P0/P1 mismatch in the certified profile, and every unsupported path
148
+ rejects before side effects.
149
+
150
+ ## Phase 3A: storage-substrate decision
151
+
152
+ Evaluate the current custom engine and permissively licensed embedded transactional
153
+ cores against the same requirements:
154
+
155
+ - crash and power-loss behavior
156
+ - atomic batch and MVCC support
157
+ - checkpoint, backup, and replication integration
158
+ - memory, latency, write amplification, and restart behavior
159
+ - format ownership, migration, licensing, and supply-chain risk
160
+
161
+ Gate: one architecture decision selects exactly one authoritative durability
162
+ boundary. Dual-WAL and dual-commit designs are prohibited.
163
+
164
+ ## Phase 3B: Storage VNext
165
+
166
+ - add a segmented, checksummed global commit log with stable timelines and LSNs
167
+ - encode atomic data, DDL, catalog, index-metadata, and auth batches
168
+ - persist request deduplication, retryable-write results, and transaction outcomes
169
+ - add database-wide MVCC read timestamps and change-proportional transactions
170
+ - replace full index-engine clones with incremental deltas
171
+ - add immutable checkpoints, bounded replay, and a durable format manifest
172
+ - move compaction to a rate-limited background service
173
+ - add group commit and real batch publication
174
+ - define an offline 5.x migration and N-1 compatibility contract
175
+
176
+ Gates:
177
+
178
+ - one-document transaction cost is independent of database size
179
+ - repeated recovery is idempotent and produces the same content digest
180
+ - ENOSPC, EIO, short writes, and failed fsyncs yield success, explicit ambiguity, or
181
+ fail-closed state, never silent divergence
182
+ - 24-hour nightly and 72-hour release-candidate soaks meet declared memory, disk,
183
+ and restart ceilings on both Linux architectures
184
+
185
+ ## Phase 4: query, index, and resource model
186
+
187
+ - implement one streaming planner/executor
188
+ - use canonical order-preserving BSON index keys
189
+ - add range, compound-prefix, and index-ordered top-k scans
190
+ - implement correct multikey expansion, uniqueness, and TTL execution
191
+ - compile predicates and regular expressions once per operation
192
+ - implement positional updates and array-filter semantics
193
+ - add process-wide and per-tenant admission for memory, scans, connections, I/O,
194
+ index builds, and maintenance
195
+ - add configurable service classes and fair scheduling
196
+ - add only features selected by the certified compatibility profile
197
+
198
+ Semantic work may proceed after Phase 2. Retryable outcomes, transaction publication,
199
+ and durable index publication depend on Storage VNext. Unsupported local concerns
200
+ remain rejected until Storage VNext implements them; majority concerns remain
201
+ rejected until replication implements them.
202
+
203
+ Gate: bounded-memory scans at maximum declared scale, published p99 latency and
204
+ capacity curves, proven tenant isolation, and zero certified-profile mismatches.
205
+
206
+ ## Phase 5: backup, PITR, and managed single-node service
207
+
208
+ - create online immutable checkpoints at exact LSNs
209
+ - archive subsequent commit-log segments continuously
210
+ - encrypt, checksum, and sign backup manifests with timeline, format, LSN range,
211
+ and key identity
212
+ - restore into a new root, replay to an exact LSN or timestamp, verify its content
213
+ digest, and promote atomically
214
+ - retain logical export/import as migration tools rather than backup primitives
215
+ - add versioned service classes, immutable node placement, node-bound grants,
216
+ TLS/mTLS endpoints, credential rotation/revocation, quotas, metering, backup
217
+ policy, maintenance windows, audit, and idempotent asynchronous operations
218
+ - operate one process per tenant initially
219
+ - qualify signed images, SBOM/provenance, canaries, rollback, alerts, runbooks, and
220
+ security before any general-availability claim
221
+
222
+ Launch order: internal alpha, private beta, then single-node GA with explicit
223
+ availability, RPO, RTO, capacity, and compatibility limits.
224
+
225
+ Gate: repeated maximum-size restore drills meet the published RPO/RTO; billing
226
+ reconciles; upgrades and rollback/restore pass; cross-tenant network, auth, quota,
227
+ backup, and restore isolation is proven; no plaintext secret reaches persisted or
228
+ logged state.
229
+
230
+ ## Phase 6: replication and high availability
231
+
232
+ - replicate the Storage VNext log across three replicas in separate failure domains
233
+ - add terms, quorum commit, snapshot installation, log catch-up, and membership
234
+ changes
235
+ - implement truthful local and majority concerns
236
+ - publish accurate `hello` topology and election metadata
237
+ - add causal times, retryable outcomes, idempotent transaction commits, and
238
+ failover-safe session behavior
239
+ - support mixed N/N-1 rolling upgrades
240
+ - keep one database assigned to one replica group
241
+
242
+ Majority RPO 0 means a majority-acknowledged write survives loss of any one replica
243
+ within the declared replica-group fault model.
244
+
245
+ Gate: no split-brain commits under partitions; accepted histories satisfy the
246
+ declared consistency model; leader failure meets the published RTO; and retries
247
+ return the original outcome exactly once.
248
+
249
+ ## Phase 7: managed HA and compatibility expansion
250
+
251
+ - place complete databases across replica groups
252
+ - migrate a database through checkpoint transfer, log catch-up, and an atomic
253
+ routing-epoch change
254
+ - permanently fence stale owners
255
+ - add automated replica replacement and maintenance-aware failover
256
+ - derive durable change streams from the replicated commit log
257
+ - certify additional drivers and ODMs
258
+ - expand aggregation, views, indexes, and administrative behavior according to
259
+ measured workload demand
260
+ - publish machine-generated compatibility and SLO matrices
261
+
262
+ Gate: no open P0/P1 defect in the certified surface, regional and maintenance
263
+ exercises pass, and customer-visible incident/status processes are operational.
264
+
265
+ ## Phase 8: horizontal scale
266
+
267
+ Scale complete databases across replica groups first. Add intra-database sharding
268
+ only after single-group limits become a measured customer constraint:
269
+
270
+ - separate router and replicated placement catalog
271
+ - range ownership and epochs
272
+ - snapshot-plus-log range migration
273
+ - stale-router rejection and permanent owner fencing
274
+ - per-shard replica groups, balancing, and range cleanup
275
+ - cross-shard transactions only as a separately justified program
276
+
277
+ Gate: migration crashes cannot create gaps, duplicates, or dual writers; stale
278
+ routing metadata cannot mutate old ownership; shard and region chaos meet the
279
+ published SLOs.
280
+
281
+ ## Release qualification
282
+
283
+ Every applicable release must pass the narrowest relevant set of these gates:
284
+
285
+ - raw-wire and target-driver handshake tests
286
+ - generated semantic and certified compatibility suites
287
+ - deterministic persistence failpoints and randomized process-kill tests
288
+ - storage/index/content-digest reconciliation after recovery
289
+ - 24-hour nightly and 72-hour release-candidate resource soaks
290
+ - both published Linux architectures
291
+ - automated backup/restore drills once backup exists
292
+ - partition, failover, and history verification once replication exists
293
+ - supply-chain, provenance, security, upgrade, and rollback checks for managed tiers
294
+
295
+ No release may advertise a capability, durability level, topology, or operational
296
+ limit that its release qualification did not exercise.
@@ -3,6 +3,6 @@
3
3
  */
4
4
  export const commitinfo = {
5
5
  name: '@push.rocks/smartdb',
6
- version: '5.0.0',
6
+ version: '5.0.2',
7
7
  description: 'A MongoDB-compatible embedded database server with wire protocol support, backed by a high-performance Rust engine.'
8
8
  }
package/ts/index.ts CHANGED
@@ -9,6 +9,9 @@ export type {
9
9
  ILocalSmartDbOptions,
10
10
  ILocalSmartDbConnectionInfo,
11
11
  ILocalSmartDbOfflineInspectionLimits,
12
+ ILocalSmartDbOfflinePhysicalNamespaceInspectionLimits,
13
+ ILocalSmartDbOfflinePhysicalNamespaceInspection,
14
+ ILocalSmartDbOfflinePhysicalNamespaceInspectionResult,
12
15
  ILocalSmartDbOfflineStringValueInspection,
13
16
  TLocalSmartDbOfflineStringValueInspectionResult,
14
17
  } from './ts_local/index.js';