pi-better-server 0.5.0 → 0.6.0
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/package.json +4 -1
- package/scripts/copy-pi-test-providers.mjs +10 -0
- package/scripts/event-publication/README.md +26 -0
- package/scripts/event-publication/commit.mjs +21 -0
- package/scripts/event-publication/measure.mjs +37 -5
- package/scripts/event-publication/writer.mjs +3 -8
- package/scripts/measure-full-runtime/probe.mjs +4 -2
- package/scripts/measure-full-runtime/recovery-trace-loader.mjs +51 -0
- package/scripts/measure-full-runtime/recovery-trace.mjs +16 -0
- package/scripts/measure-shared-reads.mjs +2 -1
- package/scripts/private-runtime/package-lock.json +18 -0
- package/scripts/private-runtime/package.json +4 -1
- package/scripts/source-provenance.mjs +2 -2
- package/scripts/test-on-pi.sh +2 -9
- package/src/handshake.ts +1 -1
- package/src/hosted-session.ts +32 -4
- package/src/maintenance.ts +35 -7
- package/src/registry.ts +28 -4
- package/src/runtime/attempt-invalidation.ts +54 -0
- package/src/runtime/background-history.ts +151 -45
- package/src/runtime/background-policy.ts +9 -4
- package/src/runtime/background-tools.ts +131 -23
- package/src/runtime/background.ts +351 -68
- package/src/runtime/cancellation.ts +28 -7
- package/src/runtime/catalog-sources.ts +199 -0
- package/src/runtime/catalog.ts +53 -21
- package/src/runtime/client.ts +22 -2
- package/src/runtime/domain/assignment-inbox.mjs +119 -0
- package/src/runtime/domain/assignment-observation.d.mts +1 -1
- package/src/runtime/domain/assignment-observation.mjs +43 -35
- package/src/runtime/domain/background/process-identity.mjs +20 -2
- package/src/runtime/domain/background/process.mjs +3 -3
- package/src/runtime/domain/background/registry.mjs +61 -3
- package/src/runtime/domain/background/types.mjs +1 -0
- package/src/runtime/domain/background-service/adapter-contract.domain.mjs +1 -1
- package/src/runtime/domain/background-service/adapter-contract.ts +1 -1
- package/src/runtime/domain/background-service/goal-provider.domain.mjs +35 -16
- package/src/runtime/domain/background-service/goal-provider.ts +31 -16
- package/src/runtime/domain/background-service/index.domain.mjs +6 -9
- package/src/runtime/domain/background-service/index.ts +6 -9
- package/src/runtime/domain/background-service/managed-authority.domain.mjs +6 -3
- package/src/runtime/domain/background-service/managed-authority.ts +5 -3
- package/src/runtime/domain/background-service/managed-client.domain.mjs +21 -7
- package/src/runtime/domain/background-service/managed-client.ts +20 -7
- package/src/runtime/domain/background-service/managed-frontend.domain.mjs +75 -17
- package/src/runtime/domain/background-service/managed-frontend.ts +62 -17
- package/src/runtime/domain/background-service/navigator-provider.domain.mjs +16 -5
- package/src/runtime/domain/background-service/navigator-provider.ts +15 -5
- package/src/runtime/domain/background-service/observed-wait-client.domain.mjs +6 -0
- package/src/runtime/domain/background-service/observed-wait-client.ts +10 -0
- package/src/runtime/domain/background-service/observed-waits.domain.mjs +170 -27
- package/src/runtime/domain/background-service/observed-waits.ts +154 -30
- package/src/runtime/domain/background-service/process-identity.domain.mjs +20 -2
- package/src/runtime/domain/background-service/process-identity.ts +18 -2
- package/src/runtime/domain/background-service/process.domain.mjs +3 -3
- package/src/runtime/domain/background-service/process.ts +3 -3
- package/src/runtime/domain/background-service/registry.domain.mjs +61 -3
- package/src/runtime/domain/background-service/registry.ts +53 -5
- package/src/runtime/domain/background-service/runtime.domain.mjs +32 -16
- package/src/runtime/domain/background-service/runtime.ts +19 -9
- package/src/runtime/domain/background-service/sandbox.domain.mjs +14 -15
- package/src/runtime/domain/background-service/sandbox.ts +14 -11
- package/src/runtime/domain/background-service/shared-callback-batcher.domain.mjs +8 -1
- package/src/runtime/domain/background-service/shared-callback-batcher.ts +11 -2
- package/src/runtime/domain/background-service/shared-navigator-panels.domain.mjs +24 -2
- package/src/runtime/domain/background-service/shared-navigator-panels.ts +26 -4
- package/src/runtime/domain/background-service/shared-navigator.domain.mjs +218 -13
- package/src/runtime/domain/background-service/shared-navigator.ts +197 -14
- package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-inbox.mjs +144 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/assignment-observation.mjs +53 -41
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-changes.ts +73 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +2 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.domain.mjs +11 -2
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/background-requests.ts +14 -3
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.domain.mjs +4 -2
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/discovery.ts +5 -3
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.domain.mjs +44 -4
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/operations.ts +50 -2
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.domain.mjs +12 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/result-supervision.ts +12 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.domain.mjs +2 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/rows.ts +2 -0
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.domain.mjs +42 -21
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/schema.ts +40 -24
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.domain.mjs +21 -3
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/store.ts +34 -8
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.domain.mjs +23 -1
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/subagent-launch.ts +24 -1
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.domain.mjs +1 -1
- package/src/runtime/domain/background-service/shared-operation-coordinator/src/types.ts +5 -1
- package/src/runtime/domain/background-service/shared-sandbox-core.ts +1 -1
- package/src/runtime/domain/background-service/shared-work-client.mjs +174 -7
- package/src/runtime/domain/background-service/supervisor/generated/process-identity.mjs +20 -2
- package/src/runtime/domain/background-service/supervisor/generated/process.mjs +3 -3
- package/src/runtime/domain/background-service/task-diagnostics.domain.mjs +1 -1
- package/src/runtime/domain/background-service/task-diagnostics.ts +1 -1
- package/src/runtime/domain/background-service/tools.domain.mjs +31 -24
- package/src/runtime/domain/background-service/tools.ts +41 -38
- package/src/runtime/domain/background-service/types.domain.mjs +1 -0
- package/src/runtime/domain/background-service/types.ts +3 -1
- package/src/runtime/domain/background-service/work-observation.domain.mjs +46 -20
- package/src/runtime/domain/background-service/work-observation.ts +46 -19
- package/src/runtime/domain/catalog/catalog-store.d.mts +9 -1
- package/src/runtime/domain/catalog/catalog-store.mjs +20 -22
- package/src/runtime/domain/coordinator/src/assignment-changes.mjs +75 -0
- package/src/runtime/domain/coordinator/src/assignment-outcomes.mjs +2 -0
- package/src/runtime/domain/coordinator/src/background-requests.mjs +11 -2
- package/src/runtime/domain/coordinator/src/discovery.mjs +4 -2
- package/src/runtime/domain/coordinator/src/operations.mjs +44 -4
- package/src/runtime/domain/coordinator/src/result-supervision.mjs +12 -0
- package/src/runtime/domain/coordinator/src/rows.mjs +2 -0
- package/src/runtime/domain/coordinator/src/schema.mjs +42 -21
- package/src/runtime/domain/coordinator/src/store.mjs +21 -3
- package/src/runtime/domain/coordinator/src/subagent-launch.mjs +23 -1
- package/src/runtime/domain/coordinator/src/types.mjs +1 -1
- package/src/runtime/domain/health-observation.d.mts +3 -1
- package/src/runtime/domain/health-observation.mjs +189 -190
- package/src/runtime/domain/log-cursor.d.mts +2 -0
- package/src/runtime/domain/log-cursor.mjs +85 -16
- package/src/runtime/domain/parse.d.mts +4 -1
- package/src/runtime/domain/parse.mjs +50 -5
- package/src/runtime/domain/sandbox-policy/README.md +61 -63
- package/src/runtime/domain/sandbox-policy/commands.domain.mjs +11 -8
- package/src/runtime/domain/sandbox-policy/commands.ts +12 -7
- package/src/runtime/domain/sandbox-policy/index.domain.mjs +53 -9
- package/src/runtime/domain/sandbox-policy/index.ts +52 -9
- package/src/runtime/domain/sandbox-policy/package.json +1 -1
- package/src/runtime/domain/sandbox-policy/permission-settings.domain.mjs +5 -2
- package/src/runtime/domain/sandbox-policy/permission-settings.ts +9 -2
- package/src/runtime/domain/sandbox-policy/permissions-page.domain.mjs +56 -137
- package/src/runtime/domain/sandbox-policy/permissions-page.ts +52 -130
- package/src/runtime/domain/sandbox-policy/permissions.domain.mjs +1 -6
- package/src/runtime/domain/sandbox-policy/permissions.ts +1 -6
- package/src/runtime/domain/sandbox-policy/shared-sandbox-core.ts +1 -1
- package/src/runtime/domain/sandbox-policy/shared-task-exec.domain.mjs +14 -1
- package/src/runtime/domain/sandbox-policy/shared-task-exec.ts +12 -1
- package/src/runtime/domain/sandbox-policy/shared-task-process-identity.domain.mjs +140 -0
- package/src/runtime/domain/sandbox-policy/shared-task-process-identity.ts +126 -0
- package/src/runtime/domain/sandbox-policy/shared-task-process-list.domain.mjs +3 -2
- package/src/runtime/domain/sandbox-policy/shared-task-process-list.ts +8 -2
- package/src/runtime/domain/sandbox-policy/shared-task-sandbox.domain.mjs +4 -3
- package/src/runtime/domain/sandbox-policy/shared-task-sandbox.ts +5 -3
- package/src/runtime/domain/sandbox-policy/shared-task-tools.domain.mjs +8 -5
- package/src/runtime/domain/sandbox-policy/shared-task-tools.ts +8 -5
- package/src/runtime/domain/subagents/README.md +1 -1
- package/src/runtime/domain/subagents/assignment-outcomes.domain.mjs +12 -6
- package/src/runtime/domain/subagents/assignment-outcomes.ts +11 -5
- package/src/runtime/domain/subagents/assignment-report.domain.mjs +87 -24
- package/src/runtime/domain/subagents/assignment-report.ts +83 -19
- package/src/runtime/domain/subagents/catalog-host-admission.domain.mjs +21 -3
- package/src/runtime/domain/subagents/catalog-host-admission.ts +19 -3
- package/src/runtime/domain/subagents/catalog-preferences.ts +1 -1
- package/src/runtime/domain/subagents/catalog-resolver.domain.mjs +35 -1
- package/src/runtime/domain/subagents/catalog-resolver.ts +35 -1
- package/src/runtime/domain/subagents/catalog-store.domain.mjs +20 -22
- package/src/runtime/domain/subagents/catalog-store.ts +27 -20
- package/src/runtime/domain/subagents/child-apply-patch.domain.mjs +13 -0
- package/src/runtime/domain/subagents/child-apply-patch.ts +13 -0
- package/src/runtime/domain/subagents/child-dependencies.mjs +27 -15
- package/src/runtime/domain/subagents/child-operations.domain.mjs +80 -2
- package/src/runtime/domain/subagents/child-operations.ts +80 -1
- package/src/runtime/domain/subagents/child-preflight.mjs +9 -2
- package/src/runtime/domain/subagents/child-process-list.domain.mjs +7 -0
- package/src/runtime/domain/subagents/child-process-list.ts +8 -0
- package/src/runtime/domain/subagents/config.domain.mjs +49 -2
- package/src/runtime/domain/subagents/config.ts +46 -2
- package/src/runtime/domain/subagents/continuation-authority.domain.mjs +5 -1
- package/src/runtime/domain/subagents/continuation-authority.ts +3 -1
- package/src/runtime/domain/subagents/continuation-runtime.domain.mjs +89 -0
- package/src/runtime/domain/subagents/continuation-runtime.ts +88 -0
- package/src/runtime/domain/subagents/extensions.mjs +11 -13
- package/src/runtime/domain/subagents/finalization.domain.mjs +12 -0
- package/src/runtime/domain/subagents/finalization.ts +15 -0
- package/src/runtime/domain/subagents/goal-provider.domain.mjs +44 -2
- package/src/runtime/domain/subagents/goal-provider.ts +44 -2
- package/src/runtime/domain/subagents/health-observation.domain.mjs +189 -190
- package/src/runtime/domain/subagents/health-observation.ts +43 -48
- package/src/runtime/domain/subagents/index.domain.mjs +296 -123
- package/src/runtime/domain/subagents/index.ts +257 -98
- package/src/runtime/domain/subagents/launch-context.domain.mjs +24 -0
- package/src/runtime/domain/subagents/launch-context.ts +23 -0
- package/src/runtime/domain/subagents/launch-digest.mjs +6 -0
- package/src/runtime/domain/subagents/log-cursor.domain.mjs +85 -16
- package/src/runtime/domain/subagents/log-cursor.ts +91 -15
- package/src/runtime/domain/subagents/managed-launch-bootstrap.mjs +2 -2
- package/src/runtime/domain/subagents/managed-launch-client.domain.mjs +6 -3
- package/src/runtime/domain/subagents/managed-launch-client.ts +6 -3
- package/src/runtime/domain/subagents/managed-launch-host.domain.mjs +222 -14
- package/src/runtime/domain/subagents/managed-launch-host.ts +168 -15
- package/src/runtime/domain/subagents/managed-launch-journal.mjs +1 -5
- package/src/runtime/domain/subagents/managed-launch-port.ts +4 -0
- package/src/runtime/domain/subagents/operation-bridge-types.domain.mjs +27 -2
- package/src/runtime/domain/subagents/operation-bridge-types.ts +27 -2
- package/src/runtime/domain/subagents/owned-exit.domain.mjs +12 -0
- package/src/runtime/domain/subagents/owned-exit.ts +12 -0
- package/src/runtime/domain/subagents/package.json +1 -1
- package/src/runtime/domain/subagents/parse.domain.mjs +50 -5
- package/src/runtime/domain/subagents/parse.ts +48 -6
- package/src/runtime/domain/subagents/permission-policy.domain.mjs +32 -8
- package/src/runtime/domain/subagents/permission-policy.ts +41 -8
- package/src/runtime/domain/subagents/process-identity.mjs +33 -0
- package/src/runtime/domain/subagents/registry.domain.mjs +47 -33
- package/src/runtime/domain/subagents/registry.ts +54 -33
- package/src/runtime/domain/subagents/shared-callback-batcher.domain.mjs +8 -1
- package/src/runtime/domain/subagents/shared-callback-batcher.ts +11 -2
- package/src/runtime/domain/subagents/shared-catalog.domain.mjs +6 -23
- package/src/runtime/domain/subagents/shared-catalog.ts +6 -14
- package/src/runtime/domain/subagents/shared-navigator-panels.domain.mjs +24 -2
- package/src/runtime/domain/subagents/shared-navigator-panels.ts +26 -4
- package/src/runtime/domain/subagents/shared-navigator.domain.mjs +218 -13
- package/src/runtime/domain/subagents/shared-navigator.ts +197 -14
- package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-inbox.mjs +144 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/assignment-observation.mjs +53 -41
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.domain.mjs +75 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-changes.ts +73 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.domain.mjs +2 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/assignment-outcomes.ts +2 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.domain.mjs +11 -2
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/background-requests.ts +14 -3
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.domain.mjs +4 -2
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/discovery.ts +5 -3
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.domain.mjs +44 -4
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/operations.ts +50 -2
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.domain.mjs +12 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/result-supervision.ts +12 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.domain.mjs +2 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/rows.ts +2 -0
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.domain.mjs +42 -21
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/schema.ts +40 -24
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.domain.mjs +21 -3
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/store.ts +34 -8
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.domain.mjs +23 -1
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/subagent-launch.ts +24 -1
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.domain.mjs +1 -1
- package/src/runtime/domain/subagents/shared-operation-coordinator/src/types.ts +5 -1
- package/src/runtime/domain/subagents/shared-sandbox-core.ts +1 -1
- package/src/runtime/domain/subagents/shared-task-exec.domain.mjs +14 -1
- package/src/runtime/domain/subagents/shared-task-exec.ts +12 -1
- package/src/runtime/domain/subagents/shared-task-process-identity.domain.mjs +140 -0
- package/src/runtime/domain/subagents/shared-task-process-identity.ts +126 -0
- package/src/runtime/domain/subagents/shared-task-process-list.domain.mjs +3 -2
- package/src/runtime/domain/subagents/shared-task-process-list.ts +8 -2
- package/src/runtime/domain/subagents/shared-task-sandbox.domain.mjs +4 -3
- package/src/runtime/domain/subagents/shared-task-sandbox.ts +5 -3
- package/src/runtime/domain/subagents/shared-task-tools.domain.mjs +8 -5
- package/src/runtime/domain/subagents/shared-task-tools.ts +8 -5
- package/src/runtime/domain/subagents/shared-work-client.mjs +174 -7
- package/src/runtime/domain/subagents/subagent-tools.domain.mjs +22 -38
- package/src/runtime/domain/subagents/subagent-tools.ts +28 -34
- package/src/runtime/domain/subagents/task-policy.domain.mjs +1 -1
- package/src/runtime/domain/subagents/task-policy.ts +3 -1
- package/src/runtime/domain/subagents/timing.domain.mjs +10 -1
- package/src/runtime/domain/subagents/timing.ts +10 -1
- package/src/runtime/domain/subagents/work-observation.domain.mjs +77 -16
- package/src/runtime/domain/subagents/work-observation.ts +71 -16
- package/src/runtime/domain/subagents/worker-operations-host.domain.mjs +9 -4
- package/src/runtime/domain/subagents/worker-operations-host.ts +12 -4
- package/src/runtime/domain/subagents/worker-waits.domain.mjs +89 -35
- package/src/runtime/domain/subagents/worker-waits.ts +93 -34
- package/src/runtime/health-config.ts +27 -11
- package/src/runtime/log-checkpoints.ts +117 -0
- package/src/runtime/mutation-store.ts +5 -4
- package/src/runtime/queries.ts +25 -2
- package/src/runtime/query-executor.ts +149 -28
- package/src/runtime/query-worker.mjs +106 -21
- package/src/runtime/read-model.ts +846 -120
- package/src/runtime/read-watchdog-probe.ts +4 -0
- package/src/runtime/result-supervision.ts +188 -16
- package/src/runtime/source-watch.ts +175 -0
- package/src/runtime/subagent-launch.ts +11 -4
- package/src/runtime/work-budget.ts +130 -0
- package/src/runtime/work-client.d.mts +8 -0
- package/src/runtime/work-client.mjs +150 -7
- package/src/server.ts +104 -23
- package/src/session-activity.ts +26 -4
- package/src/version.ts +1 -1
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { createRequire } from "node:module";
|
|
2
|
+
import { mkdirSync } from "node:fs";
|
|
3
|
+
import { dirname } from "node:path";
|
|
4
|
+
|
|
5
|
+
// Derived data only. Deletion, eviction and incompatible versions cause replay.
|
|
6
|
+
export const LOG_CHECKPOINT_VERSION = 1;
|
|
7
|
+
export const LOG_CHECKPOINT_BUDGET = 32 * 1024 * 1024;
|
|
8
|
+
export const LOG_CHECKPOINT_ENTRY_BUDGET = 256 * 1024;
|
|
9
|
+
export const LOG_CHECKPOINT_MAX_ENTRIES = 4096;
|
|
10
|
+
|
|
11
|
+
export function isSqliteLockContention(error: unknown): boolean {
|
|
12
|
+
const sqlite = error as { code?: string; errcode?: number } | null;
|
|
13
|
+
return sqlite?.code === "ERR_SQLITE_ERROR" && typeof sqlite.errcode === "number"
|
|
14
|
+
&& [5, 6].includes(sqlite.errcode & 255);
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
export class LogCheckpoints {
|
|
18
|
+
private db: any;
|
|
19
|
+
private shared: boolean;
|
|
20
|
+
private prefix: string;
|
|
21
|
+
private attached = false;
|
|
22
|
+
private initialized = false;
|
|
23
|
+
private closed = false;
|
|
24
|
+
private path: string;
|
|
25
|
+
readonly metrics = { restores: 0, misses: 0, commits: 0, oversized: 0, acquisitionAttempts: 0, contentions: 0 };
|
|
26
|
+
constructor(path: string, connection?: any, options: { defer?: boolean } = {}) {
|
|
27
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
28
|
+
const { DatabaseSync } = createRequire(import.meta.url)("node:sqlite");
|
|
29
|
+
this.shared = Boolean(connection);
|
|
30
|
+
this.db = connection ?? new DatabaseSync(path);
|
|
31
|
+
this.prefix = connection ? "log_checkpoints." : "";
|
|
32
|
+
this.path = path;
|
|
33
|
+
if (!options.defer) {
|
|
34
|
+
try { this.acquire(); }
|
|
35
|
+
catch (error) { if (!connection) { this.db.close(); this.closed = true; } throw error; }
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
get ready() { return this.initialized && !this.closed; }
|
|
39
|
+
/** One nonblocking attempt, outside the owner's source/derived transaction. */
|
|
40
|
+
initialize(): boolean {
|
|
41
|
+
try { this.acquire(); return true; }
|
|
42
|
+
catch (error) {
|
|
43
|
+
if (isSqliteLockContention(error)) {
|
|
44
|
+
this.metrics.contentions++;
|
|
45
|
+
return false;
|
|
46
|
+
}
|
|
47
|
+
throw error;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
private acquire() {
|
|
51
|
+
if (this.closed) throw new Error("Checkpoint participant is closed");
|
|
52
|
+
if (this.initialized) return;
|
|
53
|
+
if (this.db.isTransaction) throw new Error("Checkpoint acquisition requires an unpinned owner");
|
|
54
|
+
this.metrics.acquisitionAttempts++;
|
|
55
|
+
try {
|
|
56
|
+
// Keep durable folds on the query owner's handle; query tables stay in memory.
|
|
57
|
+
if (this.shared && !this.attached) {
|
|
58
|
+
this.db.prepare("ATTACH DATABASE ? AS log_checkpoints").run(this.path);
|
|
59
|
+
this.attached = true;
|
|
60
|
+
}
|
|
61
|
+
this.db.exec(`PRAGMA ${this.prefix}journal_mode=DELETE`);
|
|
62
|
+
// Setting an already-enabled auto_vacuum still requests a write lock.
|
|
63
|
+
// Reopening a checkpoint reader must not contend with a reserved writer.
|
|
64
|
+
if (this.db.prepare(`PRAGMA ${this.prefix}auto_vacuum`).get().auto_vacuum !== 1) {
|
|
65
|
+
this.db.exec(`PRAGMA ${this.prefix}auto_vacuum=FULL`);
|
|
66
|
+
}
|
|
67
|
+
this.db.exec(`CREATE TABLE IF NOT EXISTS ${this.prefix}checkpoints(path TEXT PRIMARY KEY, version INTEGER, payload TEXT, bytes INTEGER, used INTEGER)`);
|
|
68
|
+
this.initialized = true;
|
|
69
|
+
} catch (error) {
|
|
70
|
+
// Release only this participant's acquisition; a later attempt must not
|
|
71
|
+
// inherit an unverified attachment or detach another participant's data.
|
|
72
|
+
if (this.attached) {
|
|
73
|
+
try { this.db.exec("DETACH DATABASE log_checkpoints"); this.attached = false; }
|
|
74
|
+
catch (cleanup) { throw new AggregateError([error, cleanup], "Checkpoint initialization and owned attachment cleanup failed"); }
|
|
75
|
+
}
|
|
76
|
+
throw error;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
load(path: string): any {
|
|
80
|
+
if (!this.initialized || this.closed) throw new Error("Checkpoint coverage is unavailable");
|
|
81
|
+
const row = this.db.prepare(`SELECT payload FROM ${this.prefix}checkpoints WHERE path=? AND version=?`).get(path, LOG_CHECKPOINT_VERSION);
|
|
82
|
+
if (!row) { this.metrics.misses++; return undefined; }
|
|
83
|
+
try { const saved = JSON.parse(row.payload); this.metrics.restores++; return saved; } catch { this.metrics.misses++; return undefined; }
|
|
84
|
+
}
|
|
85
|
+
save(path: string, value: unknown, deferPublication = false) {
|
|
86
|
+
if (!this.initialized || this.closed) throw new Error("Checkpoint coverage is unavailable");
|
|
87
|
+
const payload = JSON.stringify(value), bytes = Buffer.byteLength(payload);
|
|
88
|
+
this.db.exec(this.shared ? "SAVEPOINT checkpoint_save" : "BEGIN IMMEDIATE");
|
|
89
|
+
try {
|
|
90
|
+
this.db.prepare(`DELETE FROM ${this.prefix}checkpoints WHERE path=?`).run(path);
|
|
91
|
+
if (bytes <= LOG_CHECKPOINT_ENTRY_BUDGET) {
|
|
92
|
+
this.db.prepare(`INSERT INTO ${this.prefix}checkpoints VALUES(?,?,?,?,?)`).run(path, LOG_CHECKPOINT_VERSION, payload, bytes, Date.now());
|
|
93
|
+
}
|
|
94
|
+
while (this.db.prepare(`SELECT coalesce(sum(bytes),0) AS n FROM ${this.prefix}checkpoints`).get().n > LOG_CHECKPOINT_BUDGET) {
|
|
95
|
+
this.db.exec(`DELETE FROM ${this.prefix}checkpoints WHERE path=(SELECT path FROM ${this.prefix}checkpoints ORDER BY used,path LIMIT 1)`);
|
|
96
|
+
}
|
|
97
|
+
this.db.prepare(`DELETE FROM ${this.prefix}checkpoints WHERE path IN (SELECT path FROM ${this.prefix}checkpoints ORDER BY used DESC,path DESC LIMIT -1 OFFSET ?)`).run(LOG_CHECKPOINT_MAX_ENTRIES);
|
|
98
|
+
this.db.exec(this.shared ? "RELEASE checkpoint_save" : "COMMIT");
|
|
99
|
+
let published = false;
|
|
100
|
+
const publish = () => {
|
|
101
|
+
if (published) return;
|
|
102
|
+
published = true;
|
|
103
|
+
this.metrics.commits++;
|
|
104
|
+
if (bytes > LOG_CHECKPOINT_ENTRY_BUDGET) this.metrics.oversized++;
|
|
105
|
+
};
|
|
106
|
+
if (!deferPublication) publish();
|
|
107
|
+
return publish;
|
|
108
|
+
} catch (error) { this.db.exec(this.shared ? "ROLLBACK TO checkpoint_save; RELEASE checkpoint_save" : "ROLLBACK"); throw error; }
|
|
109
|
+
}
|
|
110
|
+
close() {
|
|
111
|
+
if (this.closed) return;
|
|
112
|
+
if (this.shared) {
|
|
113
|
+
if (this.attached) { this.db.exec("DETACH DATABASE log_checkpoints"); this.attached = false; }
|
|
114
|
+
} else this.db.close();
|
|
115
|
+
this.closed = true;
|
|
116
|
+
}
|
|
117
|
+
}
|
|
@@ -1,23 +1,24 @@
|
|
|
1
1
|
import { realpathSync } from "node:fs";
|
|
2
2
|
import { join } from "node:path";
|
|
3
|
+
import { createWorkBudget } from "./work-budget.ts";
|
|
3
4
|
// @ts-expect-error Generated canonical coordinator.
|
|
4
5
|
import { openStore } from "./domain/coordinator/index.mjs";
|
|
5
6
|
|
|
6
7
|
// Query workers own their read connection. All main-thread mutation services
|
|
7
8
|
// share this connection, keeping mutations within the root's two-connection budget.
|
|
8
|
-
const stores = new Map<string, { store: any; leases: number }>();
|
|
9
|
+
const stores = new Map<string, { store: any; leases: number; budget: ReturnType<typeof createWorkBudget> }>();
|
|
9
10
|
|
|
10
|
-
export function acquireMutationStore(root: string): { store: any; release(): void } {
|
|
11
|
+
export function acquireMutationStore(root: string): { store: any; budget: ReturnType<typeof createWorkBudget>; release(): void } {
|
|
11
12
|
const key = realpathSync(root);
|
|
12
13
|
let entry = stores.get(key);
|
|
13
14
|
if (!entry) {
|
|
14
|
-
entry = { store: openStore({ path: join(key, "operation-coordinator.sqlite") }), leases: 0 };
|
|
15
|
+
entry = { store: openStore({ path: join(key, "operation-coordinator.sqlite") }), leases: 0, budget: createWorkBudget() };
|
|
15
16
|
stores.set(key, entry);
|
|
16
17
|
}
|
|
17
18
|
entry.leases++;
|
|
18
19
|
const owned = entry;
|
|
19
20
|
let released = false;
|
|
20
|
-
return { store: owned.store, release() {
|
|
21
|
+
return { store: owned.store, budget: owned.budget, release() {
|
|
21
22
|
if (released) return;
|
|
22
23
|
released = true;
|
|
23
24
|
if (--owned.leases === 0) {
|
package/src/runtime/queries.ts
CHANGED
|
@@ -1,6 +1,15 @@
|
|
|
1
1
|
import type { Socket } from "node:net";
|
|
2
2
|
import type { WorkReadModel, WorkScope } from "./read-model.ts";
|
|
3
3
|
|
|
4
|
+
const eventEncodings = new WeakMap<object, string>();
|
|
5
|
+
const snapshotEncodings = new WeakMap<object, string>();
|
|
6
|
+
export function snapshotJSON(snapshot: object): string {
|
|
7
|
+
let json = snapshotEncodings.get(snapshot);
|
|
8
|
+
if (json === undefined) { json = JSON.stringify(snapshot); snapshotEncodings.set(snapshot, json); }
|
|
9
|
+
return json;
|
|
10
|
+
}
|
|
11
|
+
export const queryEncodingMetrics = { serializations: 0, frames: 0, bytes: 0 };
|
|
12
|
+
|
|
4
13
|
export function workScope(input: unknown): WorkScope {
|
|
5
14
|
if (!input || typeof input !== "object" || Array.isArray(input)) throw new Error("A runtime scope object is required");
|
|
6
15
|
const value = input as Record<string, unknown>;
|
|
@@ -25,6 +34,7 @@ export function workScope(input: unknown): WorkScope {
|
|
|
25
34
|
export class WorkQueries {
|
|
26
35
|
private dispose?: () => void;
|
|
27
36
|
private paused = false;
|
|
37
|
+
private lastSnapshotSeq?: number;
|
|
28
38
|
private model: WorkReadModel;
|
|
29
39
|
private socket: Socket;
|
|
30
40
|
private maxQueuedBytes: number;
|
|
@@ -42,22 +52,35 @@ export class WorkQueries {
|
|
|
42
52
|
private event(event: unknown) {
|
|
43
53
|
if (this.socket.destroyed || this.paused) return;
|
|
44
54
|
if (this.socket.writableLength > this.maxQueuedBytes) { this.paused = true; return; }
|
|
45
|
-
const
|
|
55
|
+
const snapshot = (event as any)?.type === "runtime_snapshot" ? (event as any).snapshot : undefined;
|
|
56
|
+
let line: string;
|
|
57
|
+
if (snapshot) {
|
|
58
|
+
let prefix = eventEncodings.get(snapshot);
|
|
59
|
+
if (!prefix) {
|
|
60
|
+
prefix = '{"type":"event","event":{"type":"runtime_snapshot","snapshot":' + snapshotJSON(snapshot);
|
|
61
|
+
eventEncodings.set(snapshot, prefix); queryEncodingMetrics.serializations++;
|
|
62
|
+
}
|
|
63
|
+
// The snapshot is shared; its predecessor belongs to this subscription.
|
|
64
|
+
line = prefix + ',"previousSeq":' + (this.lastSnapshotSeq ?? snapshot.seq) + '}}\n';
|
|
65
|
+
} else line = JSON.stringify({ type: "event", event }) + "\n";
|
|
46
66
|
if (Buffer.byteLength(line) > 4 * 1024 * 1024) {
|
|
47
67
|
this.close();
|
|
48
68
|
this.socket.write(JSON.stringify({ type: "event", event: { type: "resync_required", reason: "snapshot-too-large: narrow the scope or limit" } }) + "\n");
|
|
49
69
|
return;
|
|
50
70
|
}
|
|
71
|
+
if (snapshot) this.lastSnapshotSeq = snapshot.seq;
|
|
51
72
|
this.socket.write(line);
|
|
73
|
+
queryEncodingMetrics.frames++; queryEncodingMetrics.bytes += Buffer.byteLength(line);
|
|
52
74
|
}
|
|
53
75
|
handle(command: Record<string, unknown>) {
|
|
54
76
|
if (command.type === "runtime_unsubscribe") { this.close(); return { unsubscribed: true }; }
|
|
55
77
|
if (command.type === "runtime_get_metrics") return { ...this.model.metrics };
|
|
56
78
|
const scope = workScope(command.scope);
|
|
57
79
|
const snapshot = this.model.snapshot(scope);
|
|
58
|
-
if (Buffer.byteLength(
|
|
80
|
+
if (Buffer.byteLength(snapshotJSON(snapshot)) > 4 * 1024 * 1024 - 1024) throw new Error("state-degraded: snapshot exceeds the 4 MiB frame allowance; narrow the scope or limit");
|
|
59
81
|
if (command.type === "runtime_subscribe") {
|
|
60
82
|
this.close();
|
|
83
|
+
this.lastSnapshotSeq = snapshot.seq;
|
|
61
84
|
this.dispose = this.model.onChange(() => {
|
|
62
85
|
try {
|
|
63
86
|
this.event({ type: "runtime_snapshot", snapshot: this.model.snapshot({ ...scope, cursor: undefined }) });
|
|
@@ -4,19 +4,25 @@ import { resolve } from "node:path";
|
|
|
4
4
|
import type { Duplex } from "node:stream";
|
|
5
5
|
import type { WorkReadModel } from "./read-model.ts";
|
|
6
6
|
import { workScope } from "./queries.ts";
|
|
7
|
+
import { executionPhases, inventoryPhases } from "./read-watchdog-probe.ts";
|
|
8
|
+
import { notifyWorkBudget } from "./work-budget.ts";
|
|
9
|
+
import { HostSourceWatches } from "./source-watch.ts";
|
|
7
10
|
|
|
8
11
|
export interface EncodedRead { json: string }
|
|
9
|
-
interface Waiter { connection: number; resolve(value: EncodedRead): void; reject(error: Error): void }
|
|
12
|
+
interface Waiter { connection: number; expiresAt: number; deadline: ReturnType<typeof setTimeout>; resolve(value: EncodedRead): void; reject(error: Error): void }
|
|
10
13
|
interface Query {
|
|
11
14
|
id: number; key?: string; command: Record<string, unknown>; connection: number;
|
|
12
|
-
enqueued: number;
|
|
15
|
+
enqueued: number; started?: number; progressAt: number; waiters: Set<Waiter>;
|
|
13
16
|
}
|
|
14
17
|
export type ReadStream = Pick<Duplex, "destroyed" | "writableLength" | "write" | "on" | "once" | "off">;
|
|
15
18
|
interface Stream { socket: ReadStream; paused: boolean; generation: number; drain: () => void; close: () => void }
|
|
16
19
|
interface WorkerMetrics { sourceWatchers?: number; inventories?: number; coordinatorConnections?: number; indexConnections?: number; sqlite?: { opens: number; active: number; maximum: number }; [key: string]: unknown }
|
|
17
20
|
export interface QueryExecutorOptions {
|
|
18
|
-
|
|
21
|
+
queryCacheDiagnostics?: boolean;
|
|
22
|
+
capacity?: number; timeoutMs?: number; maxConnections?: number; watchdogMs?: number;
|
|
19
23
|
workerUrl?: URL;
|
|
24
|
+
logWatchdog?: (line: string) => void;
|
|
25
|
+
budgetBuffer?: SharedArrayBuffer;
|
|
20
26
|
onTerminalLogsChanged?: (ids: string[]) => Promise<void>;
|
|
21
27
|
modelOptions?: { supervisorDirectory?: string; baseDir?: string; durableDir?: string; intervalMs?: number };
|
|
22
28
|
}
|
|
@@ -24,6 +30,7 @@ export interface QueryExecutorOptions {
|
|
|
24
30
|
/** One root, one read worker, one admitted operation at a time. No mutation RPC. */
|
|
25
31
|
export class WorkQueryExecutor {
|
|
26
32
|
private worker: Worker;
|
|
33
|
+
private sourceWatches = new HostSourceWatches();
|
|
27
34
|
private streams = new Map<number, Stream>();
|
|
28
35
|
private workerConnections = new Set<number>();
|
|
29
36
|
private queue: Query[] = [];
|
|
@@ -40,6 +47,11 @@ export class WorkQueryExecutor {
|
|
|
40
47
|
private recoveryAttempts: number[] = [];
|
|
41
48
|
private internalRecoveryDemand = false;
|
|
42
49
|
private recoveryTimer?: ReturnType<typeof setTimeout>;
|
|
50
|
+
private watchdog?: ReturnType<typeof setInterval>;
|
|
51
|
+
private watchdogCheck?: ReturnType<typeof setImmediate>;
|
|
52
|
+
private lastResponse = performance.now();
|
|
53
|
+
private heartbeat!: BigInt64Array;
|
|
54
|
+
private probe?: Int32Array;
|
|
43
55
|
private workerMetrics: WorkerMetrics = {};
|
|
44
56
|
private lastObservation: Omit<ReturnType<WorkReadModel["observation"]>, "observedAt"> & { observedAt: number | null } = {
|
|
45
57
|
status: "rebuilding", reason: "Initial source inventory is rebuilding.", observedAt: null, reasons: [],
|
|
@@ -51,27 +63,97 @@ export class WorkQueryExecutor {
|
|
|
51
63
|
private rejected = 0;
|
|
52
64
|
private cancelled = 0;
|
|
53
65
|
private timeouts = 0;
|
|
66
|
+
private queueTimeouts = 0;
|
|
67
|
+
private callerTimeouts = 0;
|
|
54
68
|
private durations: number[] = [];
|
|
55
69
|
private options: QueryExecutorOptions;
|
|
56
70
|
private agentDir: string;
|
|
57
71
|
readonly instanceId: string;
|
|
72
|
+
requestReasons() {
|
|
73
|
+
return [...this.queue, ...(this.active ? [this.active] : [])].flatMap(query => [...query.waiters].map(waiter => ({
|
|
74
|
+
kind: 'read-request', id: query.id, connection: waiter.connection, generation: this.workerGeneration,
|
|
75
|
+
phase: query.started === undefined ? 'queued' : 'dispatched',
|
|
76
|
+
lastProgressAt: query.progressAt,
|
|
77
|
+
nextDeadline: waiter.expiresAt, executionDeadline: null,
|
|
78
|
+
recovery: 'caller-timeout-or-disconnect-removes-waiter-without-cancelling-physical-worker-work',
|
|
79
|
+
})));
|
|
80
|
+
}
|
|
58
81
|
|
|
59
82
|
constructor(agentDir: string, instanceId: string, options: QueryExecutorOptions = {}) {
|
|
60
83
|
this.options = options; this.instanceId = instanceId; this.agentDir = agentDir;
|
|
61
84
|
this.lag.enable();
|
|
62
85
|
this.worker = this.startWorker();
|
|
86
|
+
const watchdogMs = this.options.watchdogMs ?? 4000;
|
|
87
|
+
let previousCheck = performance.now();
|
|
88
|
+
let resumedAt = previousCheck;
|
|
89
|
+
this.watchdog = setInterval(() => {
|
|
90
|
+
const now = performance.now();
|
|
91
|
+
// After system sleep both threads can resume with an expired heartbeat.
|
|
92
|
+
if (now - previousCheck > watchdogMs) resumedAt = now;
|
|
93
|
+
previousCheck = now;
|
|
94
|
+
if (this.closed || this.failure || now - Math.max(this.lastResponse, resumedAt) <= watchdogMs) return;
|
|
95
|
+
// Drain queued worker responses before treating a delayed timer as worker silence.
|
|
96
|
+
this.watchdogCheck ??= setImmediate(() => {
|
|
97
|
+
this.watchdogCheck = undefined;
|
|
98
|
+
this.checkWatchdog();
|
|
99
|
+
});
|
|
100
|
+
this.watchdogCheck.unref();
|
|
101
|
+
}, Math.min(250, watchdogMs / 4));
|
|
102
|
+
this.watchdog.unref();
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
private checkWatchdog() {
|
|
106
|
+
const silenceMs = performance.now() - this.lastResponse;
|
|
107
|
+
if (!this.closed && !this.failure && silenceMs > (this.options.watchdogMs ?? 4000)) {
|
|
108
|
+
const tick = Atomics.load(this.heartbeat, 0);
|
|
109
|
+
const heartbeatAgeMs = tick === 0n ? null : Number(process.hrtime.bigint() - tick) / 1e6;
|
|
110
|
+
// A busy parent can run the overdue watchdog before draining queued messages.
|
|
111
|
+
if (heartbeatAgeMs !== null && heartbeatAgeMs <= (this.options.watchdogMs ?? 4000)) return;
|
|
112
|
+
if (this.probe) {
|
|
113
|
+
const evidence = { generation: this.workerGeneration, silenceMs: Math.round(silenceMs),
|
|
114
|
+
heartbeatAgeMs: heartbeatAgeMs === null ? null : Math.round(heartbeatAgeMs),
|
|
115
|
+
mainLoopMaxDelayMs: Math.round(this.lag.max / 1e6), active: !!this.active, queued: this.queue.length,
|
|
116
|
+
execution: executionPhases[Atomics.load(this.probe, 0)], inventory: inventoryPhases[Atomics.load(this.probe, 1)] };
|
|
117
|
+
try { this.options.logWatchdog?.(`Read worker watchdog: ${JSON.stringify(evidence)}`); } catch { /* preserve watchdog behavior */ }
|
|
118
|
+
}
|
|
119
|
+
this.fail(new Error("runtime-unhealthy: read worker unresponsive; watchdog deadline exceeded"));
|
|
120
|
+
}
|
|
63
121
|
}
|
|
64
122
|
|
|
65
123
|
private startWorker() {
|
|
124
|
+
if (this.options.budgetBuffer) {
|
|
125
|
+
// startWorker runs only initially or after the preceding thread exited.
|
|
126
|
+
// A dead generation cannot retain source credits in the shared budget.
|
|
127
|
+
const counts = new Int32Array(this.options.budgetBuffer);
|
|
128
|
+
Atomics.store(counts, 1, 0); Atomics.store(counts, 2, 0);
|
|
129
|
+
notifyWorkBudget(this.options.budgetBuffer);
|
|
130
|
+
}
|
|
131
|
+
const generation = this.workerGeneration;
|
|
66
132
|
const instanceId = this.workerGeneration ? `${this.instanceId}:reads:${this.workerGeneration}` : this.instanceId;
|
|
133
|
+
this.heartbeat = new BigInt64Array(new SharedArrayBuffer(BigInt64Array.BYTES_PER_ELEMENT));
|
|
134
|
+
this.probe = this.options.logWatchdog ? new Int32Array(new SharedArrayBuffer(8)) : undefined;
|
|
67
135
|
const worker = new Worker(this.options.workerUrl ?? new URL("./query-worker.mjs", import.meta.url), {
|
|
68
|
-
execArgv: [], workerData: { agentDir: this.agentDir, instanceId, modelOptions: this.options.modelOptions },
|
|
136
|
+
execArgv: [], workerData: { agentDir: this.agentDir, instanceId, modelOptions: { ...this.options.modelOptions, budgetBuffer: this.options.budgetBuffer },
|
|
137
|
+
queryCacheDiagnostics: this.options.queryCacheDiagnostics === true, probe: this.probe, heartbeat: this.heartbeat },
|
|
138
|
+
});
|
|
139
|
+
worker.on("message", message => {
|
|
140
|
+
if (this.sourceWatches.handle(generation, message, value => {
|
|
141
|
+
if (worker === this.worker && !this.exited) worker.postMessage(value);
|
|
142
|
+
})) return;
|
|
143
|
+
if (worker === this.worker) this.receive(message);
|
|
144
|
+
});
|
|
145
|
+
worker.on("error", error => {
|
|
146
|
+
if (worker !== this.worker) return;
|
|
147
|
+
const original = String(error);
|
|
148
|
+
// Preserve the SQLite producer that the forwarded Error message omits.
|
|
149
|
+
const producer = /database (?:is locked|table is locked)/.test(original)
|
|
150
|
+
? `\n${String(error instanceof Error ? error.stack ?? error : error).split("\n").slice(0, 12).join("\n").slice(0, 4096)}` : "";
|
|
151
|
+
this.fail(new Error(`runtime-unhealthy: read worker failed: ${original}${producer}`, { cause: error }));
|
|
69
152
|
});
|
|
70
|
-
worker.on("message", message => { if (worker === this.worker) this.receive(message); });
|
|
71
|
-
worker.on("error", error => { if (worker === this.worker) this.fail(new Error(`runtime-unhealthy: read worker failed: ${String(error)}`)); });
|
|
72
153
|
worker.on("exit", code => {
|
|
73
154
|
if (worker !== this.worker) return;
|
|
74
155
|
this.exited = true;
|
|
156
|
+
void this.sourceWatches.revoke(generation).catch(() => {});
|
|
75
157
|
const sqlite = this.workerMetrics.sqlite;
|
|
76
158
|
this.workerMetrics = { ...this.workerMetrics, sourceWatchers: 0, coordinatorConnections: 0, indexConnections: 0,
|
|
77
159
|
...(sqlite ? { sqlite: { ...sqlite, active: 0 } } : {}) };
|
|
@@ -99,6 +181,7 @@ export class WorkQueryExecutor {
|
|
|
99
181
|
this.internalRecoveryDemand = false;
|
|
100
182
|
this.exited = false; this.failure = undefined; this.termination = undefined;
|
|
101
183
|
this.workerMetrics = {}; this.workerConnections.clear(); this.revision++;
|
|
184
|
+
this.lastResponse = performance.now();
|
|
102
185
|
this.lastObservation = { status: "rebuilding", reason: "Read worker is recovering its source inventory.", observedAt: null, reasons: [] };
|
|
103
186
|
this.lag.reset(); this.lag.enable();
|
|
104
187
|
try { this.worker = this.startWorker(); }
|
|
@@ -145,9 +228,9 @@ export class WorkQueryExecutor {
|
|
|
145
228
|
}
|
|
146
229
|
|
|
147
230
|
metrics() {
|
|
148
|
-
return { ...this.workerMetrics, executor: { active: this.active ? 1 : 0, queued: this.queue.length,
|
|
231
|
+
return { ...this.workerMetrics, sourceSubscriptions: this.sourceWatches.metrics(), executor: { active: this.active ? 1 : 0, queued: this.queue.length,
|
|
149
232
|
clients: this.streams.size, completed: this.completed, singleflightHits: this.coalesced, rejected: this.rejected,
|
|
150
|
-
cancelled: this.cancelled, timeouts: this.timeouts,
|
|
233
|
+
cancelled: this.cancelled, timeouts: this.timeouts, queueTimeouts: this.queueTimeouts, callerTimeouts: this.callerTimeouts,
|
|
151
234
|
capacity: this.options.capacity ?? 64, waitMs: [...this.waits], readMs: [...this.durations],
|
|
152
235
|
eventLoopLagMs: { p50: this.lag.percentile(50) / 1e6, p95: this.lag.percentile(95) / 1e6, p99: this.lag.percentile(99) / 1e6 },
|
|
153
236
|
worker: this.exited ? "stopped" : this.failure ? "stopping" : "running",
|
|
@@ -162,9 +245,21 @@ export class WorkQueryExecutor {
|
|
|
162
245
|
if (connection === 0) this.internalRecoveryDemand = true;
|
|
163
246
|
this.scheduleRecovery(); return Promise.reject(this.failure);
|
|
164
247
|
}
|
|
165
|
-
if (!["runtime_get_snapshot", "runtime_subscribe", "runtime_unsubscribe", "runtime_get_liveness", "runtime_get_upgrade_obligations"].includes(String(input.type))) return Promise.reject(new Error("Unsupported read operation"));
|
|
166
248
|
if (input.sinceSeq !== undefined && !Number.isSafeInteger(input.sinceSeq)) return Promise.reject(new Error("Invalid replay sequence"));
|
|
167
249
|
if (input.instanceId !== undefined && (typeof input.instanceId !== "string" || input.instanceId.length > 256)) return Promise.reject(new Error("Invalid runtime instance"));
|
|
250
|
+
if (input.type === "runtime_unsubscribe") {
|
|
251
|
+
for (const query of [...this.queue, ...(this.active ? [this.active] : [])]) {
|
|
252
|
+
if (query.command.type !== "runtime_subscribe" || query.connection !== connection) continue;
|
|
253
|
+
this.finish(query, new Error("runtime-unavailable: subscription cancelled"));
|
|
254
|
+
this.release(query);
|
|
255
|
+
}
|
|
256
|
+
const stream = this.streams.get(connection);
|
|
257
|
+
if (stream) stream.generation++;
|
|
258
|
+
this.worker.postMessage({ type: "detach", connection });
|
|
259
|
+
this.workerConnections.delete(connection);
|
|
260
|
+
return Promise.resolve({ json: '{"unsubscribed":true}' });
|
|
261
|
+
}
|
|
262
|
+
if (!["runtime_get_snapshot", "runtime_subscribe", "runtime_unsubscribe", "runtime_get_liveness", "runtime_get_upgrade_obligations"].includes(String(input.type))) return Promise.reject(new Error("Unsupported read operation"));
|
|
168
263
|
const command: Record<string, unknown> = { type: input.type, sinceSeq: input.sinceSeq, instanceId: input.instanceId };
|
|
169
264
|
if (command.type !== "runtime_unsubscribe" && command.type !== "runtime_get_liveness" && command.type !== "runtime_get_upgrade_obligations") {
|
|
170
265
|
const scope = workScope(input.scope);
|
|
@@ -183,13 +278,17 @@ export class WorkQueryExecutor {
|
|
|
183
278
|
return Promise.reject(new Error("runtime-overloaded: read queue is full; retry later"));
|
|
184
279
|
}
|
|
185
280
|
const id = ++this.counter;
|
|
186
|
-
query = { id, key, command, connection: key ? 0 : connection, enqueued: performance.now(),
|
|
187
|
-
deadline: setTimeout(() => this.expire(id), this.options.timeoutMs ?? 4000), waiters: new Set() };
|
|
281
|
+
query = { id, key, command, connection: key ? 0 : connection, enqueued: performance.now(), progressAt: Date.now(), waiters: new Set() };
|
|
188
282
|
this.queue.push(query);
|
|
189
283
|
if (key) this.flights.set(key, query);
|
|
190
284
|
}
|
|
191
285
|
const admitted = query;
|
|
192
|
-
const result = new Promise<EncodedRead>((resolve, reject) =>
|
|
286
|
+
const result = new Promise<EncodedRead>((resolve, reject) => {
|
|
287
|
+
const waiter: Waiter = { connection, resolve, reject,
|
|
288
|
+
expiresAt: Date.now() + (this.options.timeoutMs ?? 4000),
|
|
289
|
+
deadline: setTimeout(() => this.expire(admitted, waiter), this.options.timeoutMs ?? 4000) };
|
|
290
|
+
admitted.waiters.add(waiter);
|
|
291
|
+
});
|
|
193
292
|
this.pump();
|
|
194
293
|
return result;
|
|
195
294
|
}
|
|
@@ -197,6 +296,8 @@ export class WorkQueryExecutor {
|
|
|
197
296
|
private pump() {
|
|
198
297
|
if (this.failure || this.active || !this.queue.length) return;
|
|
199
298
|
const query = this.active = this.queue.shift()!;
|
|
299
|
+
query.started = performance.now();
|
|
300
|
+
query.progressAt = Date.now();
|
|
200
301
|
this.waits.push(performance.now() - query.enqueued);
|
|
201
302
|
if (this.waits.length > 128) this.waits.shift();
|
|
202
303
|
const stream = this.streams.get(query.connection);
|
|
@@ -207,6 +308,13 @@ export class WorkQueryExecutor {
|
|
|
207
308
|
|
|
208
309
|
private receive(message: any) {
|
|
209
310
|
if (this.failure) return;
|
|
311
|
+
this.lastResponse = performance.now();
|
|
312
|
+
if (message.type === "heartbeat") { this.worker.postMessage({ type: "heartbeat-consumed" }); return; }
|
|
313
|
+
// Replies to cancelled reads carry no fresh observation or metrics authority.
|
|
314
|
+
if (message.type === "reply" && (!this.active || message.id !== this.active.id || !this.active.waiters.size)) {
|
|
315
|
+
if (message.id === this.active?.id) { this.active = undefined; this.pump(); }
|
|
316
|
+
return;
|
|
317
|
+
}
|
|
210
318
|
if (message.metrics) this.workerMetrics = message.metrics;
|
|
211
319
|
if (message.observation) this.lastObservation = message.observation;
|
|
212
320
|
if (message.type === "terminal-logs") {
|
|
@@ -227,27 +335,40 @@ export class WorkQueryExecutor {
|
|
|
227
335
|
if (message.type !== "reply" || message.id !== this.active?.id) return;
|
|
228
336
|
const query = this.active!;
|
|
229
337
|
this.active = undefined; this.completed++;
|
|
230
|
-
this.durations.push(performance.now() - query.
|
|
338
|
+
this.durations.push(performance.now() - query.started!);
|
|
231
339
|
if (this.durations.length > 128) this.durations.shift();
|
|
232
340
|
this.finish(query, message.error ? new Error(message.error) : undefined, { json: message.json });
|
|
233
341
|
this.pump();
|
|
234
342
|
}
|
|
235
343
|
|
|
236
344
|
private finish(query: Query, error?: Error, value: EncodedRead = { json: "null" }) {
|
|
237
|
-
clearTimeout(query.deadline);
|
|
238
345
|
if (query.key && this.flights.get(query.key) === query) this.flights.delete(query.key);
|
|
239
|
-
for (const waiter of query.waiters) { if (error) waiter.reject(error); else waiter.resolve(value); }
|
|
346
|
+
for (const waiter of query.waiters) { clearTimeout(waiter.deadline); if (error) waiter.reject(error); else waiter.resolve(value); }
|
|
240
347
|
query.waiters.clear();
|
|
241
348
|
}
|
|
242
349
|
|
|
243
|
-
private expire(
|
|
350
|
+
private expire(query: Query, waiter: Waiter) {
|
|
351
|
+
if (!query.waiters.delete(waiter)) return;
|
|
244
352
|
this.timeouts++;
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
this.
|
|
353
|
+
if (query === this.active) this.callerTimeouts++;
|
|
354
|
+
else this.queueTimeouts++;
|
|
355
|
+
waiter.reject(new Error(query === this.active
|
|
356
|
+
? "runtime-timeout: caller read deadline exceeded; source was not verified"
|
|
357
|
+
: "runtime-overloaded: queued read deadline exceeded; retry later"));
|
|
358
|
+
this.release(query);
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
private release(query: Query) {
|
|
362
|
+
if (query.waiters.size) return;
|
|
363
|
+
this.finish(query);
|
|
364
|
+
if (query === this.active) {
|
|
365
|
+
// Keep the execution slot until cancellation is acknowledged. This bounds
|
|
366
|
+
// the worker mailbox even when native work cannot be interrupted.
|
|
367
|
+
this.worker.postMessage({ type: "cancel", id: query.id });
|
|
368
|
+
} else {
|
|
369
|
+
const index = this.queue.indexOf(query);
|
|
370
|
+
if (index >= 0) this.queue.splice(index, 1);
|
|
371
|
+
}
|
|
251
372
|
}
|
|
252
373
|
|
|
253
374
|
private event(connection: number, line: string) {
|
|
@@ -265,12 +386,9 @@ export class WorkQueryExecutor {
|
|
|
265
386
|
if (this.workerConnections.delete(connection) && !this.failure) this.worker.postMessage({ type: "detach", connection });
|
|
266
387
|
for (const query of [...this.queue, ...(this.active ? [this.active] : [])]) {
|
|
267
388
|
for (const waiter of query.waiters) if (waiter.connection === connection) {
|
|
268
|
-
query.waiters.delete(waiter); this.cancelled++; waiter.reject(new Error("runtime-unavailable: client disconnected"));
|
|
269
|
-
}
|
|
270
|
-
if (!query.waiters.size && query !== this.active) {
|
|
271
|
-
this.queue.splice(this.queue.indexOf(query), 1);
|
|
272
|
-
this.finish(query);
|
|
389
|
+
query.waiters.delete(waiter); clearTimeout(waiter.deadline); this.cancelled++; waiter.reject(new Error("runtime-unavailable: client disconnected"));
|
|
273
390
|
}
|
|
391
|
+
this.release(query);
|
|
274
392
|
}
|
|
275
393
|
}
|
|
276
394
|
|
|
@@ -283,18 +401,21 @@ export class WorkQueryExecutor {
|
|
|
283
401
|
this.queue = []; this.active = undefined;
|
|
284
402
|
for (const connection of this.streams.keys()) this.event(connection, JSON.stringify({ type: "event",
|
|
285
403
|
event: { type: "resync_required", reason: error.message, instanceId: this.instanceId } }) + "\n");
|
|
404
|
+
void this.sourceWatches.revoke(this.workerGeneration).catch(() => {});
|
|
286
405
|
this.termination = this.worker.terminate();
|
|
287
406
|
this.worker.unref();
|
|
288
407
|
}
|
|
289
408
|
|
|
290
409
|
async close() {
|
|
291
410
|
this.closed = true;
|
|
411
|
+
if (this.watchdog) clearInterval(this.watchdog);
|
|
412
|
+
if (this.watchdogCheck) clearImmediate(this.watchdogCheck);
|
|
292
413
|
if (this.recoveryTimer) { clearTimeout(this.recoveryTimer); this.recoveryTimer = undefined; }
|
|
293
414
|
this.fail(new Error("runtime-unavailable: query executor closed"));
|
|
294
415
|
for (const connection of this.streams.keys()) this.detach(connection);
|
|
295
416
|
let timeout: ReturnType<typeof setTimeout> | undefined;
|
|
296
417
|
// Bound graceful close even while native SQLite is still finishing a call.
|
|
297
|
-
await Promise.race([this.termination, new Promise<void>(resolve => { timeout = setTimeout(resolve, 1000); })]);
|
|
418
|
+
await Promise.race([Promise.all([this.termination, this.sourceWatches.close().catch(() => {})]), new Promise<void>(resolve => { timeout = setTimeout(resolve, 1000); })]);
|
|
298
419
|
if (timeout) clearTimeout(timeout);
|
|
299
420
|
}
|
|
300
421
|
}
|