@myclaw163/clawclaw-cli 0.6.112 → 0.7.4
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/QUICKSTART.md +46 -0
- package/QUICKSTART_HERMES.md +134 -0
- package/QUICKSTART_OPENCLAW.md +134 -0
- package/QUICKSTART_OTHER.md +134 -0
- package/README.md +23 -398
- package/bin/clawclaw-cli.mjs +9 -1
- package/docs/configuration.md +197 -0
- package/docs/runtime/README.md +52 -0
- package/docs/runtime/agent-notifications.md +55 -0
- package/docs/runtime/components-and-boundaries.md +213 -0
- package/docs/runtime/events-and-state.md +105 -0
- package/docs/runtime/owner-lifecycle-and-observability.md +69 -0
- package/docs/runtime/perception-replay.md +51 -0
- package/docs/runtime/short-commands-and-capabilities.md +55 -0
- package/docs/runtime/strategy-runtime.md +111 -0
- package/docs//350/207/252/345/256/232/344/271/211/346/204/237/347/237/245.md +488 -0
- package/docs//350/207/252/345/256/232/344/271/211/347/255/226/347/225/245.md +395 -0
- package/package.json +25 -8
- package/scripts/check-skill-command-surface.mjs +16 -7
- package/scripts/compare-perception-replays.test.ts +188 -0
- package/scripts/compare-perception-replays.ts +589 -0
- package/scripts/generate-spatial-facts.py +246 -0
- package/scripts/package-readme.mjs +48 -0
- package/scripts/replay-perception.ts +347 -0
- package/scripts/sync-frontend-map.mjs +195 -0
- package/scripts/watch-perception-events.test.ts +43 -0
- package/scripts/watch-perception-events.ts +162 -0
- package/skills/clawclaw/SKILL.md +120 -64
- package/skills/clawclaw/references/CHATTERBOX.md +2 -4
- package/skills/clawclaw/references/CLAUDE-CODE-MONITOR.md +1 -1
- package/skills/clawclaw/references/COMMANDS.md +95 -61
- package/skills/clawclaw/references/GAME-MECHANICS.md +18 -8
- package/skills/clawclaw/references/HUB.md +5 -5
- package/skills/clawclaw/references/STRATEGIES.md +34 -17
- package/skills/clawclaw/references/STREAM.md +82 -46
- package/src/assets/clawclaw-map.json +1692 -0
- package/src/assets/clawclaw-spatial-facts.json +1291 -0
- package/src/cli.ts +21 -47
- package/src/commands/account.test.ts +229 -50
- package/src/commands/account.ts +456 -223
- package/src/commands/communication.test.ts +259 -0
- package/src/commands/communication.ts +391 -0
- package/src/commands/competition.test.ts +116 -0
- package/src/commands/competition.ts +50 -28
- package/src/commands/data.test.ts +57 -1
- package/src/commands/data.ts +79 -4
- package/src/commands/events-canonical-state.test.ts +187 -0
- package/src/commands/events.test.ts +50 -136
- package/src/commands/events.ts +175 -241
- package/src/commands/game/index.test.ts +510 -0
- package/src/commands/game/index.ts +556 -0
- package/src/commands/game-map.test.ts +40 -3
- package/src/commands/hub.test.ts +2 -23
- package/src/commands/hub.ts +4 -16
- package/src/commands/load.test.ts +10 -22
- package/src/commands/load.ts +15 -2
- package/src/commands/peek.ts +2 -3
- package/src/commands/perception.test.ts +46 -0
- package/src/commands/perception.ts +92 -0
- package/src/commands/setup/codex.ts +0 -1
- package/src/commands/strategy.test.ts +139 -102
- package/src/commands/strategy.ts +175 -103
- package/src/commands/upgrade.ts +0 -21
- package/src/lib/auth.test.ts +35 -0
- package/src/lib/auth.ts +45 -6
- package/src/lib/diagnostics-config.test.ts +59 -0
- package/src/lib/diagnostics-config.ts +76 -0
- package/src/lib/game-client.test.ts +166 -0
- package/src/lib/game-client.ts +316 -87
- package/src/lib/game-context.ts +29 -0
- package/src/lib/gameplay-config.test.ts +66 -0
- package/src/lib/gameplay-config.ts +151 -0
- package/src/lib/http-transport.test.ts +63 -0
- package/src/lib/http-transport.ts +76 -10
- package/src/lib/init-command.test.ts +25 -1
- package/src/lib/init-command.ts +66 -1
- package/src/lib/participation-leave.ts +78 -0
- package/src/lib/perception-config.test.ts +138 -0
- package/src/lib/perception-config.ts +101 -0
- package/src/lib/room.test.ts +14 -0
- package/src/lib/room.ts +28 -2
- package/src/lib/server-registry.test.ts +15 -5
- package/src/lib/server-registry.ts +9 -10
- package/src/lib/strategy-export.test.ts +123 -44
- package/src/lib/strategy-export.ts +110 -81
- package/src/lib/user-data.test.ts +2 -0
- package/src/lib/user-data.ts +17 -16
- package/src/pipeline/canonical-event-presentation.test.ts +195 -0
- package/src/pipeline/canonical-event-presentation.ts +71 -0
- package/src/pipeline/event-format.test.ts +357 -59
- package/src/pipeline/event-format.ts +365 -80
- package/src/pipeline/event-hints.test.ts +241 -0
- package/src/pipeline/event-hints.ts +202 -51
- package/src/pipeline/game-sync-event-normalization.test.ts +239 -0
- package/src/pipeline/game-sync-event-normalization.ts +215 -0
- package/src/pipeline/player-projection.test.ts +164 -102
- package/src/pipeline/player-projection.ts +194 -235
- package/src/runtime/canonical-event-emitter.test.ts +70 -0
- package/src/runtime/canonical-event-emitter.ts +78 -0
- package/src/runtime/canonical-monitor.test.ts +575 -0
- package/src/runtime/canonical-monitor.ts +388 -0
- package/src/runtime/clawclaw/agent-event-policy.test.ts +27 -0
- package/src/runtime/clawclaw/agent-event-policy.ts +35 -0
- package/src/runtime/clawclaw/index.ts +4 -0
- package/src/runtime/clawclaw/notifications.test.ts +47 -0
- package/src/runtime/clawclaw/notifications.ts +65 -0
- package/src/runtime/clawclaw/owner-lock.test.ts +221 -0
- package/src/runtime/clawclaw/owner.ts +945 -0
- package/src/runtime/clawclaw/plugins/action/action-plugin.ts +299 -0
- package/src/runtime/clawclaw/plugins/action/index.ts +1 -0
- package/src/runtime/clawclaw/plugins/assembly.test.ts +81 -0
- package/src/runtime/clawclaw/plugins/assembly.ts +116 -0
- package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.test.ts +150 -0
- package/src/runtime/clawclaw/plugins/derived-event/derived-event-plugin.ts +100 -0
- package/src/runtime/clawclaw/plugins/derived-event/derived-event-rules.ts +162 -0
- package/src/runtime/clawclaw/plugins/derived-event/index.ts +2 -0
- package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.test.ts +223 -0
- package/src/runtime/clawclaw/plugins/game-query/game-query-plugin.ts +236 -0
- package/src/runtime/clawclaw/plugins/game-query/index.ts +1 -0
- package/src/runtime/clawclaw/plugins/index.ts +7 -0
- package/src/runtime/clawclaw/plugins/mailbox/index.ts +3 -0
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-plugin.ts +77 -0
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-presentation.ts +91 -0
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.test.ts +1008 -0
- package/src/runtime/clawclaw/plugins/mailbox/mailbox-service.ts +475 -0
- package/src/runtime/clawclaw/plugins/perception/contracts.ts +32 -0
- package/src/runtime/clawclaw/plugins/perception/index.ts +8 -0
- package/src/runtime/clawclaw/plugins/perception/module-runner.test.ts +204 -0
- package/src/runtime/clawclaw/plugins/perception/module-runner.ts +290 -0
- package/src/runtime/clawclaw/plugins/perception/modules/co-movement-module.ts +324 -0
- package/src/runtime/clawclaw/plugins/perception/modules/follow-module.ts +365 -0
- package/src/runtime/clawclaw/plugins/perception/modules/index.ts +7 -0
- package/src/runtime/clawclaw/plugins/perception/modules/motion-module.test.ts +341 -0
- package/src/runtime/clawclaw/plugins/perception/modules/motion-module.ts +447 -0
- package/src/runtime/clawclaw/plugins/perception/modules/parallel-module-test-helpers.ts +30 -0
- package/src/runtime/clawclaw/plugins/perception/modules/relation-stability.test.ts +289 -0
- package/src/runtime/clawclaw/plugins/perception/modules/route-module.test.ts +180 -0
- package/src/runtime/clawclaw/plugins/perception/modules/route-module.ts +329 -0
- package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.test.ts +82 -0
- package/src/runtime/clawclaw/plugins/perception/modules/spatial-module.ts +172 -0
- package/src/runtime/clawclaw/plugins/perception/modules/stop-module.test.ts +212 -0
- package/src/runtime/clawclaw/plugins/perception/modules/stop-module.ts +256 -0
- package/src/runtime/clawclaw/plugins/perception/modules/temporal-evidence.test.ts +121 -0
- package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.test.ts +106 -0
- package/src/runtime/clawclaw/plugins/perception/modules/visibility-module.ts +225 -0
- package/src/runtime/clawclaw/plugins/perception/official-module-ids.ts +11 -0
- package/src/runtime/clawclaw/plugins/perception/official-modules.ts +31 -0
- package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.test.ts +759 -0
- package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-pool.ts +707 -0
- package/src/runtime/clawclaw/plugins/perception/perception-analysis-thread-worker.ts +215 -0
- package/src/runtime/clawclaw/plugins/perception/perception-module-loader.ts +61 -0
- package/src/runtime/clawclaw/plugins/perception/perception-plugin.test.ts +1516 -0
- package/src/runtime/clawclaw/plugins/perception/perception-plugin.ts +1529 -0
- package/src/runtime/clawclaw/plugins/perception/perception-source.test.ts +119 -0
- package/src/runtime/clawclaw/plugins/perception/perception-source.ts +244 -0
- package/src/runtime/clawclaw/plugins/perception/replay.test.ts +65 -0
- package/src/runtime/clawclaw/plugins/perception/replay.ts +86 -0
- package/src/runtime/clawclaw/plugins/perception/shared/math.ts +107 -0
- package/src/runtime/clawclaw/plugins/perception/spatial-facts.ts +114 -0
- package/src/runtime/clawclaw/plugins/perception/visual-state-projector.ts +98 -0
- package/src/runtime/clawclaw/plugins/runtime-plugins.test.ts +1019 -0
- package/src/runtime/clawclaw/plugins/source/game-transport.test.ts +287 -0
- package/src/runtime/clawclaw/plugins/source/game-transport.ts +281 -0
- package/src/runtime/clawclaw/plugins/source/index.ts +5 -0
- package/src/runtime/clawclaw/plugins/source/player-change-tracker.test.ts +270 -0
- package/src/runtime/clawclaw/plugins/source/player-change-tracker.ts +151 -0
- package/src/runtime/clawclaw/plugins/source/room-transport.test.ts +307 -0
- package/src/runtime/clawclaw/plugins/source/room-transport.ts +480 -0
- package/src/runtime/clawclaw/plugins/source/source-plugin.test.ts +1909 -0
- package/src/runtime/clawclaw/plugins/source/source-plugin.ts +2055 -0
- package/src/runtime/clawclaw/plugins/source/source-transports.ts +30 -0
- package/src/runtime/clawclaw/plugins/source/types.ts +79 -0
- package/src/runtime/clawclaw/plugins/strategy/context-capabilities.ts +5 -0
- package/src/runtime/clawclaw/plugins/strategy/examples/task-only-strategy.test.ts +177 -0
- package/src/runtime/clawclaw/plugins/strategy/examples/task-only-strategy.ts +185 -0
- package/src/runtime/clawclaw/plugins/strategy/index.ts +8 -0
- package/src/runtime/clawclaw/plugins/strategy/local-strategy-executor.ts +412 -0
- package/src/runtime/clawclaw/plugins/strategy/strategy-action.ts +73 -0
- package/src/runtime/clawclaw/plugins/strategy/strategy-analysis-thread-host.ts +183 -0
- package/src/runtime/clawclaw/plugins/strategy/strategy-executor-types.ts +25 -0
- package/src/runtime/clawclaw/plugins/strategy/strategy-executor.test.ts +693 -0
- package/src/runtime/clawclaw/plugins/strategy/strategy-game-api.ts +57 -0
- package/src/runtime/clawclaw/plugins/strategy/strategy-module-loader.ts +164 -0
- package/src/runtime/clawclaw/plugins/strategy/strategy-plugin.test.ts +1936 -0
- package/src/runtime/clawclaw/plugins/strategy/strategy-plugin.ts +1557 -0
- package/src/runtime/clawclaw/plugins/strategy/strategy-source.test.ts +131 -0
- package/src/runtime/clawclaw/plugins/strategy/strategy-source.ts +413 -0
- package/src/runtime/clawclaw/plugins/strategy/thread-strategy-executor.ts +792 -0
- package/src/runtime/clawclaw/runtime-data-export.test.ts +249 -0
- package/src/runtime/clawclaw/runtime-data-export.ts +402 -0
- package/src/runtime/clawclaw/runtime-state.ts +98 -0
- package/src/runtime/clawclaw/runtime.ts +133 -0
- package/src/runtime/clawclaw-event-catalog.test.ts +74 -0
- package/src/runtime/clawclaw-event-catalog.ts +266 -0
- package/src/runtime/clawclaw-position.ts +4 -0
- package/src/runtime/clawclaw-room-state.ts +51 -0
- package/src/runtime/framework/action-diagnostics.test.ts +81 -0
- package/src/runtime/framework/action-diagnostics.ts +146 -0
- package/src/runtime/framework/capability-registry.test.ts +282 -0
- package/src/runtime/framework/capability-registry.ts +283 -0
- package/src/runtime/framework/contracts.ts +118 -0
- package/src/runtime/framework/control/control-scheduler.ts +1260 -0
- package/src/runtime/framework/control/domain-set.ts +81 -0
- package/src/runtime/framework/control/index.ts +3 -0
- package/src/runtime/framework/control/types.ts +184 -0
- package/src/runtime/framework/control-coordinator.test.ts +660 -0
- package/src/runtime/framework/control-coordinator.ts +11 -0
- package/src/runtime/framework/events/event-catalog.ts +74 -0
- package/src/runtime/framework/events/event-delivery-service.test.ts +84 -0
- package/src/runtime/framework/events/event-delivery-service.ts +198 -0
- package/src/runtime/framework/events/event-ingress.test.ts +178 -0
- package/src/runtime/framework/events/event-ingress.ts +97 -0
- package/src/runtime/framework/events/event-repository.ts +59 -0
- package/src/runtime/framework/events/index.ts +7 -0
- package/src/runtime/framework/events/mailbox-event-repositories.test.ts +594 -0
- package/src/runtime/framework/events/memory-event-repository.ts +928 -0
- package/src/runtime/framework/events/sqlite-event-repository.test.ts +200 -0
- package/src/runtime/framework/events/sqlite-event-repository.ts +1681 -0
- package/src/runtime/framework/events/test-helpers.ts +78 -0
- package/src/runtime/framework/events/types.ts +286 -0
- package/src/runtime/framework/index.ts +7 -0
- package/src/runtime/framework/load-node-sqlite.ts +17 -0
- package/src/runtime/framework/mailbox/coalescer.test.ts +55 -0
- package/src/runtime/framework/mailbox/coalescer.ts +83 -0
- package/src/runtime/framework/mailbox/host-notification-sink.ts +44 -0
- package/src/runtime/framework/mailbox/identity.test.ts +38 -0
- package/src/runtime/framework/mailbox/identity.ts +38 -0
- package/src/runtime/framework/mailbox/index.ts +7 -0
- package/src/runtime/framework/mailbox/mailbox-dispatcher.test.ts +513 -0
- package/src/runtime/framework/mailbox/mailbox-dispatcher.ts +282 -0
- package/src/runtime/framework/mailbox/mailbox-repository.ts +44 -0
- package/src/runtime/framework/mailbox/notification-projector.test.ts +77 -0
- package/src/runtime/framework/mailbox/notification-projector.ts +65 -0
- package/src/runtime/framework/mailbox/types.ts +139 -0
- package/src/runtime/framework/modules/runtime-module-loader-hooks.d.mts +19 -0
- package/src/runtime/framework/modules/runtime-module-loader-hooks.mjs +117 -0
- package/src/runtime/framework/modules/runtime-module-loader.test.ts +209 -0
- package/src/runtime/framework/modules/runtime-module-loader.ts +71 -0
- package/src/runtime/framework/modules/runtime-module-worker-bootstrap.mjs +23 -0
- package/src/runtime/framework/participation-manager.test.ts +108 -0
- package/src/runtime/framework/participation-manager.ts +244 -0
- package/src/runtime/framework/plugins/contracts.ts +382 -0
- package/src/runtime/framework/plugins/index.ts +4 -0
- package/src/runtime/framework/plugins/runtime-event-identity.ts +17 -0
- package/src/runtime/framework/plugins/runtime-input-journal.test.ts +179 -0
- package/src/runtime/framework/plugins/runtime-input-journal.ts +693 -0
- package/src/runtime/framework/plugins/runtime-plugin-scheduler.test.ts +1994 -0
- package/src/runtime/framework/plugins/runtime-plugin-scheduler.ts +1860 -0
- package/src/runtime/framework/runtime.ts +1756 -0
- package/src/runtime/framework/serial-task-queue.ts +14 -0
- package/src/runtime/framework/state/contracts.ts +49 -0
- package/src/runtime/framework/state/current-state-store.ts +184 -0
- package/src/runtime/framework/state/durable-agent-state-snapshot.test.ts +144 -0
- package/src/runtime/framework/state/durable-agent-state-snapshot.ts +209 -0
- package/src/runtime/framework/state/freshness.ts +72 -0
- package/src/runtime/framework/state/history/contracts.ts +150 -0
- package/src/runtime/framework/state/history/history-writer.ts +194 -0
- package/src/runtime/framework/state/history/memory-state-history-repository.ts +178 -0
- package/src/runtime/framework/state/history/sqlite-state-history-repository.test.ts +157 -0
- package/src/runtime/framework/state/history/sqlite-state-history-repository.ts +629 -0
- package/src/runtime/framework/state/history/state-history.test.ts +251 -0
- package/src/runtime/framework/state/history/trajectory-projector.ts +209 -0
- package/src/runtime/framework/state/index.ts +13 -0
- package/src/runtime/framework/state/state-core.test.ts +197 -0
- package/src/runtime/framework/state/state-ingress.ts +95 -0
- package/src/runtime/framework/state/state-provider.ts +62 -0
- package/src/runtime/framework/state/types.ts +155 -0
- package/src/runtime/game-sync-protocol.test.ts +123 -0
- package/src/runtime/game-sync-protocol.ts +261 -0
- package/src/runtime/mailbox-host-relay.test.ts +248 -0
- package/src/runtime/mailbox-host-relay.ts +300 -0
- package/src/runtime/observability/factory.ts +188 -0
- package/src/runtime/observability/index.ts +6 -0
- package/src/runtime/observability/observability.test.ts +561 -0
- package/src/runtime/observability/recorder.ts +209 -0
- package/src/runtime/observability/redaction.ts +154 -0
- package/src/runtime/observability/reporter.ts +154 -0
- package/src/runtime/observability/sinks.ts +135 -0
- package/src/runtime/observability/types.ts +92 -0
- package/src/runtime/owner-control.test.ts +153 -0
- package/src/runtime/owner-control.ts +206 -42
- package/src/runtime/parent-process-watch.test.ts +27 -0
- package/src/runtime/parent-process-watch.ts +51 -0
- package/src/runtime/pending-event-handoff.test.ts +29 -0
- package/src/runtime/pending-event-handoff.ts +61 -0
- package/src/runtime/raw-ws-log.test.ts +86 -17
- package/src/runtime/raw-ws-log.ts +230 -21
- package/src/runtime/runtime-logger.test.ts +58 -0
- package/src/runtime/runtime-logger.ts +10 -13
- package/src/runtime/runtime-persistence.test.ts +26 -0
- package/src/runtime/runtime.test.ts +1704 -0
- package/src/runtime/ws-client.test.ts +496 -103
- package/src/runtime/ws-client.ts +546 -166
- package/src/sdk/action.ts +3 -1
- package/src/sdk/index.ts +4 -19
- package/src/sdk/perception-plugin/index.test.ts +22 -0
- package/src/sdk/perception-plugin/index.ts +285 -0
- package/src/sdk/strategy-plugin/index.test.ts +952 -0
- package/src/sdk/strategy-plugin/index.ts +1324 -0
- package/src/sdk/types.ts +3 -1
- package/src/short-command/classifier.test.ts +107 -0
- package/src/short-command/classifier.ts +169 -0
- package/src/short-command/index.ts +7 -0
- package/src/short-command/presenter.test.ts +119 -0
- package/src/short-command/presenter.ts +308 -0
- package/src/short-command/process-io.ts +13 -0
- package/src/short-command/response-contract.ts +58 -0
- package/src/short-command/runner.test.ts +78 -0
- package/src/short-command/runner.ts +164 -0
- package/src/short-command/sensitive-data-filter.test.ts +56 -0
- package/src/short-command/sensitive-data-filter.ts +123 -0
- package/src/short-command/transport-response.test.ts +39 -0
- package/src/short-command/transport-response.ts +89 -0
- package/src/short-command/types.ts +92 -0
- package/src/strategies/avoid-lone.ts +18 -11
- package/src/strategies/avoid-players.ts +29 -13
- package/src/strategies/corpse-patrol.ts +29 -11
- package/src/strategies/crab-sabotage.ts +31 -18
- package/src/strategies/custom-module.test.ts +3 -5
- package/src/strategies/find-player.ts +34 -15
- package/src/strategies/game-utils.test.ts +42 -0
- package/src/strategies/game-utils.ts +143 -53
- package/src/strategies/goals/avoid-lone-top.ts +22 -1
- package/src/strategies/goals/avoid-players-top.test.ts +13 -0
- package/src/strategies/goals/avoid-players-top.ts +6 -5
- package/src/strategies/goals/corpse-patrol-top.ts +9 -2
- package/src/strategies/goals/crab-octopus-reflexes.ts +6 -2
- package/src/strategies/goals/crab-sabotage-top.ts +7 -1
- package/src/strategies/goals/emergency-hunt-goal.ts +15 -3
- package/src/strategies/goals/find-player-top.ts +47 -3
- package/src/strategies/goals/flee-players-goal.ts +2 -0
- package/src/strategies/goals/follow-companion-goal.ts +27 -3
- package/src/strategies/goals/hide-top.ts +47 -5
- package/src/strategies/goals/keep-away-goal.ts +24 -2
- package/src/strategies/goals/kill-frenzy-top.ts +12 -2
- package/src/strategies/goals/kill-lone-top.test.ts +72 -0
- package/src/strategies/goals/kill-lone-top.ts +8 -6
- package/src/strategies/goals/kill-target-goal.ts +16 -7
- package/src/strategies/goals/kill-target-top.ts +16 -2
- package/src/strategies/goals/linger-corpse-goal.ts +11 -3
- package/src/strategies/goals/lone-kill-core.ts +4 -2
- package/src/strategies/goals/move-room-goal.ts +46 -4
- package/src/strategies/goals/normal-shrimp-top.test.ts +16 -0
- package/src/strategies/goals/normal-shrimp-top.ts +18 -18
- package/src/strategies/goals/paradise-fish-top.test.ts +78 -0
- package/src/strategies/goals/paradise-fish-top.ts +16 -6
- package/src/strategies/goals/patrol-top.ts +14 -3
- package/src/strategies/goals/report-patrol-top.ts +14 -3
- package/src/strategies/goals/safe-task-goal.ts +32 -4
- package/src/strategies/goals/social-task-top.ts +39 -8
- package/src/strategies/goals/task-kill-report-top.ts +33 -10
- package/src/strategies/goals/task-only-top.test.ts +89 -0
- package/src/strategies/goals/task-only-top.ts +9 -2
- package/src/strategies/goals/task-or-patrol-goal.ts +21 -3
- package/src/strategies/goals/warrior-shrimp-top.test.ts +75 -23
- package/src/strategies/goals/warrior-shrimp-top.ts +34 -13
- package/src/strategies/greeting.ts +10 -3
- package/src/strategies/hide-spots.ts +4 -0
- package/src/strategies/hide.ts +35 -20
- package/src/strategies/kill-frenzy.ts +18 -12
- package/src/strategies/kill-lone.ts +43 -12
- package/src/strategies/kill-target.ts +34 -17
- package/src/strategies/lone-kill-task.ts +31 -18
- package/src/strategies/move-room.ts +32 -15
- package/src/strategies/off-route-points.ts +12 -4
- package/src/strategies/paradise-fish.ts +49 -14
- package/src/strategies/pathfind/astar-path.test.ts +73 -0
- package/src/strategies/pathfind/astar-path.ts +196 -0
- package/src/strategies/pathfind/escape-planner.test.ts +27 -1
- package/src/strategies/pathfind/escape-planner.ts +108 -0
- package/src/strategies/patrol.ts +18 -11
- package/src/strategies/report-patrol.ts +18 -11
- package/src/strategies/shrimp-memory.ts +66 -14
- package/src/strategies/social-task.ts +49 -45
- package/src/strategies/task-kill-report.ts +34 -16
- package/src/strategies/task-only.test.ts +124 -0
- package/src/strategies/task-only.ts +20 -11
- package/src/strategies/task-report.ts +29 -11
- package/src/strategies/types.ts +29 -62
- package/src/strategies/warrior-memory.ts +44 -14
- package/scripts/check_monitor.test.mjs +0 -212
- package/skills/clawclaw/references/KNOWLEDGE.md +0 -42
- package/src/commands/do.test.ts +0 -117
- package/src/commands/do.ts +0 -195
- package/src/commands/game-monitor-status.test.ts +0 -58
- package/src/commands/game-start-plan.test.ts +0 -356
- package/src/commands/game.ts +0 -2046
- package/src/commands/history-player.test.ts +0 -105
- package/src/commands/history.ts +0 -573
- package/src/commands/knowledge.test.ts +0 -13
- package/src/commands/knowledge.ts +0 -176
- package/src/commands/meeting-history.test.ts +0 -106
- package/src/commands/state.ts +0 -46
- package/src/commands/watch.test.ts +0 -1313
- package/src/commands/watch.ts +0 -824
- package/src/lib/knowledge-store.test.ts +0 -170
- package/src/lib/knowledge-store.ts +0 -369
- package/src/perception/player-history-store.test.ts +0 -177
- package/src/perception/player-history-store.ts +0 -262
- package/src/pipeline/event-store.test.ts +0 -28
- package/src/pipeline/event-store.ts +0 -193
- package/src/pipeline/pipeline.ts +0 -35
- package/src/runtime/event-daemon.test.ts +0 -268
- package/src/runtime/event-daemon.ts +0 -531
- package/src/runtime/room-lobby-runtime.test.ts +0 -95
- package/src/runtime/room-lobby-runtime.ts +0 -367
- package/src/strategies/avoid-players.knowledge.md +0 -19
- package/src/strategies/kill-lone.knowledge.md +0 -17
- package/src/strategies/knowledge-contract.ts +0 -85
- package/src/strategies/loader.test.ts +0 -710
- package/src/strategies/loader.ts +0 -183
- package/src/strategies/new-events-backfill.ts +0 -98
- package/src/strategies/paradise-fish.knowledge.md +0 -19
- package/src/strategies/scanner.ts +0 -238
- package/src/strategies/shrimp-memory.knowledge.md +0 -19
- package/src/strategies/social-task.test.ts +0 -28
- package/src/strategies/spawn.ts +0 -82
- package/src/strategies/strategy-loop.test.ts +0 -15
- package/src/strategies/strategy-loop.ts +0 -748
- package/src/strategies/warrior-memory.knowledge.md +0 -21
|
@@ -0,0 +1,1860 @@
|
|
|
1
|
+
import { randomUUID } from 'crypto';
|
|
2
|
+
import type { CanonicalEvent, CommitEventResult } from '../events/types.js';
|
|
3
|
+
import type {
|
|
4
|
+
StateFrameHistoryReader,
|
|
5
|
+
StateFrameQuery,
|
|
6
|
+
StoredStateFrame,
|
|
7
|
+
} from '../state/history/contracts.js';
|
|
8
|
+
import type { StateProviderResult } from '../state/types.js';
|
|
9
|
+
import { cloneCanonical, runtimeScopeKey, type RuntimeScope } from '../state/types.js';
|
|
10
|
+
import type {
|
|
11
|
+
RuntimeEpoch,
|
|
12
|
+
RuntimeEpochExecutionResult,
|
|
13
|
+
RuntimeEpochFlushReason,
|
|
14
|
+
RuntimeEpochPlugin,
|
|
15
|
+
RuntimeEpochPluginContext,
|
|
16
|
+
RuntimeEpochPluginDescriptor,
|
|
17
|
+
RuntimeEpochPluginInput,
|
|
18
|
+
RuntimeEpochPluginOutcome,
|
|
19
|
+
RuntimeEpochPluginRecord,
|
|
20
|
+
RuntimeEpochPluginResult,
|
|
21
|
+
RuntimeEpochStateRecord,
|
|
22
|
+
RuntimeDiagnosticSeverity,
|
|
23
|
+
RuntimeEventProposal,
|
|
24
|
+
RuntimeInputJournal,
|
|
25
|
+
RuntimePluginCapabilityAccess,
|
|
26
|
+
RuntimePluginFailurePolicy,
|
|
27
|
+
RuntimePluginStore,
|
|
28
|
+
} from './contracts.js';
|
|
29
|
+
|
|
30
|
+
export interface RuntimeEpochWork<TState = Record<string, unknown>, TEvent = Record<string, unknown>> {
|
|
31
|
+
epoch: RuntimeEpoch<TState, TEvent>;
|
|
32
|
+
frame: StoredStateFrame<TState>;
|
|
33
|
+
/** Game-facing State captured at acceptance of this exact epoch. */
|
|
34
|
+
currentState: StateProviderResult<Record<string, any> | null>;
|
|
35
|
+
previousState: TState | null;
|
|
36
|
+
epochEvents: CanonicalEvent[];
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
export interface RuntimePluginSchedulerOptions<
|
|
40
|
+
TState = Record<string, unknown>,
|
|
41
|
+
TEvent = Record<string, unknown>,
|
|
42
|
+
> {
|
|
43
|
+
plugins?: readonly RuntimeEpochPlugin<TState, TEvent>[];
|
|
44
|
+
inputJournal: RuntimeInputJournal<TState, TEvent>;
|
|
45
|
+
pluginStore: RuntimePluginStore;
|
|
46
|
+
stateHistory: StateFrameHistoryReader<TState>;
|
|
47
|
+
/** Commit the immutable Source Events before any plugin processes this epoch. */
|
|
48
|
+
commitInputEvents(work: RuntimeEpochWork<TState, TEvent>): Promise<CanonicalEvent[]>;
|
|
49
|
+
/** Runtime validates and commits each plugin output before completing that plugin. */
|
|
50
|
+
publishEvent(
|
|
51
|
+
pluginId: string,
|
|
52
|
+
epoch: RuntimeEpoch<TState, TEvent>,
|
|
53
|
+
proposal: RuntimeEventProposal,
|
|
54
|
+
proposalIndex: number,
|
|
55
|
+
): Promise<CommitEventResult>;
|
|
56
|
+
listEvents(request: {
|
|
57
|
+
scope: RuntimeScope;
|
|
58
|
+
afterCommitSeq: number;
|
|
59
|
+
maxCommitSeq: number;
|
|
60
|
+
epochSeq?: number;
|
|
61
|
+
maxEpochSeq?: number;
|
|
62
|
+
types?: readonly string[];
|
|
63
|
+
}): CanonicalEvent[];
|
|
64
|
+
highWaterCommitSeq(scope: RuntimeScope): number;
|
|
65
|
+
currentSegment?: RuntimeEpochPluginContext<TState>['currentSegment'];
|
|
66
|
+
capabilitiesFor?(
|
|
67
|
+
plugin: RuntimeEpochPlugin<TState, TEvent>,
|
|
68
|
+
scope: RuntimeScope,
|
|
69
|
+
signal: AbortSignal,
|
|
70
|
+
epochSeq: number,
|
|
71
|
+
): RuntimePluginCapabilityAccess;
|
|
72
|
+
onEpochClosed?(
|
|
73
|
+
work: RuntimeEpochWork<TState, TEvent>,
|
|
74
|
+
result: RuntimeEpochExecutionResult,
|
|
75
|
+
): void | Promise<void>;
|
|
76
|
+
onFatalError?(error: unknown, pluginId: string, scope: RuntimeScope): void;
|
|
77
|
+
onDiagnostic?(
|
|
78
|
+
name: string,
|
|
79
|
+
attributes: Record<string, unknown>,
|
|
80
|
+
scope: RuntimeScope,
|
|
81
|
+
severity?: RuntimeDiagnosticSeverity,
|
|
82
|
+
): void;
|
|
83
|
+
pluginTimeoutMs?: number;
|
|
84
|
+
maxCatchUpEpochs?: number;
|
|
85
|
+
/** Full-diagnostic timing summaries are emitted at this cadence and on scope stop. */
|
|
86
|
+
diagnosticTimingWindowMs?: number;
|
|
87
|
+
/** Monotonic-enough wall clock seam for deterministic scheduler diagnostics. */
|
|
88
|
+
nowMs?: () => number;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
interface PendingWork<TState, TEvent> {
|
|
92
|
+
work: RuntimeEpochWork<TState, TEvent>;
|
|
93
|
+
queuedAtMs: number;
|
|
94
|
+
resolve: (result: RuntimeEpochExecutionResult) => void;
|
|
95
|
+
reject: (error: unknown) => void;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
interface InvocationResult {
|
|
99
|
+
plugin: RuntimeEpochPlugin<any, any>;
|
|
100
|
+
invocationId: string;
|
|
101
|
+
startedAt: number;
|
|
102
|
+
durationMs: number;
|
|
103
|
+
/** Resolves only after the underlying update Promise has actually settled. */
|
|
104
|
+
settlement: Promise<void>;
|
|
105
|
+
attempt: number;
|
|
106
|
+
result?: RuntimeEpochPluginResult;
|
|
107
|
+
error?: unknown;
|
|
108
|
+
cursorBefore: number;
|
|
109
|
+
checkpointBefore?: unknown;
|
|
110
|
+
maxEventWatermark: number;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
interface ActiveInvocation {
|
|
114
|
+
pluginId: string;
|
|
115
|
+
epochSeq: number;
|
|
116
|
+
controller: AbortController;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
interface BufferedInvocation<TState, TEvent> {
|
|
120
|
+
invocation: InvocationResult;
|
|
121
|
+
work: RuntimeEpochWork<TState, TEvent>;
|
|
122
|
+
hadBacklog: boolean;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
type RuntimeLagBand = 'healthy' | 'degraded' | 'critical';
|
|
126
|
+
|
|
127
|
+
interface PluginTimingWindow {
|
|
128
|
+
readonly scope: RuntimeScope;
|
|
129
|
+
readonly pluginId: string;
|
|
130
|
+
readonly startedAtMs: number;
|
|
131
|
+
fromEpochSeq: number;
|
|
132
|
+
throughEpochSeq: number;
|
|
133
|
+
readonly durationsMs: number[];
|
|
134
|
+
processedCount: number;
|
|
135
|
+
noopCount: number;
|
|
136
|
+
failedCount: number;
|
|
137
|
+
coalescedCount: number;
|
|
138
|
+
slowCount: number;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
interface LagSnapshot {
|
|
142
|
+
readonly band: RuntimeLagBand;
|
|
143
|
+
readonly latestEpochSeq: number;
|
|
144
|
+
readonly maxLagEpochCount: number;
|
|
145
|
+
readonly lagCountCapped: boolean;
|
|
146
|
+
readonly pluginProgress: Array<{
|
|
147
|
+
plugin_id: string;
|
|
148
|
+
completed_through_epoch_seq: number;
|
|
149
|
+
ready_through_epoch_seq: number;
|
|
150
|
+
lag_epoch_count: number;
|
|
151
|
+
lag_count_capped: boolean;
|
|
152
|
+
}>;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
const DEFAULT_PLUGIN_TIMEOUT_MS = 1_000;
|
|
156
|
+
const DEFAULT_MAX_CATCH_UP_EPOCHS = 10;
|
|
157
|
+
const MAX_PLUGIN_IN_FLIGHT = 10;
|
|
158
|
+
const DEFAULT_RETRY_ATTEMPTS = 3;
|
|
159
|
+
const DEFAULT_DIAGNOSTIC_TIMING_WINDOW_MS = 10_000;
|
|
160
|
+
const DEFAULT_SLOW_PLUGIN_MS = 250;
|
|
161
|
+
const DEFAULT_SLOW_STRATEGY_PLUGIN_MS = 1_000;
|
|
162
|
+
const DEFAULT_SLOW_EPOCH_MS = 1_000;
|
|
163
|
+
const DEGRADED_LAG_EPOCHS = 3;
|
|
164
|
+
const CRITICAL_LAG_EPOCHS = 10;
|
|
165
|
+
|
|
166
|
+
function rounded(value: number): number {
|
|
167
|
+
return Math.round(value * 1_000) / 1_000;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function percentile(sorted: readonly number[], fraction: number): number {
|
|
171
|
+
if (sorted.length === 0) return 0;
|
|
172
|
+
return sorted[Math.max(0, Math.ceil(sorted.length * fraction) - 1)]!;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
function lagBand(lagEpochCount: number): RuntimeLagBand {
|
|
176
|
+
if (lagEpochCount >= CRITICAL_LAG_EPOCHS) return 'critical';
|
|
177
|
+
if (lagEpochCount >= DEGRADED_LAG_EPOCHS) return 'degraded';
|
|
178
|
+
return 'healthy';
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function slowPluginThresholdMs(pluginId: string): number {
|
|
182
|
+
return /(?:^|\.)strategy$/.test(pluginId)
|
|
183
|
+
? DEFAULT_SLOW_STRATEGY_PLUGIN_MS
|
|
184
|
+
: DEFAULT_SLOW_PLUGIN_MS;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function forbidsCoalescing<TState, TEvent>(
|
|
188
|
+
work: RuntimeEpochWork<TState, TEvent>,
|
|
189
|
+
): boolean {
|
|
190
|
+
return work.epoch.coalescing === 'forbidden';
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function unavailableCapabilities(pluginId: string): RuntimePluginCapabilityAccess {
|
|
194
|
+
const unavailable = (): never => {
|
|
195
|
+
throw new Error(`Runtime capability access is unavailable for Plugin ${pluginId}.`);
|
|
196
|
+
};
|
|
197
|
+
return {
|
|
198
|
+
provideObservation: unavailable,
|
|
199
|
+
provideAction: unavailable,
|
|
200
|
+
queryObservation: unavailable,
|
|
201
|
+
performAction: unavailable,
|
|
202
|
+
releaseActionCaller: unavailable,
|
|
203
|
+
};
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function computationCapabilities(
|
|
207
|
+
pluginId: string,
|
|
208
|
+
capabilities: RuntimePluginCapabilityAccess,
|
|
209
|
+
): RuntimePluginCapabilityAccess {
|
|
210
|
+
const registrationUnavailable = (): never => {
|
|
211
|
+
throw new Error(
|
|
212
|
+
`Runtime Epoch Plugin ${pluginId} cannot register capabilities from a parallel update.`,
|
|
213
|
+
);
|
|
214
|
+
};
|
|
215
|
+
return {
|
|
216
|
+
provideObservation: registrationUnavailable,
|
|
217
|
+
provideAction: registrationUnavailable,
|
|
218
|
+
queryObservation: capabilities.queryObservation.bind(capabilities),
|
|
219
|
+
performAction: async () => {
|
|
220
|
+
throw new Error(
|
|
221
|
+
`Runtime Epoch Plugin ${pluginId} cannot perform Action from a parallel update; return a proposal and act from ordered commit.`,
|
|
222
|
+
);
|
|
223
|
+
},
|
|
224
|
+
releaseActionCaller: () => {
|
|
225
|
+
throw new Error(
|
|
226
|
+
`Runtime Epoch Plugin ${pluginId} cannot release an Action caller from a parallel update; release it from ordered commit.`,
|
|
227
|
+
);
|
|
228
|
+
},
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
function assertNonEmpty(value: string, field: string): void {
|
|
233
|
+
if (typeof value !== 'string' || !value.trim()) throw new TypeError(`${field} must not be empty.`);
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function normalizedFailurePolicy(plugin: RuntimeEpochPlugin<any, any>): RuntimePluginFailurePolicy {
|
|
237
|
+
const configured = plugin.failurePolicy;
|
|
238
|
+
const policy = typeof configured === 'string' ? { mode: configured } : configured;
|
|
239
|
+
const normalized: RuntimePluginFailurePolicy = policy ?? { mode: 'failed_completion' };
|
|
240
|
+
if (!['failed_completion', 'retry', 'pause', 'terminate'].includes(normalized.mode)) {
|
|
241
|
+
throw new TypeError(`Runtime Epoch Plugin ${plugin.id} has invalid failurePolicy mode.`);
|
|
242
|
+
}
|
|
243
|
+
if (
|
|
244
|
+
normalized.maxAttempts !== undefined
|
|
245
|
+
&& (!Number.isInteger(normalized.maxAttempts) || normalized.maxAttempts <= 0)
|
|
246
|
+
) {
|
|
247
|
+
throw new TypeError(`Runtime Epoch Plugin ${plugin.id} failurePolicy.maxAttempts must be positive.`);
|
|
248
|
+
}
|
|
249
|
+
return normalized.mode === 'retry'
|
|
250
|
+
? { mode: 'retry', maxAttempts: normalized.maxAttempts ?? DEFAULT_RETRY_ATTEMPTS }
|
|
251
|
+
: { mode: normalized.mode };
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
function normalizedMaxInFlight(plugin: RuntimeEpochPlugin<any, any>): number {
|
|
255
|
+
const maxInFlight = plugin.maxInFlight ?? 1;
|
|
256
|
+
if (!Number.isInteger(maxInFlight) || maxInFlight <= 0 || maxInFlight > MAX_PLUGIN_IN_FLIGHT) {
|
|
257
|
+
throw new TypeError(
|
|
258
|
+
`Runtime Epoch Plugin ${plugin.id} maxInFlight must be an integer between 1 and ${MAX_PLUGIN_IN_FLIGHT}.`,
|
|
259
|
+
);
|
|
260
|
+
}
|
|
261
|
+
return maxInFlight;
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function pluginLayers<TState, TEvent>(
|
|
265
|
+
plugins: readonly RuntimeEpochPlugin<TState, TEvent>[],
|
|
266
|
+
): RuntimeEpochPlugin<TState, TEvent>[][] {
|
|
267
|
+
const byId = new Map<string, RuntimeEpochPlugin<TState, TEvent>>();
|
|
268
|
+
const stateOwners = new Map<string, string>();
|
|
269
|
+
const capabilityOwners = new Map<string, string>();
|
|
270
|
+
for (const plugin of plugins) {
|
|
271
|
+
if (plugin.kind !== 'epoch') throw new TypeError(`Runtime Epoch Plugin ${plugin.id} has invalid kind.`);
|
|
272
|
+
assertNonEmpty(plugin.id, 'Runtime Epoch Plugin id');
|
|
273
|
+
assertNonEmpty(plugin.version, `Runtime Epoch Plugin ${plugin.id} version`);
|
|
274
|
+
if (byId.has(plugin.id)) throw new Error(`Duplicate Runtime Epoch Plugin id: ${plugin.id}`);
|
|
275
|
+
byId.set(plugin.id, plugin);
|
|
276
|
+
normalizedFailurePolicy(plugin);
|
|
277
|
+
normalizedMaxInFlight(plugin);
|
|
278
|
+
for (const topic of plugin.produces?.states ?? []) {
|
|
279
|
+
assertNonEmpty(topic, `Runtime Epoch Plugin ${plugin.id} State output`);
|
|
280
|
+
const owner = stateOwners.get(topic);
|
|
281
|
+
if (owner) throw new Error(`Runtime State topic ${topic} is owned by both ${owner} and ${plugin.id}`);
|
|
282
|
+
stateOwners.set(topic, plugin.id);
|
|
283
|
+
}
|
|
284
|
+
for (const capability of plugin.capabilities?.provides ?? []) {
|
|
285
|
+
assertNonEmpty(capability, `Runtime Epoch Plugin ${plugin.id} capability`);
|
|
286
|
+
const owner = capabilityOwners.get(capability);
|
|
287
|
+
if (owner) throw new Error(`Runtime capability ${capability} is provided by both ${owner} and ${plugin.id}`);
|
|
288
|
+
capabilityOwners.set(capability, plugin.id);
|
|
289
|
+
}
|
|
290
|
+
for (const capability of plugin.capabilities?.uses ?? []) {
|
|
291
|
+
assertNonEmpty(capability, `Runtime Epoch Plugin ${plugin.id} capability dependency`);
|
|
292
|
+
}
|
|
293
|
+
if (plugin.timeoutMs !== undefined && (!Number.isInteger(plugin.timeoutMs) || plugin.timeoutMs <= 0)) {
|
|
294
|
+
throw new TypeError(`Runtime Epoch Plugin ${plugin.id} timeoutMs must be a positive integer.`);
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
for (const plugin of plugins) {
|
|
298
|
+
for (const dependency of plugin.after ?? []) {
|
|
299
|
+
if (!byId.has(dependency)) {
|
|
300
|
+
throw new Error(`Runtime Epoch Plugin ${plugin.id} depends on missing ${dependency}`);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
const remaining = new Map(byId);
|
|
306
|
+
const completed = new Set<string>();
|
|
307
|
+
const layers: RuntimeEpochPlugin<TState, TEvent>[][] = [];
|
|
308
|
+
while (remaining.size > 0) {
|
|
309
|
+
const layer = [...remaining.values()]
|
|
310
|
+
.filter((plugin) => (plugin.after ?? []).every((id) => completed.has(id)))
|
|
311
|
+
.sort((a, b) => a.id.localeCompare(b.id));
|
|
312
|
+
if (layer.length === 0) {
|
|
313
|
+
throw new Error(`Runtime Epoch Plugin dependency cycle: ${[...remaining.keys()].sort().join(', ')}`);
|
|
314
|
+
}
|
|
315
|
+
layers.push(layer);
|
|
316
|
+
for (const plugin of layer) {
|
|
317
|
+
remaining.delete(plugin.id);
|
|
318
|
+
completed.add(plugin.id);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
return layers;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function validateResult(plugin: RuntimeEpochPlugin<any, any>, result: RuntimeEpochPluginResult): void {
|
|
325
|
+
if (result.outcome !== 'processed' && result.outcome !== 'noop') {
|
|
326
|
+
throw new TypeError(`Runtime Epoch Plugin ${plugin.id} returned an invalid outcome.`);
|
|
327
|
+
}
|
|
328
|
+
const stateOutputs = new Set(plugin.produces?.states ?? []);
|
|
329
|
+
for (const state of result.states ?? []) {
|
|
330
|
+
if (!stateOutputs.has(state.topic)) {
|
|
331
|
+
throw new Error(`Runtime Epoch Plugin ${plugin.id} did not declare State output ${state.topic}.`);
|
|
332
|
+
}
|
|
333
|
+
}
|
|
334
|
+
const eventOutputs = new Set(plugin.produces?.events ?? []);
|
|
335
|
+
for (const event of result.events ?? []) {
|
|
336
|
+
if (!eventOutputs.has(event.type)) {
|
|
337
|
+
throw new Error(`Runtime Epoch Plugin ${plugin.id} did not declare Event output ${event.type}.`);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
if (result.proposal !== undefined) {
|
|
341
|
+
throw new Error(`Runtime Epoch Plugin ${plugin.id} commit output must not contain a proposal.`);
|
|
342
|
+
}
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function validateComputationResult(
|
|
346
|
+
plugin: RuntimeEpochPlugin<any, any>,
|
|
347
|
+
result: RuntimeEpochPluginResult,
|
|
348
|
+
): void {
|
|
349
|
+
if (result.outcome !== 'processed' && result.outcome !== 'noop') {
|
|
350
|
+
throw new TypeError(`Runtime Epoch Plugin ${plugin.id} returned an invalid outcome.`);
|
|
351
|
+
}
|
|
352
|
+
if (
|
|
353
|
+
result.states !== undefined
|
|
354
|
+
|| result.events !== undefined
|
|
355
|
+
|| result.checkpoint !== undefined
|
|
356
|
+
|| result.consumeEventsThroughCommitSeq !== undefined
|
|
357
|
+
) {
|
|
358
|
+
throw new Error(
|
|
359
|
+
`Runtime Epoch Plugin ${plugin.id} update must return only outcome, reason and proposal when commit is declared.`,
|
|
360
|
+
);
|
|
361
|
+
}
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
function validateParallelFinalResult(
|
|
365
|
+
plugin: RuntimeEpochPlugin<any, any>,
|
|
366
|
+
result: RuntimeEpochPluginResult,
|
|
367
|
+
): void {
|
|
368
|
+
validateResult(plugin, result);
|
|
369
|
+
if (result.checkpoint !== undefined || result.consumeEventsThroughCommitSeq !== undefined) {
|
|
370
|
+
throw new Error(
|
|
371
|
+
`Runtime Epoch Plugin ${plugin.id} with maxInFlight > 1 must use commit for checkpoint or Event cursor output.`,
|
|
372
|
+
);
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
export class RuntimeEpochPluginTimeoutError extends Error {
|
|
377
|
+
constructor(readonly pluginId: string, readonly timeoutMs: number) {
|
|
378
|
+
super(`Runtime Epoch Plugin "${pluginId}" exceeded ${timeoutMs}ms.`);
|
|
379
|
+
this.name = 'RuntimeEpochPluginTimeoutError';
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
export class RuntimeEpochPluginSupersededError extends Error {
|
|
384
|
+
constructor(
|
|
385
|
+
readonly pluginId: string,
|
|
386
|
+
readonly epochSeq: number,
|
|
387
|
+
readonly newerEpochSeq: number,
|
|
388
|
+
readonly reasonCode: 'newer_epoch_available' | 'catch_up_limit' = 'newer_epoch_available',
|
|
389
|
+
) {
|
|
390
|
+
super(`Runtime Epoch Plugin "${pluginId}" epoch ${epochSeq} was superseded by epoch ${newerEpochSeq}.`);
|
|
391
|
+
this.name = 'RuntimeEpochPluginSupersededError';
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
export class RuntimeEpochPluginFatalError extends Error {
|
|
396
|
+
constructor(readonly pluginId: string, readonly cause: unknown) {
|
|
397
|
+
super(`Runtime Epoch Plugin "${pluginId}" terminated the Runtime: ${cause instanceof Error ? cause.message : String(cause)}`);
|
|
398
|
+
this.name = 'RuntimeEpochPluginFatalError';
|
|
399
|
+
}
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
function pluginDiagnosticErrorCode(error: unknown, fallback: string): string {
|
|
403
|
+
const code = error && typeof error === 'object' && typeof (error as any).code === 'string'
|
|
404
|
+
? (error as any).code.trim()
|
|
405
|
+
: '';
|
|
406
|
+
if (/^[A-Za-z][A-Za-z0-9_.-]{0,119}$/.test(code)) return code;
|
|
407
|
+
if (error instanceof Error && error.name !== 'Error') {
|
|
408
|
+
const name = error.name.trim();
|
|
409
|
+
if (/^[A-Za-z][A-Za-z0-9_.-]{0,119}$/.test(name)) return name;
|
|
410
|
+
}
|
|
411
|
+
return fallback;
|
|
412
|
+
}
|
|
413
|
+
|
|
414
|
+
/**
|
|
415
|
+
* Advances each plugin on its own durable cursor. Dependencies gate only the
|
|
416
|
+
* affected plugin, so an unrelated slow branch cannot stall the whole graph.
|
|
417
|
+
*/
|
|
418
|
+
export class RuntimePluginScheduler<
|
|
419
|
+
TState = Record<string, unknown>,
|
|
420
|
+
TEvent = Record<string, unknown>,
|
|
421
|
+
> {
|
|
422
|
+
private readonly layers: RuntimeEpochPlugin<TState, TEvent>[][];
|
|
423
|
+
private readonly plugins: RuntimeEpochPlugin<TState, TEvent>[];
|
|
424
|
+
private readonly pluginOrder = new Map<string, number>();
|
|
425
|
+
private readonly pending = new Map<number, PendingWork<TState, TEvent>>();
|
|
426
|
+
private readonly inputJournal: RuntimeInputJournal<TState, TEvent>;
|
|
427
|
+
private readonly pluginStore: RuntimePluginStore;
|
|
428
|
+
private readonly stateHistory: StateFrameHistoryReader<TState>;
|
|
429
|
+
private readonly commitInputEvents: RuntimePluginSchedulerOptions<TState, TEvent>['commitInputEvents'];
|
|
430
|
+
private readonly publishEvent: RuntimePluginSchedulerOptions<TState, TEvent>['publishEvent'];
|
|
431
|
+
private readonly listEvents: RuntimePluginSchedulerOptions<TState, TEvent>['listEvents'];
|
|
432
|
+
private readonly highWaterCommitSeq: RuntimePluginSchedulerOptions<TState, TEvent>['highWaterCommitSeq'];
|
|
433
|
+
private readonly currentSegment: RuntimeEpochPluginContext<TState>['currentSegment'];
|
|
434
|
+
private readonly capabilitiesFor?: RuntimePluginSchedulerOptions<TState, TEvent>['capabilitiesFor'];
|
|
435
|
+
private readonly onEpochClosed?: RuntimePluginSchedulerOptions<TState, TEvent>['onEpochClosed'];
|
|
436
|
+
private readonly onFatalError?: RuntimePluginSchedulerOptions<TState, TEvent>['onFatalError'];
|
|
437
|
+
private readonly onDiagnostic?: RuntimePluginSchedulerOptions<TState, TEvent>['onDiagnostic'];
|
|
438
|
+
private readonly pluginTimeoutMs: number;
|
|
439
|
+
private readonly maxCatchUpEpochs: number;
|
|
440
|
+
private readonly diagnosticTimingWindowMs: number;
|
|
441
|
+
private readonly nowMs: () => number;
|
|
442
|
+
private readonly activeInvocations = new Map<string, ActiveInvocation>();
|
|
443
|
+
private readonly bufferedInvocations = new Map<string, Map<number, BufferedInvocation<TState, TEvent>>>();
|
|
444
|
+
private readonly activeCommits = new Map<string, AbortController>();
|
|
445
|
+
private readonly inputEventCommits = new Map<number, Promise<void>>();
|
|
446
|
+
private inputEventCommitTail: Promise<void> = Promise.resolve();
|
|
447
|
+
private readonly catchUpCounts = new Map<string, number>();
|
|
448
|
+
private readonly pluginTimingWindows = new Map<string, PluginTimingWindow>();
|
|
449
|
+
private readonly lagBands = new Map<string, RuntimeLagBand>();
|
|
450
|
+
private readonly pausedPlugins = new Set<string>();
|
|
451
|
+
private activeScope: RuntimeScope | null = null;
|
|
452
|
+
private pumping = false;
|
|
453
|
+
private pumpRequested = false;
|
|
454
|
+
private closing = false;
|
|
455
|
+
private stopped = false;
|
|
456
|
+
private fatalError: unknown;
|
|
457
|
+
private lastWork: RuntimeEpochWork<TState, TEvent> | null = null;
|
|
458
|
+
private idleWaiters: Array<() => void> = [];
|
|
459
|
+
|
|
460
|
+
constructor(options: RuntimePluginSchedulerOptions<TState, TEvent>) {
|
|
461
|
+
this.layers = pluginLayers(options.plugins ?? []);
|
|
462
|
+
this.plugins = this.layers.flat();
|
|
463
|
+
this.plugins.forEach((plugin, index) => this.pluginOrder.set(plugin.id, index));
|
|
464
|
+
this.inputJournal = options.inputJournal;
|
|
465
|
+
this.pluginStore = options.pluginStore;
|
|
466
|
+
this.stateHistory = options.stateHistory;
|
|
467
|
+
this.commitInputEvents = options.commitInputEvents;
|
|
468
|
+
this.publishEvent = options.publishEvent;
|
|
469
|
+
this.listEvents = options.listEvents;
|
|
470
|
+
this.highWaterCommitSeq = options.highWaterCommitSeq;
|
|
471
|
+
this.currentSegment = options.currentSegment ?? (() => ({ kind: 'unknown' }));
|
|
472
|
+
this.capabilitiesFor = options.capabilitiesFor;
|
|
473
|
+
this.onEpochClosed = options.onEpochClosed;
|
|
474
|
+
this.onFatalError = options.onFatalError;
|
|
475
|
+
this.onDiagnostic = options.onDiagnostic;
|
|
476
|
+
this.pluginTimeoutMs = options.pluginTimeoutMs ?? DEFAULT_PLUGIN_TIMEOUT_MS;
|
|
477
|
+
this.maxCatchUpEpochs = options.maxCatchUpEpochs ?? DEFAULT_MAX_CATCH_UP_EPOCHS;
|
|
478
|
+
this.diagnosticTimingWindowMs = options.diagnosticTimingWindowMs
|
|
479
|
+
?? DEFAULT_DIAGNOSTIC_TIMING_WINDOW_MS;
|
|
480
|
+
this.nowMs = options.nowMs ?? Date.now;
|
|
481
|
+
if (!Number.isInteger(this.pluginTimeoutMs) || this.pluginTimeoutMs <= 0) {
|
|
482
|
+
throw new TypeError('pluginTimeoutMs must be a positive integer.');
|
|
483
|
+
}
|
|
484
|
+
if (
|
|
485
|
+
!Number.isInteger(this.maxCatchUpEpochs)
|
|
486
|
+
|| this.maxCatchUpEpochs <= 0
|
|
487
|
+
|| this.maxCatchUpEpochs > MAX_PLUGIN_IN_FLIGHT
|
|
488
|
+
) {
|
|
489
|
+
throw new TypeError(`maxCatchUpEpochs must be an integer between 1 and ${MAX_PLUGIN_IN_FLIGHT}.`);
|
|
490
|
+
}
|
|
491
|
+
if (!Number.isInteger(this.diagnosticTimingWindowMs) || this.diagnosticTimingWindowMs <= 0) {
|
|
492
|
+
throw new TypeError('diagnosticTimingWindowMs must be a positive integer.');
|
|
493
|
+
}
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
descriptors(): RuntimeEpochPluginDescriptor[] {
|
|
497
|
+
return this.plugins.map((plugin) => ({
|
|
498
|
+
kind: 'epoch',
|
|
499
|
+
id: plugin.id,
|
|
500
|
+
version: plugin.version,
|
|
501
|
+
after: [...(plugin.after ?? [])],
|
|
502
|
+
catchUp: plugin.catchUp ?? 'every_epoch',
|
|
503
|
+
maxInFlight: normalizedMaxInFlight(plugin),
|
|
504
|
+
consumes: cloneCanonical(plugin.consumes ?? {}),
|
|
505
|
+
produces: cloneCanonical(plugin.produces ?? {}),
|
|
506
|
+
capabilities: cloneCanonical(plugin.capabilities ?? {}),
|
|
507
|
+
failurePolicy: cloneCanonical(normalizedFailurePolicy(plugin)),
|
|
508
|
+
...(plugin.timeoutMs === undefined ? {} : { timeoutMs: plugin.timeoutMs }),
|
|
509
|
+
}));
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
async activateScope(scope: RuntimeScope): Promise<void> {
|
|
513
|
+
if (this.activeScope && runtimeScopeKey(this.activeScope) === runtimeScopeKey(scope)) return;
|
|
514
|
+
if (this.activeInvocations.size > 0 || this.activeCommits.size > 0 || this.bufferedInvocationCount() > 0) {
|
|
515
|
+
throw new Error('Cannot switch Runtime plugin scope while invocations are active.');
|
|
516
|
+
}
|
|
517
|
+
if (this.activeScope) await this.stopScope('segment_ending');
|
|
518
|
+
this.activeScope = cloneCanonical(scope);
|
|
519
|
+
this.pausedPlugins.clear();
|
|
520
|
+
this.catchUpCounts.clear();
|
|
521
|
+
for (const layer of this.layers) {
|
|
522
|
+
await Promise.all(layer.map(async (plugin) => {
|
|
523
|
+
const startController = new AbortController();
|
|
524
|
+
await this.withDeadline(plugin, startController, () => plugin.start?.(
|
|
525
|
+
this.context(plugin, scope, startController.signal, 0),
|
|
526
|
+
));
|
|
527
|
+
const recoverController = new AbortController();
|
|
528
|
+
await this.withDeadline(plugin, recoverController, () => plugin.recover?.(
|
|
529
|
+
this.context(
|
|
530
|
+
plugin,
|
|
531
|
+
scope,
|
|
532
|
+
recoverController.signal,
|
|
533
|
+
this.pluginStore.pluginProgress(plugin.id, scope).completedThroughEpochSeq,
|
|
534
|
+
),
|
|
535
|
+
));
|
|
536
|
+
}));
|
|
537
|
+
}
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
enqueue(work: RuntimeEpochWork<TState, TEvent>): Promise<RuntimeEpochExecutionResult> {
|
|
541
|
+
if (this.stopped || this.closing || this.fatalError) {
|
|
542
|
+
return Promise.reject(this.fatalError ?? new Error('Runtime Epoch Plugin Host is stopped.'));
|
|
543
|
+
}
|
|
544
|
+
if (this.pending.has(work.epoch.epochSeq)) {
|
|
545
|
+
return Promise.reject(new Error(`Runtime epoch ${work.epoch.epochSeq} is already queued.`));
|
|
546
|
+
}
|
|
547
|
+
this.ensureRecoveredRecords(work);
|
|
548
|
+
const queuedAtMs = this.nowMs();
|
|
549
|
+
const completion = new Promise<RuntimeEpochExecutionResult>((resolve, reject) => {
|
|
550
|
+
this.pending.set(work.epoch.epochSeq, {
|
|
551
|
+
work: cloneCanonical(work),
|
|
552
|
+
queuedAtMs,
|
|
553
|
+
resolve,
|
|
554
|
+
reject,
|
|
555
|
+
});
|
|
556
|
+
});
|
|
557
|
+
this.reportLagTransition(work.epoch.scope, work.epoch.epochSeq);
|
|
558
|
+
this.requestPump();
|
|
559
|
+
return completion;
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
async flush(reason: RuntimeEpochFlushReason): Promise<void> {
|
|
563
|
+
await this.waitForIdle();
|
|
564
|
+
const scope = this.activeScope;
|
|
565
|
+
if (!scope) return;
|
|
566
|
+
const failures: unknown[] = [];
|
|
567
|
+
for (const layer of this.layers) {
|
|
568
|
+
await Promise.all(layer.map(async (plugin) => {
|
|
569
|
+
if (!plugin.flush) return;
|
|
570
|
+
const controller = new AbortController();
|
|
571
|
+
try {
|
|
572
|
+
const result = await this.withDeadline(plugin, controller, () => plugin.flush!(
|
|
573
|
+
reason,
|
|
574
|
+
this.context(
|
|
575
|
+
plugin,
|
|
576
|
+
scope,
|
|
577
|
+
controller.signal,
|
|
578
|
+
this.pluginStore.pluginProgress(plugin.id, scope).completedThroughEpochSeq,
|
|
579
|
+
),
|
|
580
|
+
));
|
|
581
|
+
if (result !== undefined) {
|
|
582
|
+
throw new Error(`Runtime Epoch Plugin ${plugin.id} lifecycle flush must not return output.`);
|
|
583
|
+
}
|
|
584
|
+
this.onDiagnostic?.('runtime.plugin.flush_completed', {
|
|
585
|
+
plugin_id: plugin.id,
|
|
586
|
+
reason,
|
|
587
|
+
}, scope);
|
|
588
|
+
} catch (error) {
|
|
589
|
+
failures.push(error);
|
|
590
|
+
this.onDiagnostic?.('runtime.plugin.flush_failed', {
|
|
591
|
+
plugin_id: plugin.id,
|
|
592
|
+
reason,
|
|
593
|
+
error_code: pluginDiagnosticErrorCode(error, 'RUNTIME_PLUGIN_FLUSH_FAILED'),
|
|
594
|
+
}, scope, 'error');
|
|
595
|
+
}
|
|
596
|
+
}));
|
|
597
|
+
}
|
|
598
|
+
if (failures.length > 0) {
|
|
599
|
+
throw new AggregateError(failures, `${failures.length} Runtime Epoch Plugin flush operation(s) failed.`);
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
waitForIdle(): Promise<void> {
|
|
604
|
+
if (this.isIdle()) return Promise.resolve();
|
|
605
|
+
return new Promise((resolve) => this.idleWaiters.push(resolve));
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
async close(): Promise<void> {
|
|
609
|
+
if (this.stopped) return;
|
|
610
|
+
this.closing = true;
|
|
611
|
+
this.requestPump();
|
|
612
|
+
await this.waitForIdle();
|
|
613
|
+
let flushError: unknown;
|
|
614
|
+
try {
|
|
615
|
+
if (!this.fatalError) await this.flush('shutdown');
|
|
616
|
+
} catch (error) {
|
|
617
|
+
flushError = error;
|
|
618
|
+
} finally {
|
|
619
|
+
await this.stopScope('shutdown');
|
|
620
|
+
this.stopped = true;
|
|
621
|
+
}
|
|
622
|
+
if (flushError) throw flushError;
|
|
623
|
+
}
|
|
624
|
+
|
|
625
|
+
private requestPump(): void {
|
|
626
|
+
this.pumpRequested = true;
|
|
627
|
+
if (this.pumping || this.stopped) return;
|
|
628
|
+
this.pumping = true;
|
|
629
|
+
queueMicrotask(() => {
|
|
630
|
+
void this.pump().catch((error) => this.failRuntime(error, 'runtime.scheduler')).finally(() => {
|
|
631
|
+
this.pumping = false;
|
|
632
|
+
if (this.pumpRequested && !this.stopped && !this.fatalError) this.requestPump();
|
|
633
|
+
else this.resolveIdle();
|
|
634
|
+
});
|
|
635
|
+
});
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
private async pump(): Promise<void> {
|
|
639
|
+
while (!this.fatalError) {
|
|
640
|
+
this.pumpRequested = false;
|
|
641
|
+
const first = this.pendingInOrder()[0];
|
|
642
|
+
if (!first) return;
|
|
643
|
+
if (!this.activeScope || runtimeScopeKey(this.activeScope) !== runtimeScopeKey(first.work.epoch.scope)) {
|
|
644
|
+
if (this.activeInvocations.size > 0 || this.activeCommits.size > 0) return;
|
|
645
|
+
await this.activateScope(first.work.epoch.scope);
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
this.abortSupersededInvocations();
|
|
649
|
+
if (await this.closeReadyEpochs()) {
|
|
650
|
+
continue;
|
|
651
|
+
}
|
|
652
|
+
const commits = this.launchReadyCommits();
|
|
653
|
+
const launched = this.launchReadyPlugins();
|
|
654
|
+
if (commits > 0 || launched > 0) return;
|
|
655
|
+
return;
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
private launchReadyPlugins(): number {
|
|
660
|
+
const scope = this.activeScope;
|
|
661
|
+
if (!scope) return 0;
|
|
662
|
+
let launched = 0;
|
|
663
|
+
for (const plugin of this.plugins) {
|
|
664
|
+
const maxInFlight = normalizedMaxInFlight(plugin);
|
|
665
|
+
if (maxInFlight === 1 && this.scheduledInvocationCount(plugin.id) > 0) continue;
|
|
666
|
+
let candidates = this.launchCandidates(plugin, scope);
|
|
667
|
+
if (candidates.length === 0) continue;
|
|
668
|
+
if (this.pausedPlugins.has(plugin.id)) {
|
|
669
|
+
if (maxInFlight > 1) {
|
|
670
|
+
if (this.scheduledInvocationCount(plugin.id) > 0 || this.activeCommits.has(plugin.id)) continue;
|
|
671
|
+
const earliest = this.readyCandidates(plugin, scope)[0];
|
|
672
|
+
if (!earliest || this.isInvocationScheduled(plugin.id, earliest.work.epoch.epochSeq)) continue;
|
|
673
|
+
this.recordPausedCompletion(plugin, earliest.work);
|
|
674
|
+
launched += 1;
|
|
675
|
+
} else {
|
|
676
|
+
for (const pending of candidates) this.recordPausedCompletion(plugin, pending.work);
|
|
677
|
+
launched += candidates.length;
|
|
678
|
+
}
|
|
679
|
+
this.requestPump();
|
|
680
|
+
continue;
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
if (maxInFlight > 1) {
|
|
684
|
+
this.trimParallelBacklog(plugin, scope);
|
|
685
|
+
candidates = this.launchCandidates(plugin, scope);
|
|
686
|
+
const reorderCapacity = Math.min(maxInFlight, this.maxCatchUpEpochs);
|
|
687
|
+
let slots = reorderCapacity - this.scheduledInvocationCount(plugin.id);
|
|
688
|
+
for (const candidate of candidates) {
|
|
689
|
+
if (slots <= 0) break;
|
|
690
|
+
this.runPlugin(plugin, candidate.work, candidates.length > 1);
|
|
691
|
+
launched += 1;
|
|
692
|
+
slots -= 1;
|
|
693
|
+
}
|
|
694
|
+
continue;
|
|
695
|
+
}
|
|
696
|
+
|
|
697
|
+
const catchUp = plugin.catchUp ?? 'every_epoch';
|
|
698
|
+
const count = this.catchUpCounts.get(plugin.id) ?? 0;
|
|
699
|
+
const requiredIndex = candidates.findIndex((candidate) => forbidsCoalescing(candidate.work));
|
|
700
|
+
const shouldJump = requiredIndex > 0
|
|
701
|
+
|| (requiredIndex < 0 && (catchUp === 'latest_only'
|
|
702
|
+
|| (catchUp === 'every_epoch' && count >= this.maxCatchUpEpochs && candidates.length > 1)));
|
|
703
|
+
if (shouldJump && candidates.length > 1) {
|
|
704
|
+
const targetIndex = requiredIndex >= 0 ? requiredIndex : candidates.length - 1;
|
|
705
|
+
const skipped = candidates.slice(0, targetIndex);
|
|
706
|
+
const target = candidates[targetIndex];
|
|
707
|
+
this.recordCoalesced(
|
|
708
|
+
plugin,
|
|
709
|
+
skipped.map((entry) => entry.work),
|
|
710
|
+
requiredIndex >= 0
|
|
711
|
+
? 'required_epoch_boundary'
|
|
712
|
+
: catchUp === 'latest_only'
|
|
713
|
+
? 'newer_epoch_available'
|
|
714
|
+
: 'catch_up_limit',
|
|
715
|
+
);
|
|
716
|
+
candidates = [target];
|
|
717
|
+
this.catchUpCounts.set(plugin.id, 0);
|
|
718
|
+
}
|
|
719
|
+
|
|
720
|
+
const target = candidates[0];
|
|
721
|
+
const hadBacklog = candidates.length > 1 || this.readyCandidates(plugin, scope).length > 1;
|
|
722
|
+
this.runPlugin(plugin, target.work, hadBacklog);
|
|
723
|
+
launched += 1;
|
|
724
|
+
}
|
|
725
|
+
return launched;
|
|
726
|
+
}
|
|
727
|
+
|
|
728
|
+
private runPlugin(
|
|
729
|
+
plugin: RuntimeEpochPlugin<TState, TEvent>,
|
|
730
|
+
work: RuntimeEpochWork<TState, TEvent>,
|
|
731
|
+
hadBacklog: boolean,
|
|
732
|
+
): void {
|
|
733
|
+
const activeKey = this.invocationKey(plugin.id, work.epoch.epochSeq);
|
|
734
|
+
void this.invokeWithPolicy(plugin, work).then((invocation) => {
|
|
735
|
+
void invocation.settlement.then(() => {
|
|
736
|
+
this.activeInvocations.delete(activeKey);
|
|
737
|
+
this.requestPump();
|
|
738
|
+
});
|
|
739
|
+
const buffer = this.bufferFor(plugin.id);
|
|
740
|
+
if (buffer.has(work.epoch.epochSeq)) {
|
|
741
|
+
throw new Error(`Runtime Epoch Plugin ${plugin.id} epoch ${work.epoch.epochSeq} completed twice.`);
|
|
742
|
+
}
|
|
743
|
+
buffer.set(work.epoch.epochSeq, {
|
|
744
|
+
invocation,
|
|
745
|
+
work: cloneCanonical(work),
|
|
746
|
+
hadBacklog,
|
|
747
|
+
});
|
|
748
|
+
this.requestPump();
|
|
749
|
+
}).catch((error) => {
|
|
750
|
+
this.activeInvocations.delete(activeKey);
|
|
751
|
+
this.failRuntime(error, plugin.id, work.epoch.scope);
|
|
752
|
+
});
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
private launchReadyCommits(): number {
|
|
756
|
+
const scope = this.activeScope;
|
|
757
|
+
if (!scope) return 0;
|
|
758
|
+
let launched = 0;
|
|
759
|
+
for (const plugin of this.plugins) {
|
|
760
|
+
// A parallel update may finish while an earlier ordered commit is still
|
|
761
|
+
// performing effects. Apply the same catch-up window to those completed
|
|
762
|
+
// proposals before granting the next commit lease; otherwise buffered
|
|
763
|
+
// results can bypass trimParallelBacklog and replay an arbitrarily stale
|
|
764
|
+
// sequence of Actions after the head commit settles.
|
|
765
|
+
if (normalizedMaxInFlight(plugin) > 1) {
|
|
766
|
+
this.trimParallelBacklog(plugin, scope);
|
|
767
|
+
}
|
|
768
|
+
if (this.activeCommits.has(plugin.id)) continue;
|
|
769
|
+
const progress = this.pluginStore.pluginProgress(plugin.id, scope);
|
|
770
|
+
const next = this.pendingInOrder().find((pending) => (
|
|
771
|
+
runtimeScopeKey(pending.work.epoch.scope) === runtimeScopeKey(scope)
|
|
772
|
+
&& pending.work.epoch.epochSeq > progress.completedThroughEpochSeq
|
|
773
|
+
));
|
|
774
|
+
if (!next) continue;
|
|
775
|
+
const buffered = this.bufferFor(plugin.id).get(next.work.epoch.epochSeq);
|
|
776
|
+
if (!buffered) continue;
|
|
777
|
+
const controller = new AbortController();
|
|
778
|
+
this.activeCommits.set(plugin.id, controller);
|
|
779
|
+
void this.commitBufferedInvocation(buffered, controller).catch((error) => {
|
|
780
|
+
this.failRuntime(error, plugin.id, buffered.work.epoch.scope);
|
|
781
|
+
}).finally(() => {
|
|
782
|
+
this.bufferFor(plugin.id).delete(buffered.work.epoch.epochSeq);
|
|
783
|
+
this.activeCommits.delete(plugin.id);
|
|
784
|
+
this.requestPump();
|
|
785
|
+
});
|
|
786
|
+
launched += 1;
|
|
787
|
+
}
|
|
788
|
+
return launched;
|
|
789
|
+
}
|
|
790
|
+
|
|
791
|
+
private async commitBufferedInvocation(
|
|
792
|
+
buffered: BufferedInvocation<TState, TEvent>,
|
|
793
|
+
controller: AbortController,
|
|
794
|
+
): Promise<void> {
|
|
795
|
+
const { plugin } = buffered.invocation;
|
|
796
|
+
const policy = normalizedFailurePolicy(plugin);
|
|
797
|
+
if (buffered.invocation.error && policy.mode === 'terminate') {
|
|
798
|
+
throw new RuntimeEpochPluginFatalError(plugin.id, buffered.invocation.error);
|
|
799
|
+
}
|
|
800
|
+
if (buffered.invocation.error && policy.mode === 'pause') this.pausedPlugins.add(plugin.id);
|
|
801
|
+
if (this.pausedPlugins.has(plugin.id) && !buffered.invocation.error) {
|
|
802
|
+
this.recordPausedCompletion(plugin, buffered.work);
|
|
803
|
+
return;
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
const progress = this.pluginStore.pluginProgress(plugin.id, buffered.work.epoch.scope);
|
|
807
|
+
let invocation: InvocationResult = {
|
|
808
|
+
...buffered.invocation,
|
|
809
|
+
cursorBefore: progress.eventCursor,
|
|
810
|
+
...(progress.checkpoint === undefined
|
|
811
|
+
? { checkpointBefore: undefined }
|
|
812
|
+
: { checkpointBefore: cloneCanonical(progress.checkpoint) }),
|
|
813
|
+
};
|
|
814
|
+
// Decide whether a latest-only proposal is stale at the ordered-commit
|
|
815
|
+
// boundary. Once commit starts, its reducer/Action side effects and its
|
|
816
|
+
// published output must remain one atomic decision; rechecking afterwards
|
|
817
|
+
// could execute an old Action and then silently discard the matching
|
|
818
|
+
// State/Event output.
|
|
819
|
+
const latestReadyBeforeCommit = this.readyCandidates(
|
|
820
|
+
plugin,
|
|
821
|
+
buffered.work.epoch.scope,
|
|
822
|
+
).at(-1)?.work.epoch.epochSeq ?? buffered.work.epoch.epochSeq;
|
|
823
|
+
const supersededBeforeCommit = !invocation.error
|
|
824
|
+
&& !forbidsCoalescing(buffered.work)
|
|
825
|
+
&& (plugin.catchUp ?? 'every_epoch') === 'latest_only'
|
|
826
|
+
&& latestReadyBeforeCommit > buffered.work.epoch.epochSeq
|
|
827
|
+
? latestReadyBeforeCommit
|
|
828
|
+
: null;
|
|
829
|
+
if (!invocation.error && plugin.commit && supersededBeforeCommit === null) {
|
|
830
|
+
const commitStartedAt = this.nowMs();
|
|
831
|
+
const maxEventWatermark = this.inputJournal.eventWatermarkThrough(
|
|
832
|
+
buffered.work.epoch.scope,
|
|
833
|
+
buffered.work.epoch.epochSeq,
|
|
834
|
+
);
|
|
835
|
+
const input = this.pluginInput(
|
|
836
|
+
plugin,
|
|
837
|
+
buffered.work,
|
|
838
|
+
this.epochEventsFor(buffered.work),
|
|
839
|
+
this.upstreamStatesFor(buffered.work.epoch.epochSeq),
|
|
840
|
+
progress.eventCursor,
|
|
841
|
+
maxEventWatermark,
|
|
842
|
+
);
|
|
843
|
+
try {
|
|
844
|
+
const result = await this.withDeadline(
|
|
845
|
+
plugin,
|
|
846
|
+
controller,
|
|
847
|
+
() => plugin.commit!(
|
|
848
|
+
input,
|
|
849
|
+
cloneCanonical(invocation.result!),
|
|
850
|
+
this.context(plugin, buffered.work.epoch.scope, controller.signal, buffered.work.epoch.epochSeq),
|
|
851
|
+
),
|
|
852
|
+
undefined,
|
|
853
|
+
true,
|
|
854
|
+
);
|
|
855
|
+
validateResult(plugin, result);
|
|
856
|
+
invocation = {
|
|
857
|
+
...invocation,
|
|
858
|
+
result: cloneCanonical(result),
|
|
859
|
+
maxEventWatermark,
|
|
860
|
+
durationMs: invocation.durationMs + Math.max(0, this.nowMs() - commitStartedAt),
|
|
861
|
+
};
|
|
862
|
+
} catch (error) {
|
|
863
|
+
invocation = {
|
|
864
|
+
...invocation,
|
|
865
|
+
error,
|
|
866
|
+
result: undefined,
|
|
867
|
+
maxEventWatermark,
|
|
868
|
+
durationMs: invocation.durationMs + Math.max(0, this.nowMs() - commitStartedAt),
|
|
869
|
+
};
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
if (invocation.error && policy.mode === 'terminate') {
|
|
873
|
+
throw new RuntimeEpochPluginFatalError(plugin.id, invocation.error);
|
|
874
|
+
}
|
|
875
|
+
if (invocation.error && policy.mode === 'pause') this.pausedPlugins.add(plugin.id);
|
|
876
|
+
await this.commitInvocation(invocation, buffered.work, supersededBeforeCommit);
|
|
877
|
+
if (normalizedMaxInFlight(plugin) === 1 && (plugin.catchUp ?? 'every_epoch') === 'every_epoch') {
|
|
878
|
+
const backlogRemains = this.readyCandidates(plugin, buffered.work.epoch.scope).length > 0;
|
|
879
|
+
this.catchUpCounts.set(
|
|
880
|
+
plugin.id,
|
|
881
|
+
buffered.hadBacklog || backlogRemains ? (this.catchUpCounts.get(plugin.id) ?? 0) + 1 : 0,
|
|
882
|
+
);
|
|
883
|
+
}
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
private async invokeWithPolicy(
|
|
887
|
+
plugin: RuntimeEpochPlugin<TState, TEvent>,
|
|
888
|
+
work: RuntimeEpochWork<TState, TEvent>,
|
|
889
|
+
): Promise<InvocationResult> {
|
|
890
|
+
const policy = normalizedFailurePolicy(plugin);
|
|
891
|
+
const maxAttempts = policy.mode === 'retry' ? policy.maxAttempts ?? DEFAULT_RETRY_ATTEMPTS : 1;
|
|
892
|
+
let invocation!: InvocationResult;
|
|
893
|
+
for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
|
|
894
|
+
invocation = await this.invoke(plugin, work, attempt);
|
|
895
|
+
if (!invocation.error || invocation.error instanceof RuntimeEpochPluginSupersededError) return invocation;
|
|
896
|
+
if (attempt < maxAttempts) {
|
|
897
|
+
this.onDiagnostic?.('runtime.plugin.invocation_retrying', {
|
|
898
|
+
plugin_id: plugin.id,
|
|
899
|
+
epoch_seq: work.epoch.epochSeq,
|
|
900
|
+
attempt,
|
|
901
|
+
max_attempts: maxAttempts,
|
|
902
|
+
error_code: pluginDiagnosticErrorCode(
|
|
903
|
+
invocation.error,
|
|
904
|
+
'RUNTIME_PLUGIN_INVOCATION_FAILED',
|
|
905
|
+
),
|
|
906
|
+
}, work.epoch.scope, 'warn');
|
|
907
|
+
await invocation.settlement;
|
|
908
|
+
}
|
|
909
|
+
}
|
|
910
|
+
return invocation;
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
private async invoke(
|
|
914
|
+
plugin: RuntimeEpochPlugin<TState, TEvent>,
|
|
915
|
+
work: RuntimeEpochWork<TState, TEvent>,
|
|
916
|
+
attempt: number,
|
|
917
|
+
): Promise<InvocationResult> {
|
|
918
|
+
const invocationId = randomUUID();
|
|
919
|
+
const controller = new AbortController();
|
|
920
|
+
const startedAt = this.nowMs();
|
|
921
|
+
this.activeInvocations.set(this.invocationKey(plugin.id, work.epoch.epochSeq), {
|
|
922
|
+
pluginId: plugin.id,
|
|
923
|
+
epochSeq: work.epoch.epochSeq,
|
|
924
|
+
controller,
|
|
925
|
+
});
|
|
926
|
+
await this.ensureInputEventsCommitted(work);
|
|
927
|
+
const progress = this.pluginStore.pluginProgress(plugin.id, work.epoch.scope);
|
|
928
|
+
const maxEventWatermark = this.inputJournal.eventWatermarkThrough(work.epoch.scope, work.epoch.epochSeq);
|
|
929
|
+
const input = this.pluginInput(
|
|
930
|
+
plugin,
|
|
931
|
+
work,
|
|
932
|
+
this.epochEventsFor(work),
|
|
933
|
+
this.upstreamStatesFor(work.epoch.epochSeq),
|
|
934
|
+
progress.eventCursor,
|
|
935
|
+
maxEventWatermark,
|
|
936
|
+
);
|
|
937
|
+
let settlement = Promise.resolve();
|
|
938
|
+
try {
|
|
939
|
+
const result = await this.withDeadline(
|
|
940
|
+
plugin,
|
|
941
|
+
controller,
|
|
942
|
+
() => plugin.update(
|
|
943
|
+
input,
|
|
944
|
+
this.context(
|
|
945
|
+
plugin,
|
|
946
|
+
work.epoch.scope,
|
|
947
|
+
controller.signal,
|
|
948
|
+
work.epoch.epochSeq,
|
|
949
|
+
{
|
|
950
|
+
progress,
|
|
951
|
+
allowActions: normalizedMaxInFlight(plugin) === 1,
|
|
952
|
+
snapshotSegment: normalizedMaxInFlight(plugin) > 1,
|
|
953
|
+
},
|
|
954
|
+
),
|
|
955
|
+
),
|
|
956
|
+
(settlement) => {
|
|
957
|
+
this.onDiagnostic?.('runtime.plugin.stale_output_rejected', {
|
|
958
|
+
plugin_id: plugin.id,
|
|
959
|
+
invocation_id: invocationId,
|
|
960
|
+
epoch_seq: work.epoch.epochSeq,
|
|
961
|
+
settlement,
|
|
962
|
+
reason: controller.signal.reason instanceof RuntimeEpochPluginSupersededError
|
|
963
|
+
? controller.signal.reason.reasonCode
|
|
964
|
+
: 'invocation_timed_out',
|
|
965
|
+
}, work.epoch.scope, 'warn');
|
|
966
|
+
},
|
|
967
|
+
false,
|
|
968
|
+
(operationSettlement) => { settlement = operationSettlement; },
|
|
969
|
+
);
|
|
970
|
+
if (plugin.commit) validateComputationResult(plugin, result);
|
|
971
|
+
else if (normalizedMaxInFlight(plugin) > 1) validateParallelFinalResult(plugin, result);
|
|
972
|
+
else validateResult(plugin, result);
|
|
973
|
+
return {
|
|
974
|
+
plugin,
|
|
975
|
+
invocationId,
|
|
976
|
+
startedAt,
|
|
977
|
+
durationMs: Math.max(0, this.nowMs() - startedAt),
|
|
978
|
+
settlement,
|
|
979
|
+
attempt,
|
|
980
|
+
result: cloneCanonical(result),
|
|
981
|
+
cursorBefore: progress.eventCursor,
|
|
982
|
+
...(progress.checkpoint === undefined ? {} : { checkpointBefore: cloneCanonical(progress.checkpoint) }),
|
|
983
|
+
maxEventWatermark,
|
|
984
|
+
};
|
|
985
|
+
} catch (error) {
|
|
986
|
+
if (error instanceof RuntimeEpochPluginTimeoutError) {
|
|
987
|
+
this.onDiagnostic?.('runtime.plugin.invocation_cancelled', {
|
|
988
|
+
plugin_id: plugin.id,
|
|
989
|
+
invocation_id: invocationId,
|
|
990
|
+
epoch_seq: work.epoch.epochSeq,
|
|
991
|
+
reason: 'timeout',
|
|
992
|
+
timeout_ms: error.timeoutMs,
|
|
993
|
+
}, work.epoch.scope, 'warn');
|
|
994
|
+
} else if (error instanceof RuntimeEpochPluginSupersededError) {
|
|
995
|
+
this.onDiagnostic?.('runtime.plugin.invocation_cancelled', {
|
|
996
|
+
plugin_id: plugin.id,
|
|
997
|
+
invocation_id: invocationId,
|
|
998
|
+
epoch_seq: work.epoch.epochSeq,
|
|
999
|
+
newer_epoch_seq: error.newerEpochSeq,
|
|
1000
|
+
reason: error.reasonCode,
|
|
1001
|
+
}, work.epoch.scope);
|
|
1002
|
+
}
|
|
1003
|
+
return {
|
|
1004
|
+
plugin,
|
|
1005
|
+
invocationId,
|
|
1006
|
+
startedAt,
|
|
1007
|
+
durationMs: Math.max(0, this.nowMs() - startedAt),
|
|
1008
|
+
settlement,
|
|
1009
|
+
attempt,
|
|
1010
|
+
error,
|
|
1011
|
+
cursorBefore: progress.eventCursor,
|
|
1012
|
+
...(progress.checkpoint === undefined ? {} : { checkpointBefore: cloneCanonical(progress.checkpoint) }),
|
|
1013
|
+
maxEventWatermark,
|
|
1014
|
+
};
|
|
1015
|
+
}
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
private async commitInvocation(
|
|
1019
|
+
invocation: InvocationResult,
|
|
1020
|
+
work: RuntimeEpochWork<TState, TEvent>,
|
|
1021
|
+
supersededBeforeCommit: number | null = null,
|
|
1022
|
+
): Promise<void> {
|
|
1023
|
+
const { plugin } = invocation;
|
|
1024
|
+
let outcome: RuntimeEpochPluginOutcome;
|
|
1025
|
+
let reason: string | undefined;
|
|
1026
|
+
let stateRows: RuntimeEpochStateRecord[] = [];
|
|
1027
|
+
let eventCount = 0;
|
|
1028
|
+
let cursorAfter = invocation.cursorBefore;
|
|
1029
|
+
|
|
1030
|
+
if (invocation.error instanceof RuntimeEpochPluginSupersededError) {
|
|
1031
|
+
outcome = 'coalesced';
|
|
1032
|
+
reason = invocation.error.reasonCode;
|
|
1033
|
+
} else if (invocation.error) {
|
|
1034
|
+
outcome = 'failed';
|
|
1035
|
+
reason = invocation.error instanceof Error ? invocation.error.message : String(invocation.error);
|
|
1036
|
+
} else {
|
|
1037
|
+
const result = invocation.result!;
|
|
1038
|
+
const superseded = supersededBeforeCommit !== null;
|
|
1039
|
+
outcome = superseded ? 'coalesced' : result.outcome;
|
|
1040
|
+
reason = superseded ? 'newer_epoch_available_before_commit' : result.reason;
|
|
1041
|
+
if (superseded) {
|
|
1042
|
+
this.onDiagnostic?.('runtime.plugin.stale_output_rejected', {
|
|
1043
|
+
plugin_id: plugin.id,
|
|
1044
|
+
invocation_id: invocation.invocationId,
|
|
1045
|
+
epoch_seq: work.epoch.epochSeq,
|
|
1046
|
+
newer_epoch_seq: supersededBeforeCommit,
|
|
1047
|
+
reason,
|
|
1048
|
+
}, work.epoch.scope);
|
|
1049
|
+
} else {
|
|
1050
|
+
if (result.consumeEventsThroughCommitSeq !== undefined) {
|
|
1051
|
+
const requested = result.consumeEventsThroughCommitSeq;
|
|
1052
|
+
if (
|
|
1053
|
+
!Number.isInteger(requested)
|
|
1054
|
+
|| requested < invocation.cursorBefore
|
|
1055
|
+
|| requested > invocation.maxEventWatermark
|
|
1056
|
+
) {
|
|
1057
|
+
throw new Error(`Runtime Epoch Plugin ${plugin.id} returned invalid Event cursor ${requested}.`);
|
|
1058
|
+
}
|
|
1059
|
+
cursorAfter = requested;
|
|
1060
|
+
}
|
|
1061
|
+
stateRows = (result.states ?? []).map((state) => ({
|
|
1062
|
+
epochSeq: work.epoch.epochSeq,
|
|
1063
|
+
pluginId: plugin.id,
|
|
1064
|
+
topic: state.topic,
|
|
1065
|
+
value: cloneCanonical(state.value),
|
|
1066
|
+
}));
|
|
1067
|
+
for (const [proposalIndex, proposal] of (result.events ?? []).entries()) {
|
|
1068
|
+
await this.publishEvent(plugin.id, work.epoch, proposal, proposalIndex);
|
|
1069
|
+
eventCount += 1;
|
|
1070
|
+
}
|
|
1071
|
+
if (eventCount > 0) {
|
|
1072
|
+
this.inputJournal.markEventWatermark(
|
|
1073
|
+
work.epoch.epochSeq,
|
|
1074
|
+
this.highWaterCommitSeq(work.epoch.scope),
|
|
1075
|
+
);
|
|
1076
|
+
}
|
|
1077
|
+
}
|
|
1078
|
+
}
|
|
1079
|
+
|
|
1080
|
+
if (stateRows.length > 0) this.pluginStore.saveStates(stateRows);
|
|
1081
|
+
const recordedAtMs = this.nowMs();
|
|
1082
|
+
const now = new Date(recordedAtMs).toISOString();
|
|
1083
|
+
const record: RuntimeEpochPluginRecord = {
|
|
1084
|
+
epochSeq: work.epoch.epochSeq,
|
|
1085
|
+
pluginId: plugin.id,
|
|
1086
|
+
invocationId: invocation.invocationId,
|
|
1087
|
+
outcome,
|
|
1088
|
+
...(reason ? { reason } : {}),
|
|
1089
|
+
durationMs: invocation.durationMs,
|
|
1090
|
+
stateCount: stateRows.length,
|
|
1091
|
+
eventCount,
|
|
1092
|
+
eventCursorBefore: invocation.cursorBefore,
|
|
1093
|
+
eventCursorAfter: cursorAfter,
|
|
1094
|
+
recordedAt: now,
|
|
1095
|
+
};
|
|
1096
|
+
this.pluginStore.recordPlugin(record);
|
|
1097
|
+
this.pluginStore.savePluginProgress({
|
|
1098
|
+
pluginId: plugin.id,
|
|
1099
|
+
completedThroughEpochSeq: work.epoch.epochSeq,
|
|
1100
|
+
eventCursor: cursorAfter,
|
|
1101
|
+
...(
|
|
1102
|
+
invocation.result?.checkpoint === undefined || outcome === 'coalesced'
|
|
1103
|
+
? (invocation.checkpointBefore === undefined ? {} : { checkpoint: cloneCanonical(invocation.checkpointBefore) })
|
|
1104
|
+
: { checkpoint: cloneCanonical(invocation.result.checkpoint) }
|
|
1105
|
+
),
|
|
1106
|
+
updatedAt: now,
|
|
1107
|
+
}, work.epoch.scope);
|
|
1108
|
+
this.recordPluginTiming(record, work.epoch.scope, recordedAtMs);
|
|
1109
|
+
if (outcome === 'failed') {
|
|
1110
|
+
this.onDiagnostic?.('runtime.plugin.invocation_failed', {
|
|
1111
|
+
plugin_id: plugin.id,
|
|
1112
|
+
invocation_id: invocation.invocationId,
|
|
1113
|
+
epoch_seq: work.epoch.epochSeq,
|
|
1114
|
+
attempt: invocation.attempt,
|
|
1115
|
+
outcome,
|
|
1116
|
+
error_code: pluginDiagnosticErrorCode(invocation.error, 'RUNTIME_PLUGIN_INVOCATION_FAILED'),
|
|
1117
|
+
duration_ms: record.durationMs,
|
|
1118
|
+
state_count: record.stateCount,
|
|
1119
|
+
event_count: record.eventCount,
|
|
1120
|
+
event_cursor_before: record.eventCursorBefore,
|
|
1121
|
+
event_cursor_after: record.eventCursorAfter,
|
|
1122
|
+
}, work.epoch.scope, 'error');
|
|
1123
|
+
} else {
|
|
1124
|
+
const slowThresholdMs = slowPluginThresholdMs(plugin.id);
|
|
1125
|
+
if (record.durationMs >= slowThresholdMs) {
|
|
1126
|
+
this.onDiagnostic?.('runtime.plugin.slow', {
|
|
1127
|
+
plugin_id: plugin.id,
|
|
1128
|
+
invocation_id: invocation.invocationId,
|
|
1129
|
+
epoch_seq: work.epoch.epochSeq,
|
|
1130
|
+
attempt: invocation.attempt,
|
|
1131
|
+
outcome,
|
|
1132
|
+
...(reason === undefined ? {} : { reason }),
|
|
1133
|
+
duration_ms: record.durationMs,
|
|
1134
|
+
threshold_ms: slowThresholdMs,
|
|
1135
|
+
state_count: record.stateCount,
|
|
1136
|
+
event_count: record.eventCount,
|
|
1137
|
+
}, work.epoch.scope, 'warn');
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
|
|
1142
|
+
private recordCoalesced(
|
|
1143
|
+
plugin: RuntimeEpochPlugin<TState, TEvent>,
|
|
1144
|
+
works: readonly RuntimeEpochWork<TState, TEvent>[],
|
|
1145
|
+
reason: string,
|
|
1146
|
+
): void {
|
|
1147
|
+
if (works.length === 0) return;
|
|
1148
|
+
for (const work of works) {
|
|
1149
|
+
const progress = this.pluginStore.pluginProgress(plugin.id, work.epoch.scope);
|
|
1150
|
+
const recordedAtMs = this.nowMs();
|
|
1151
|
+
const recordedAt = new Date(recordedAtMs).toISOString();
|
|
1152
|
+
const record: RuntimeEpochPluginRecord = {
|
|
1153
|
+
epochSeq: work.epoch.epochSeq,
|
|
1154
|
+
pluginId: plugin.id,
|
|
1155
|
+
invocationId: randomUUID(),
|
|
1156
|
+
outcome: 'coalesced',
|
|
1157
|
+
reason,
|
|
1158
|
+
durationMs: 0,
|
|
1159
|
+
stateCount: 0,
|
|
1160
|
+
eventCount: 0,
|
|
1161
|
+
eventCursorBefore: progress.eventCursor,
|
|
1162
|
+
eventCursorAfter: progress.eventCursor,
|
|
1163
|
+
recordedAt,
|
|
1164
|
+
};
|
|
1165
|
+
this.pluginStore.recordPlugin(record);
|
|
1166
|
+
this.pluginStore.savePluginProgress({
|
|
1167
|
+
...progress,
|
|
1168
|
+
completedThroughEpochSeq: work.epoch.epochSeq,
|
|
1169
|
+
updatedAt: recordedAt,
|
|
1170
|
+
}, work.epoch.scope);
|
|
1171
|
+
this.recordPluginTiming(record, work.epoch.scope, recordedAtMs, false);
|
|
1172
|
+
}
|
|
1173
|
+
this.onDiagnostic?.('runtime.plugin.invocations_coalesced', {
|
|
1174
|
+
plugin_id: plugin.id,
|
|
1175
|
+
reason,
|
|
1176
|
+
skipped_from_epoch_seq: works[0].epoch.epochSeq,
|
|
1177
|
+
skipped_through_epoch_seq: works.at(-1)!.epoch.epochSeq,
|
|
1178
|
+
coalesced_epoch_count: works.length,
|
|
1179
|
+
}, works[0].epoch.scope);
|
|
1180
|
+
}
|
|
1181
|
+
|
|
1182
|
+
private recordPausedCompletion(
|
|
1183
|
+
plugin: RuntimeEpochPlugin<TState, TEvent>,
|
|
1184
|
+
work: RuntimeEpochWork<TState, TEvent>,
|
|
1185
|
+
): void {
|
|
1186
|
+
const progress = this.pluginStore.pluginProgress(plugin.id, work.epoch.scope);
|
|
1187
|
+
const recordedAtMs = this.nowMs();
|
|
1188
|
+
const recordedAt = new Date(recordedAtMs).toISOString();
|
|
1189
|
+
const record: RuntimeEpochPluginRecord = {
|
|
1190
|
+
epochSeq: work.epoch.epochSeq,
|
|
1191
|
+
pluginId: plugin.id,
|
|
1192
|
+
invocationId: randomUUID(),
|
|
1193
|
+
outcome: 'failed',
|
|
1194
|
+
reason: 'plugin_paused',
|
|
1195
|
+
durationMs: 0,
|
|
1196
|
+
stateCount: 0,
|
|
1197
|
+
eventCount: 0,
|
|
1198
|
+
eventCursorBefore: progress.eventCursor,
|
|
1199
|
+
eventCursorAfter: progress.eventCursor,
|
|
1200
|
+
recordedAt,
|
|
1201
|
+
};
|
|
1202
|
+
this.pluginStore.recordPlugin(record);
|
|
1203
|
+
this.pluginStore.savePluginProgress({
|
|
1204
|
+
...progress,
|
|
1205
|
+
completedThroughEpochSeq: work.epoch.epochSeq,
|
|
1206
|
+
updatedAt: recordedAt,
|
|
1207
|
+
}, work.epoch.scope);
|
|
1208
|
+
this.recordPluginTiming(record, work.epoch.scope, recordedAtMs, false);
|
|
1209
|
+
this.onDiagnostic?.('runtime.plugin.invocation_failed', {
|
|
1210
|
+
plugin_id: plugin.id,
|
|
1211
|
+
epoch_seq: work.epoch.epochSeq,
|
|
1212
|
+
outcome: 'failed',
|
|
1213
|
+
reason: 'plugin_paused',
|
|
1214
|
+
}, work.epoch.scope, 'warn');
|
|
1215
|
+
}
|
|
1216
|
+
|
|
1217
|
+
private async closeReadyEpochs(): Promise<boolean> {
|
|
1218
|
+
const scope = this.activeScope;
|
|
1219
|
+
if (!scope) return false;
|
|
1220
|
+
let progressed = false;
|
|
1221
|
+
while (true) {
|
|
1222
|
+
const pending = this.pendingInOrder()[0];
|
|
1223
|
+
if (!pending || runtimeScopeKey(pending.work.epoch.scope) !== runtimeScopeKey(scope)) break;
|
|
1224
|
+
const epochSeq = pending.work.epoch.epochSeq;
|
|
1225
|
+
await this.ensureInputEventsCommitted(pending.work);
|
|
1226
|
+
const complete = this.plugins.every((plugin) => (
|
|
1227
|
+
this.pluginStore.pluginProgress(plugin.id, scope).completedThroughEpochSeq >= epochSeq
|
|
1228
|
+
));
|
|
1229
|
+
if (!complete) break;
|
|
1230
|
+
const outcomes = this.pluginStore.pluginRecords(epochSeq)
|
|
1231
|
+
.sort((a, b) => this.orderOfId(a.pluginId) - this.orderOfId(b.pluginId));
|
|
1232
|
+
const eventWatermark = this.inputJournal.eventWatermarkThrough(scope, epochSeq);
|
|
1233
|
+
const eventCount = this.listEvents({
|
|
1234
|
+
scope,
|
|
1235
|
+
afterCommitSeq: 0,
|
|
1236
|
+
maxCommitSeq: eventWatermark,
|
|
1237
|
+
epochSeq,
|
|
1238
|
+
}).length;
|
|
1239
|
+
const closedAtMs = this.nowMs();
|
|
1240
|
+
const durationMs = Math.max(0, closedAtMs - pending.queuedAtMs);
|
|
1241
|
+
const result: RuntimeEpochExecutionResult = {
|
|
1242
|
+
epochSeq,
|
|
1243
|
+
durationMs,
|
|
1244
|
+
outcomes,
|
|
1245
|
+
stateCount: this.pluginStore.states(epochSeq).length,
|
|
1246
|
+
eventCount,
|
|
1247
|
+
eventWatermark,
|
|
1248
|
+
};
|
|
1249
|
+
this.inputJournal.markClosed(epochSeq, new Date(closedAtMs).toISOString(), durationMs);
|
|
1250
|
+
this.lastWork = cloneCanonical(pending.work);
|
|
1251
|
+
await this.onEpochClosed?.(cloneCanonical(pending.work), cloneCanonical(result));
|
|
1252
|
+
this.pending.delete(epochSeq);
|
|
1253
|
+
pending.resolve(cloneCanonical(result));
|
|
1254
|
+
if (durationMs >= DEFAULT_SLOW_EPOCH_MS) {
|
|
1255
|
+
this.onDiagnostic?.('runtime.epoch.slow', {
|
|
1256
|
+
epoch_seq: epochSeq,
|
|
1257
|
+
domain_tick: pending.work.epoch.domainTick,
|
|
1258
|
+
source_id: pending.work.epoch.sourceId,
|
|
1259
|
+
duration_ms: durationMs,
|
|
1260
|
+
threshold_ms: DEFAULT_SLOW_EPOCH_MS,
|
|
1261
|
+
plugin_count: outcomes.length,
|
|
1262
|
+
state_count: result.stateCount,
|
|
1263
|
+
event_count: result.eventCount,
|
|
1264
|
+
}, scope, 'warn');
|
|
1265
|
+
}
|
|
1266
|
+
this.reportLagTransition(scope, this.latestPendingEpochSeq(scope, epochSeq));
|
|
1267
|
+
progressed = true;
|
|
1268
|
+
}
|
|
1269
|
+
return progressed;
|
|
1270
|
+
}
|
|
1271
|
+
|
|
1272
|
+
private readyCandidates(
|
|
1273
|
+
plugin: RuntimeEpochPlugin<TState, TEvent>,
|
|
1274
|
+
scope: RuntimeScope,
|
|
1275
|
+
): PendingWork<TState, TEvent>[] {
|
|
1276
|
+
const progress = this.pluginStore.pluginProgress(plugin.id, scope);
|
|
1277
|
+
const dependencies = (plugin.after ?? []).map((id) => (
|
|
1278
|
+
this.pluginStore.pluginProgress(id, scope).completedThroughEpochSeq
|
|
1279
|
+
));
|
|
1280
|
+
const readyThrough = dependencies.length === 0
|
|
1281
|
+
? Number.MAX_SAFE_INTEGER
|
|
1282
|
+
: Math.min(...dependencies);
|
|
1283
|
+
return this.pendingInOrder().filter((pending) => (
|
|
1284
|
+
runtimeScopeKey(pending.work.epoch.scope) === runtimeScopeKey(scope)
|
|
1285
|
+
&& pending.work.epoch.epochSeq > progress.completedThroughEpochSeq
|
|
1286
|
+
&& pending.work.epoch.epochSeq <= readyThrough
|
|
1287
|
+
));
|
|
1288
|
+
}
|
|
1289
|
+
|
|
1290
|
+
private launchCandidates(
|
|
1291
|
+
plugin: RuntimeEpochPlugin<TState, TEvent>,
|
|
1292
|
+
scope: RuntimeScope,
|
|
1293
|
+
): PendingWork<TState, TEvent>[] {
|
|
1294
|
+
return this.readyCandidates(plugin, scope).filter((pending) => (
|
|
1295
|
+
!this.isInvocationScheduled(plugin.id, pending.work.epoch.epochSeq)
|
|
1296
|
+
));
|
|
1297
|
+
}
|
|
1298
|
+
|
|
1299
|
+
private trimParallelBacklog(
|
|
1300
|
+
plugin: RuntimeEpochPlugin<TState, TEvent>,
|
|
1301
|
+
scope: RuntimeScope,
|
|
1302
|
+
): void {
|
|
1303
|
+
const catchUpWindow = Math.min(
|
|
1304
|
+
normalizedMaxInFlight(plugin),
|
|
1305
|
+
this.maxCatchUpEpochs,
|
|
1306
|
+
);
|
|
1307
|
+
while (true) {
|
|
1308
|
+
const ready = this.readyCandidates(plugin, scope);
|
|
1309
|
+
const earliest = ready[0];
|
|
1310
|
+
const latest = ready.at(-1);
|
|
1311
|
+
if (
|
|
1312
|
+
!earliest
|
|
1313
|
+
|| !latest
|
|
1314
|
+
|| latest.work.epoch.epochSeq - earliest.work.epoch.epochSeq < catchUpWindow
|
|
1315
|
+
) return;
|
|
1316
|
+
if (forbidsCoalescing(earliest.work)) return;
|
|
1317
|
+
// commit() is the atomic reducer/effect boundary. Once it has started we
|
|
1318
|
+
// must let it finish; only a completed proposal that has not obtained the
|
|
1319
|
+
// commit lease may be discarded.
|
|
1320
|
+
if (this.activeCommits.has(plugin.id)) return;
|
|
1321
|
+
const buffer = this.bufferFor(plugin.id);
|
|
1322
|
+
const buffered = buffer.get(earliest.work.epoch.epochSeq);
|
|
1323
|
+
if (buffered) {
|
|
1324
|
+
// invokeWithPolicy can return before the underlying Promise settles
|
|
1325
|
+
// after cancellation/timeout. It can also carry a real failure whose
|
|
1326
|
+
// failure policy must remain observable. In either case use the normal
|
|
1327
|
+
// ordered completion path instead of silently rewriting it as catch-up.
|
|
1328
|
+
if (
|
|
1329
|
+
this.activeInvocations.has(this.invocationKey(plugin.id, earliest.work.epoch.epochSeq))
|
|
1330
|
+
|| buffered.invocation.error !== undefined
|
|
1331
|
+
) return;
|
|
1332
|
+
buffer.delete(earliest.work.epoch.epochSeq);
|
|
1333
|
+
this.recordCoalesced(plugin, [earliest.work], 'catch_up_limit');
|
|
1334
|
+
continue;
|
|
1335
|
+
}
|
|
1336
|
+
const active = this.activeInvocations.get(
|
|
1337
|
+
this.invocationKey(plugin.id, earliest.work.epoch.epochSeq),
|
|
1338
|
+
);
|
|
1339
|
+
if (active) {
|
|
1340
|
+
if (!active.controller.signal.aborted) {
|
|
1341
|
+
active.controller.abort(new RuntimeEpochPluginSupersededError(
|
|
1342
|
+
plugin.id,
|
|
1343
|
+
earliest.work.epoch.epochSeq,
|
|
1344
|
+
latest.work.epoch.epochSeq,
|
|
1345
|
+
'catch_up_limit',
|
|
1346
|
+
));
|
|
1347
|
+
}
|
|
1348
|
+
return;
|
|
1349
|
+
}
|
|
1350
|
+
this.recordCoalesced(plugin, [earliest.work], 'catch_up_limit');
|
|
1351
|
+
}
|
|
1352
|
+
}
|
|
1353
|
+
|
|
1354
|
+
private invocationKey(pluginId: string, epochSeq: number): string {
|
|
1355
|
+
return `${pluginId}\u0000${epochSeq}`;
|
|
1356
|
+
}
|
|
1357
|
+
|
|
1358
|
+
private bufferFor(pluginId: string): Map<number, BufferedInvocation<TState, TEvent>> {
|
|
1359
|
+
let buffer = this.bufferedInvocations.get(pluginId);
|
|
1360
|
+
if (!buffer) {
|
|
1361
|
+
buffer = new Map();
|
|
1362
|
+
this.bufferedInvocations.set(pluginId, buffer);
|
|
1363
|
+
}
|
|
1364
|
+
return buffer;
|
|
1365
|
+
}
|
|
1366
|
+
|
|
1367
|
+
private bufferedInvocationCount(): number {
|
|
1368
|
+
let count = 0;
|
|
1369
|
+
for (const buffer of this.bufferedInvocations.values()) count += buffer.size;
|
|
1370
|
+
return count;
|
|
1371
|
+
}
|
|
1372
|
+
|
|
1373
|
+
private scheduledInvocationCount(pluginId: string): number {
|
|
1374
|
+
const epochs = new Set(this.bufferedInvocations.get(pluginId)?.keys() ?? []);
|
|
1375
|
+
for (const invocation of this.activeInvocations.values()) {
|
|
1376
|
+
if (invocation.pluginId === pluginId) epochs.add(invocation.epochSeq);
|
|
1377
|
+
}
|
|
1378
|
+
return epochs.size;
|
|
1379
|
+
}
|
|
1380
|
+
|
|
1381
|
+
private isInvocationScheduled(pluginId: string, epochSeq: number): boolean {
|
|
1382
|
+
return this.activeInvocations.has(this.invocationKey(pluginId, epochSeq))
|
|
1383
|
+
|| (this.bufferedInvocations.get(pluginId)?.has(epochSeq) ?? false);
|
|
1384
|
+
}
|
|
1385
|
+
|
|
1386
|
+
private abortSupersededInvocations(): void {
|
|
1387
|
+
const scope = this.activeScope;
|
|
1388
|
+
if (!scope) return;
|
|
1389
|
+
for (const plugin of this.plugins) {
|
|
1390
|
+
if ((plugin.catchUp ?? 'every_epoch') !== 'latest_only') continue;
|
|
1391
|
+
for (const active of this.activeInvocations.values()) {
|
|
1392
|
+
if (active.pluginId !== plugin.id || active.controller.signal.aborted) continue;
|
|
1393
|
+
const activeWork = this.pending.get(active.epochSeq)?.work;
|
|
1394
|
+
if (activeWork && forbidsCoalescing(activeWork)) continue;
|
|
1395
|
+
const latestReady = this.readyCandidates(plugin, scope).at(-1)?.work.epoch.epochSeq;
|
|
1396
|
+
if (latestReady !== undefined && latestReady > active.epochSeq) {
|
|
1397
|
+
active.controller.abort(new RuntimeEpochPluginSupersededError(plugin.id, active.epochSeq, latestReady));
|
|
1398
|
+
}
|
|
1399
|
+
}
|
|
1400
|
+
}
|
|
1401
|
+
}
|
|
1402
|
+
|
|
1403
|
+
private epochEventsFor(work: RuntimeEpochWork<TState, TEvent>): CanonicalEvent[] {
|
|
1404
|
+
const watermark = this.inputJournal.eventWatermarkThrough(work.epoch.scope, work.epoch.epochSeq);
|
|
1405
|
+
const committedCurrentEvents = this.listEvents({
|
|
1406
|
+
scope: work.epoch.scope,
|
|
1407
|
+
afterCommitSeq: 0,
|
|
1408
|
+
maxCommitSeq: watermark,
|
|
1409
|
+
epochSeq: work.epoch.epochSeq,
|
|
1410
|
+
});
|
|
1411
|
+
const events = [
|
|
1412
|
+
...work.epochEvents,
|
|
1413
|
+
...committedCurrentEvents,
|
|
1414
|
+
];
|
|
1415
|
+
const unique = new Map(events.map((event) => [event.eventId, event]));
|
|
1416
|
+
return [...unique.values()];
|
|
1417
|
+
}
|
|
1418
|
+
|
|
1419
|
+
private upstreamStatesFor(epochSeq: number): Record<string, unknown> {
|
|
1420
|
+
return Object.fromEntries(this.pluginStore.states(epochSeq).map((row) => [row.topic, cloneCanonical(row.value)]));
|
|
1421
|
+
}
|
|
1422
|
+
|
|
1423
|
+
private pluginInput(
|
|
1424
|
+
plugin: RuntimeEpochPlugin<TState, TEvent>,
|
|
1425
|
+
work: RuntimeEpochWork<TState, TEvent>,
|
|
1426
|
+
epochEvents: readonly CanonicalEvent[],
|
|
1427
|
+
upstreamStates: Readonly<Record<string, unknown>>,
|
|
1428
|
+
eventCursor: number,
|
|
1429
|
+
maxEventWatermark: number,
|
|
1430
|
+
): RuntimeEpochPluginInput<TState, TEvent> {
|
|
1431
|
+
const subscribedTypes = plugin.consumes?.events ?? [];
|
|
1432
|
+
const allEvents = subscribedTypes.includes('*');
|
|
1433
|
+
const eventTypes = new Set(subscribedTypes);
|
|
1434
|
+
const committedPendingEvents = subscribedTypes.length === 0 ? [] : this.listEvents({
|
|
1435
|
+
scope: work.epoch.scope,
|
|
1436
|
+
afterCommitSeq: eventCursor,
|
|
1437
|
+
maxCommitSeq: maxEventWatermark,
|
|
1438
|
+
maxEpochSeq: work.epoch.epochSeq,
|
|
1439
|
+
...(allEvents ? {} : { types: subscribedTypes }),
|
|
1440
|
+
});
|
|
1441
|
+
const pendingEvents = new Map(committedPendingEvents.map((event) => [event.eventId, event]));
|
|
1442
|
+
for (const event of epochEvents) {
|
|
1443
|
+
if (
|
|
1444
|
+
event.commitSeq > eventCursor
|
|
1445
|
+
&& (allEvents || eventTypes.has(event.type))
|
|
1446
|
+
) pendingEvents.set(event.eventId, event);
|
|
1447
|
+
}
|
|
1448
|
+
const stateTopics = new Set(plugin.consumes?.states ?? []);
|
|
1449
|
+
const allStates = stateTopics.has('*');
|
|
1450
|
+
return {
|
|
1451
|
+
epoch: cloneCanonical(work.epoch),
|
|
1452
|
+
frame: cloneCanonical(work.frame),
|
|
1453
|
+
currentState: cloneCanonical(work.currentState),
|
|
1454
|
+
previousState: cloneCanonical(work.previousState),
|
|
1455
|
+
epochEvents: cloneCanonical(epochEvents.filter((event) => allEvents || eventTypes.has(event.type))),
|
|
1456
|
+
pendingEvents: cloneCanonical([...pendingEvents.values()].sort((a, b) => a.commitSeq - b.commitSeq)),
|
|
1457
|
+
upstreamStates: cloneCanonical(Object.fromEntries(
|
|
1458
|
+
Object.entries(upstreamStates).filter(([topic]) => allStates || stateTopics.has(topic)),
|
|
1459
|
+
)),
|
|
1460
|
+
};
|
|
1461
|
+
}
|
|
1462
|
+
|
|
1463
|
+
private context(
|
|
1464
|
+
plugin: RuntimeEpochPlugin<TState, TEvent>,
|
|
1465
|
+
scope: RuntimeScope,
|
|
1466
|
+
signal: AbortSignal,
|
|
1467
|
+
epochSeq: number,
|
|
1468
|
+
options: {
|
|
1469
|
+
progress?: Readonly<ReturnType<RuntimePluginStore['pluginProgress']>>;
|
|
1470
|
+
allowActions?: boolean;
|
|
1471
|
+
snapshotSegment?: boolean;
|
|
1472
|
+
} = {},
|
|
1473
|
+
): RuntimeEpochPluginContext<TState> {
|
|
1474
|
+
const progress = options.progress;
|
|
1475
|
+
const capabilities = this.capabilitiesFor?.(plugin, scope, signal, epochSeq)
|
|
1476
|
+
?? unavailableCapabilities(plugin.id);
|
|
1477
|
+
const segment = options.snapshotSegment ? cloneCanonical(this.currentSegment()) : null;
|
|
1478
|
+
return Object.freeze({
|
|
1479
|
+
scope: cloneCanonical(scope),
|
|
1480
|
+
stateHistory: this.stateHistoryThrough(scope, epochSeq),
|
|
1481
|
+
currentSegment: segment
|
|
1482
|
+
? () => cloneCanonical(segment)
|
|
1483
|
+
: this.currentSegment,
|
|
1484
|
+
checkpoint: () => cloneCanonical(
|
|
1485
|
+
progress
|
|
1486
|
+
? progress.checkpoint
|
|
1487
|
+
: this.pluginStore.pluginProgress(plugin.id, scope).checkpoint,
|
|
1488
|
+
),
|
|
1489
|
+
progress: () => cloneCanonical(progress ?? this.pluginStore.pluginProgress(plugin.id, scope)),
|
|
1490
|
+
capabilities: options.allowActions === false
|
|
1491
|
+
? computationCapabilities(plugin.id, capabilities)
|
|
1492
|
+
: capabilities,
|
|
1493
|
+
diagnostic: (
|
|
1494
|
+
name: string,
|
|
1495
|
+
attributes: Readonly<Record<string, unknown>> = {},
|
|
1496
|
+
severity: RuntimeDiagnosticSeverity = 'debug',
|
|
1497
|
+
) => {
|
|
1498
|
+
this.onDiagnostic?.(name, {
|
|
1499
|
+
plugin_id: plugin.id,
|
|
1500
|
+
epoch_seq: epochSeq,
|
|
1501
|
+
...attributes,
|
|
1502
|
+
}, scope, severity);
|
|
1503
|
+
},
|
|
1504
|
+
signal,
|
|
1505
|
+
});
|
|
1506
|
+
}
|
|
1507
|
+
|
|
1508
|
+
private async stopScope(reason: 'segment_ending' | 'shutdown'): Promise<void> {
|
|
1509
|
+
const scope = this.activeScope;
|
|
1510
|
+
if (!scope) return;
|
|
1511
|
+
for (const layer of [...this.layers].reverse()) {
|
|
1512
|
+
await Promise.all(layer.map(async (plugin) => {
|
|
1513
|
+
if (!plugin.stop) return;
|
|
1514
|
+
const controller = new AbortController();
|
|
1515
|
+
await this.withDeadline(plugin, controller, () => plugin.stop!(
|
|
1516
|
+
reason,
|
|
1517
|
+
this.context(
|
|
1518
|
+
plugin,
|
|
1519
|
+
scope,
|
|
1520
|
+
controller.signal,
|
|
1521
|
+
this.pluginStore.pluginProgress(plugin.id, scope).completedThroughEpochSeq,
|
|
1522
|
+
),
|
|
1523
|
+
)).catch((error) => {
|
|
1524
|
+
this.onDiagnostic?.('runtime.plugin.stop_failed', {
|
|
1525
|
+
plugin_id: plugin.id,
|
|
1526
|
+
reason,
|
|
1527
|
+
error_code: pluginDiagnosticErrorCode(error, 'RUNTIME_PLUGIN_STOP_FAILED'),
|
|
1528
|
+
}, scope, 'warn');
|
|
1529
|
+
});
|
|
1530
|
+
}));
|
|
1531
|
+
}
|
|
1532
|
+
this.flushPluginTimingWindows(scope, this.nowMs());
|
|
1533
|
+
this.lagBands.delete(runtimeScopeKey(scope));
|
|
1534
|
+
this.activeScope = null;
|
|
1535
|
+
}
|
|
1536
|
+
|
|
1537
|
+
private stateHistoryThrough(scope: RuntimeScope, epochSeq: number): StateFrameHistoryReader<TState> {
|
|
1538
|
+
const boundedQuery = (query: StateFrameQuery): StateFrameQuery => ({
|
|
1539
|
+
...query,
|
|
1540
|
+
scope: cloneCanonical(scope),
|
|
1541
|
+
toEpochSeq: Math.min(query.toEpochSeq ?? epochSeq, epochSeq),
|
|
1542
|
+
});
|
|
1543
|
+
return Object.freeze({
|
|
1544
|
+
queryStateFrames: (query: StateFrameQuery) => this.stateHistory.queryStateFrames(boundedQuery(query)),
|
|
1545
|
+
latestStateFrame: (_requestedScope: RuntimeScope) => this.stateHistory.queryStateFrames({
|
|
1546
|
+
scope: cloneCanonical(scope),
|
|
1547
|
+
toEpochSeq: epochSeq,
|
|
1548
|
+
order: 'desc',
|
|
1549
|
+
limit: 1,
|
|
1550
|
+
}).frames[0] ?? null,
|
|
1551
|
+
});
|
|
1552
|
+
}
|
|
1553
|
+
|
|
1554
|
+
private ensureInputEventsCommitted(work: RuntimeEpochWork<TState, TEvent>): Promise<void> {
|
|
1555
|
+
const epochSeq = work.epoch.epochSeq;
|
|
1556
|
+
if (this.inputJournal.inputEventsCommitted(epochSeq)) return Promise.resolve();
|
|
1557
|
+
const existing = this.inputEventCommits.get(epochSeq);
|
|
1558
|
+
if (existing) return existing;
|
|
1559
|
+
const committing = this.inputEventCommitTail.then(async () => {
|
|
1560
|
+
await this.commitInputEvents(cloneCanonical(work));
|
|
1561
|
+
const watermark = this.highWaterCommitSeq(work.epoch.scope);
|
|
1562
|
+
this.inputJournal.markInputEventsCommitted(epochSeq, watermark);
|
|
1563
|
+
});
|
|
1564
|
+
this.inputEventCommitTail = committing.catch(() => {});
|
|
1565
|
+
void committing.then(
|
|
1566
|
+
() => this.inputEventCommits.delete(epochSeq),
|
|
1567
|
+
() => this.inputEventCommits.delete(epochSeq),
|
|
1568
|
+
);
|
|
1569
|
+
this.inputEventCommits.set(epochSeq, committing);
|
|
1570
|
+
return committing;
|
|
1571
|
+
}
|
|
1572
|
+
|
|
1573
|
+
private ensureRecoveredRecords(work: RuntimeEpochWork<TState, TEvent>): void {
|
|
1574
|
+
const existing = new Set(this.pluginStore.pluginRecords(work.epoch.epochSeq).map((row) => row.pluginId));
|
|
1575
|
+
for (const plugin of this.plugins) {
|
|
1576
|
+
const progress = this.pluginStore.pluginProgress(plugin.id, work.epoch.scope);
|
|
1577
|
+
if (progress.completedThroughEpochSeq < work.epoch.epochSeq || existing.has(plugin.id)) continue;
|
|
1578
|
+
this.pluginStore.recordPlugin({
|
|
1579
|
+
epochSeq: work.epoch.epochSeq,
|
|
1580
|
+
pluginId: plugin.id,
|
|
1581
|
+
invocationId: randomUUID(),
|
|
1582
|
+
outcome: 'noop',
|
|
1583
|
+
reason: 'recovered:already_completed',
|
|
1584
|
+
durationMs: 0,
|
|
1585
|
+
stateCount: this.pluginStore.states(work.epoch.epochSeq)
|
|
1586
|
+
.filter((row) => row.pluginId === plugin.id).length,
|
|
1587
|
+
eventCount: this.listEvents({
|
|
1588
|
+
scope: work.epoch.scope,
|
|
1589
|
+
afterCommitSeq: 0,
|
|
1590
|
+
maxCommitSeq: this.inputJournal.eventWatermarkThrough(
|
|
1591
|
+
work.epoch.scope,
|
|
1592
|
+
work.epoch.epochSeq,
|
|
1593
|
+
),
|
|
1594
|
+
epochSeq: work.epoch.epochSeq,
|
|
1595
|
+
}).filter((event) => event.sourceId === `runtime-plugin:${plugin.id}`).length,
|
|
1596
|
+
eventCursorBefore: progress.eventCursor,
|
|
1597
|
+
eventCursorAfter: progress.eventCursor,
|
|
1598
|
+
recordedAt: new Date().toISOString(),
|
|
1599
|
+
});
|
|
1600
|
+
}
|
|
1601
|
+
}
|
|
1602
|
+
|
|
1603
|
+
private async withDeadline<T>(
|
|
1604
|
+
plugin: RuntimeEpochPlugin<TState, TEvent>,
|
|
1605
|
+
controller: AbortController,
|
|
1606
|
+
run: () => T | Promise<T>,
|
|
1607
|
+
onStaleSettlement?: (settlement: 'resolved' | 'rejected') => void,
|
|
1608
|
+
awaitSettlementAfterCancellation = false,
|
|
1609
|
+
onOperationSettlement?: (settlement: Promise<void>) => void,
|
|
1610
|
+
): Promise<T> {
|
|
1611
|
+
const timeoutMs = plugin.timeoutMs ?? this.pluginTimeoutMs;
|
|
1612
|
+
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
1613
|
+
let abandoned = false;
|
|
1614
|
+
let removeAbortListener: (() => void) | undefined;
|
|
1615
|
+
const operation = Promise.resolve().then(() => {
|
|
1616
|
+
if (controller.signal.aborted) {
|
|
1617
|
+
const reason = controller.signal.reason;
|
|
1618
|
+
throw reason instanceof Error
|
|
1619
|
+
? reason
|
|
1620
|
+
: new Error('Runtime Epoch Plugin invocation was cancelled.');
|
|
1621
|
+
}
|
|
1622
|
+
return run();
|
|
1623
|
+
});
|
|
1624
|
+
const operationSettlement = operation.then(() => {}, () => {});
|
|
1625
|
+
onOperationSettlement?.(operationSettlement);
|
|
1626
|
+
void operation.then(
|
|
1627
|
+
() => { if (abandoned) onStaleSettlement?.('resolved'); },
|
|
1628
|
+
() => { if (abandoned) onStaleSettlement?.('rejected'); },
|
|
1629
|
+
);
|
|
1630
|
+
const cancellation = new Promise<never>((_resolve, reject) => {
|
|
1631
|
+
const onAbort = (): void => {
|
|
1632
|
+
abandoned = true;
|
|
1633
|
+
const reason = controller.signal.reason;
|
|
1634
|
+
reject(reason instanceof Error ? reason : new Error('Runtime Epoch Plugin invocation was cancelled.'));
|
|
1635
|
+
};
|
|
1636
|
+
if (controller.signal.aborted) {
|
|
1637
|
+
onAbort();
|
|
1638
|
+
return;
|
|
1639
|
+
}
|
|
1640
|
+
controller.signal.addEventListener('abort', onAbort, { once: true });
|
|
1641
|
+
removeAbortListener = () => controller.signal.removeEventListener('abort', onAbort);
|
|
1642
|
+
});
|
|
1643
|
+
const timeout = new Promise<never>((_resolve, reject) => {
|
|
1644
|
+
timer = setTimeout(() => {
|
|
1645
|
+
abandoned = true;
|
|
1646
|
+
const error = new RuntimeEpochPluginTimeoutError(plugin.id, timeoutMs);
|
|
1647
|
+
controller.abort(error);
|
|
1648
|
+
reject(error);
|
|
1649
|
+
}, timeoutMs);
|
|
1650
|
+
});
|
|
1651
|
+
try {
|
|
1652
|
+
return await Promise.race([operation, timeout, cancellation]);
|
|
1653
|
+
} catch (error) {
|
|
1654
|
+
if (awaitSettlementAfterCancellation && abandoned) {
|
|
1655
|
+
await operation.then(() => {}, () => {});
|
|
1656
|
+
}
|
|
1657
|
+
throw error;
|
|
1658
|
+
} finally {
|
|
1659
|
+
if (timer) clearTimeout(timer);
|
|
1660
|
+
removeAbortListener?.();
|
|
1661
|
+
}
|
|
1662
|
+
}
|
|
1663
|
+
|
|
1664
|
+
private pendingInOrder(): PendingWork<TState, TEvent>[] {
|
|
1665
|
+
return [...this.pending.values()].sort((a, b) => a.work.epoch.epochSeq - b.work.epoch.epochSeq);
|
|
1666
|
+
}
|
|
1667
|
+
|
|
1668
|
+
private latestPendingEpochSeq(scope: RuntimeScope, fallback = 0): number {
|
|
1669
|
+
return this.pendingInOrder()
|
|
1670
|
+
.filter((pending) => runtimeScopeKey(pending.work.epoch.scope) === runtimeScopeKey(scope))
|
|
1671
|
+
.reduce((latest, pending) => Math.max(latest, pending.work.epoch.epochSeq), fallback);
|
|
1672
|
+
}
|
|
1673
|
+
|
|
1674
|
+
private orderOf(plugin: RuntimeEpochPlugin<TState, TEvent>): number {
|
|
1675
|
+
return this.orderOfId(plugin.id);
|
|
1676
|
+
}
|
|
1677
|
+
|
|
1678
|
+
private orderOfId(pluginId: string): number {
|
|
1679
|
+
return this.pluginOrder.get(pluginId) ?? Number.MAX_SAFE_INTEGER;
|
|
1680
|
+
}
|
|
1681
|
+
|
|
1682
|
+
private recordPluginTiming(
|
|
1683
|
+
record: RuntimeEpochPluginRecord,
|
|
1684
|
+
scope: RuntimeScope,
|
|
1685
|
+
nowMs: number,
|
|
1686
|
+
invoked = true,
|
|
1687
|
+
): void {
|
|
1688
|
+
if (!this.onDiagnostic) return;
|
|
1689
|
+
const key = `${runtimeScopeKey(scope)}:${record.pluginId}`;
|
|
1690
|
+
let window = this.pluginTimingWindows.get(key);
|
|
1691
|
+
if (window && nowMs - window.startedAtMs >= this.diagnosticTimingWindowMs) {
|
|
1692
|
+
this.emitPluginTimingWindow(window, nowMs);
|
|
1693
|
+
this.pluginTimingWindows.delete(key);
|
|
1694
|
+
window = undefined;
|
|
1695
|
+
}
|
|
1696
|
+
if (!window) {
|
|
1697
|
+
window = {
|
|
1698
|
+
scope: cloneCanonical(scope),
|
|
1699
|
+
pluginId: record.pluginId,
|
|
1700
|
+
startedAtMs: nowMs,
|
|
1701
|
+
fromEpochSeq: record.epochSeq,
|
|
1702
|
+
throughEpochSeq: record.epochSeq,
|
|
1703
|
+
durationsMs: [],
|
|
1704
|
+
processedCount: 0,
|
|
1705
|
+
noopCount: 0,
|
|
1706
|
+
failedCount: 0,
|
|
1707
|
+
coalescedCount: 0,
|
|
1708
|
+
slowCount: 0,
|
|
1709
|
+
};
|
|
1710
|
+
this.pluginTimingWindows.set(key, window);
|
|
1711
|
+
}
|
|
1712
|
+
window.fromEpochSeq = Math.min(window.fromEpochSeq, record.epochSeq);
|
|
1713
|
+
window.throughEpochSeq = Math.max(window.throughEpochSeq, record.epochSeq);
|
|
1714
|
+
if (record.outcome === 'processed') window.processedCount += 1;
|
|
1715
|
+
else if (record.outcome === 'noop') window.noopCount += 1;
|
|
1716
|
+
else if (record.outcome === 'failed') window.failedCount += 1;
|
|
1717
|
+
else window.coalescedCount += 1;
|
|
1718
|
+
if (invoked) {
|
|
1719
|
+
window.durationsMs.push(record.durationMs);
|
|
1720
|
+
if (record.durationMs >= slowPluginThresholdMs(record.pluginId)) window.slowCount += 1;
|
|
1721
|
+
}
|
|
1722
|
+
}
|
|
1723
|
+
|
|
1724
|
+
private emitPluginTimingWindow(window: PluginTimingWindow, endedAtMs: number): void {
|
|
1725
|
+
if (!this.onDiagnostic) return;
|
|
1726
|
+
const sorted = [...window.durationsMs].sort((a, b) => a - b);
|
|
1727
|
+
const total = sorted.reduce((sum, value) => sum + value, 0);
|
|
1728
|
+
this.onDiagnostic('runtime.plugin.timing_window', {
|
|
1729
|
+
plugin_id: window.pluginId,
|
|
1730
|
+
window_ms: Math.max(0, endedAtMs - window.startedAtMs),
|
|
1731
|
+
from_epoch_seq: window.fromEpochSeq,
|
|
1732
|
+
through_epoch_seq: window.throughEpochSeq,
|
|
1733
|
+
invocation_count: sorted.length,
|
|
1734
|
+
processed_count: window.processedCount,
|
|
1735
|
+
noop_count: window.noopCount,
|
|
1736
|
+
failed_count: window.failedCount,
|
|
1737
|
+
coalesced_count: window.coalescedCount,
|
|
1738
|
+
slow_count: window.slowCount,
|
|
1739
|
+
duration_avg_ms: sorted.length === 0 ? 0 : rounded(total / sorted.length),
|
|
1740
|
+
duration_p50_ms: percentile(sorted, 0.5),
|
|
1741
|
+
duration_p95_ms: percentile(sorted, 0.95),
|
|
1742
|
+
duration_max_ms: sorted.at(-1) ?? 0,
|
|
1743
|
+
}, window.scope);
|
|
1744
|
+
}
|
|
1745
|
+
|
|
1746
|
+
private flushPluginTimingWindows(scope: RuntimeScope, endedAtMs: number): void {
|
|
1747
|
+
const scopePrefix = `${runtimeScopeKey(scope)}:`;
|
|
1748
|
+
for (const [key, window] of this.pluginTimingWindows) {
|
|
1749
|
+
if (!key.startsWith(scopePrefix)) continue;
|
|
1750
|
+
this.emitPluginTimingWindow(window, endedAtMs);
|
|
1751
|
+
this.pluginTimingWindows.delete(key);
|
|
1752
|
+
}
|
|
1753
|
+
}
|
|
1754
|
+
|
|
1755
|
+
private boundedPendingLag(
|
|
1756
|
+
scope: RuntimeScope,
|
|
1757
|
+
completedThroughEpochSeq: number,
|
|
1758
|
+
latestEpochSeq: number,
|
|
1759
|
+
): { count: number; capped: boolean } {
|
|
1760
|
+
let count = 0;
|
|
1761
|
+
for (const pending of this.pending.values()) {
|
|
1762
|
+
if (runtimeScopeKey(pending.work.epoch.scope) !== runtimeScopeKey(scope)) continue;
|
|
1763
|
+
const epochSeq = pending.work.epoch.epochSeq;
|
|
1764
|
+
if (epochSeq <= completedThroughEpochSeq || epochSeq > latestEpochSeq) continue;
|
|
1765
|
+
count += 1;
|
|
1766
|
+
if (count >= CRITICAL_LAG_EPOCHS) {
|
|
1767
|
+
return { count: CRITICAL_LAG_EPOCHS, capped: true };
|
|
1768
|
+
}
|
|
1769
|
+
}
|
|
1770
|
+
return { count, capped: false };
|
|
1771
|
+
}
|
|
1772
|
+
|
|
1773
|
+
private lagSnapshot(scope: RuntimeScope, latestEpochSeq: number): LagSnapshot {
|
|
1774
|
+
const progressByPlugin = new Map(this.plugins.map((plugin) => [
|
|
1775
|
+
plugin.id,
|
|
1776
|
+
this.pluginStore.pluginProgress(plugin.id, scope),
|
|
1777
|
+
]));
|
|
1778
|
+
const pluginProgress = this.plugins.map((plugin) => {
|
|
1779
|
+
const progress = progressByPlugin.get(plugin.id)!;
|
|
1780
|
+
const dependencies = (plugin.after ?? []).map((id) => (
|
|
1781
|
+
progressByPlugin.get(id)?.completedThroughEpochSeq ?? 0
|
|
1782
|
+
));
|
|
1783
|
+
const readyThroughEpochSeq = dependencies.length === 0
|
|
1784
|
+
? latestEpochSeq
|
|
1785
|
+
: Math.min(latestEpochSeq, ...dependencies);
|
|
1786
|
+
const lag = this.boundedPendingLag(scope, progress.completedThroughEpochSeq, latestEpochSeq);
|
|
1787
|
+
return {
|
|
1788
|
+
plugin_id: plugin.id,
|
|
1789
|
+
completed_through_epoch_seq: progress.completedThroughEpochSeq,
|
|
1790
|
+
ready_through_epoch_seq: readyThroughEpochSeq,
|
|
1791
|
+
lag_epoch_count: lag.count,
|
|
1792
|
+
lag_count_capped: lag.capped,
|
|
1793
|
+
};
|
|
1794
|
+
});
|
|
1795
|
+
const maxLagEpochCount = Math.max(0, ...pluginProgress.map((progress) => progress.lag_epoch_count));
|
|
1796
|
+
return {
|
|
1797
|
+
band: lagBand(maxLagEpochCount),
|
|
1798
|
+
latestEpochSeq,
|
|
1799
|
+
maxLagEpochCount,
|
|
1800
|
+
lagCountCapped: pluginProgress.some((progress) => progress.lag_count_capped),
|
|
1801
|
+
pluginProgress,
|
|
1802
|
+
};
|
|
1803
|
+
}
|
|
1804
|
+
|
|
1805
|
+
private reportLagTransition(scope: RuntimeScope, latestEpochSeq: number): void {
|
|
1806
|
+
if (!this.onDiagnostic || this.plugins.length === 0) return;
|
|
1807
|
+
const snapshot = this.lagSnapshot(scope, latestEpochSeq);
|
|
1808
|
+
const scopeKey = runtimeScopeKey(scope);
|
|
1809
|
+
const previous = this.lagBands.get(scopeKey) ?? 'healthy';
|
|
1810
|
+
this.lagBands.set(scopeKey, snapshot.band);
|
|
1811
|
+
if (snapshot.band === previous) return;
|
|
1812
|
+
const common = {
|
|
1813
|
+
previous_band: previous,
|
|
1814
|
+
current_band: snapshot.band,
|
|
1815
|
+
latest_epoch_seq: snapshot.latestEpochSeq,
|
|
1816
|
+
max_lag_epoch_count: snapshot.maxLagEpochCount,
|
|
1817
|
+
lag_count_capped: snapshot.lagCountCapped,
|
|
1818
|
+
plugin_progress: snapshot.pluginProgress.filter((progress) => (
|
|
1819
|
+
progress.lag_epoch_count >= DEGRADED_LAG_EPOCHS
|
|
1820
|
+
)),
|
|
1821
|
+
};
|
|
1822
|
+
if (snapshot.band === 'critical') {
|
|
1823
|
+
this.onDiagnostic('runtime.view.lag_critical', common, scope, 'warn');
|
|
1824
|
+
} else if (snapshot.band === 'degraded') {
|
|
1825
|
+
this.onDiagnostic('runtime.view.lag_degraded', common, scope, 'warn');
|
|
1826
|
+
} else {
|
|
1827
|
+
this.onDiagnostic('runtime.view.lag_recovered', common, scope, 'info');
|
|
1828
|
+
}
|
|
1829
|
+
}
|
|
1830
|
+
|
|
1831
|
+
private failRuntime(error: unknown, pluginId: string, scope = this.activeScope ?? undefined): void {
|
|
1832
|
+
if (this.fatalError) return;
|
|
1833
|
+
this.fatalError = error;
|
|
1834
|
+
for (const active of this.activeInvocations.values()) {
|
|
1835
|
+
if (!active.controller.signal.aborted) active.controller.abort(error);
|
|
1836
|
+
}
|
|
1837
|
+
for (const controller of this.activeCommits.values()) {
|
|
1838
|
+
if (!controller.signal.aborted) controller.abort(error);
|
|
1839
|
+
}
|
|
1840
|
+
for (const pending of this.pending.values()) pending.reject(error);
|
|
1841
|
+
this.pending.clear();
|
|
1842
|
+
this.bufferedInvocations.clear();
|
|
1843
|
+
if (scope) this.onFatalError?.(error, pluginId, scope);
|
|
1844
|
+
this.resolveIdle();
|
|
1845
|
+
}
|
|
1846
|
+
|
|
1847
|
+
private isIdle(): boolean {
|
|
1848
|
+
return this.pending.size === 0
|
|
1849
|
+
&& this.activeInvocations.size === 0
|
|
1850
|
+
&& this.activeCommits.size === 0
|
|
1851
|
+
&& this.bufferedInvocationCount() === 0
|
|
1852
|
+
&& !this.pumping;
|
|
1853
|
+
}
|
|
1854
|
+
|
|
1855
|
+
private resolveIdle(): void {
|
|
1856
|
+
if (!this.isIdle()) return;
|
|
1857
|
+
const waiters = this.idleWaiters.splice(0);
|
|
1858
|
+
for (const resolve of waiters) resolve();
|
|
1859
|
+
}
|
|
1860
|
+
}
|