Runtime topology, connections and lifecycles
Latest review, 2026-10-31 (ARCH-015, ARCH-016, ARCH-017): CHANGES REMAIN. Schedule claims precede dispatch and entry points use Govern; run-row and descriptor failures block dispatch. Cross-slot expired claims are now reaped to
indeterminate(ARCH-023), the reproduced function-ACL gap is closed — Govern now runs the explicit per-function ACL in every entry (ARCH-024), contract-risk read failures fail closed instead of silently downgrading to medium (ARCH-025), and terminal event persistence is atomic — the guarded status update and event append run in one transaction, so a failed event write rolls back instead of being ACKed away (ARCH-015). Drain/shutdown normal paths exist; ARCH-016 closed the accepted-task drain gap (continuations route via session store; drain waits TaskRunner.Count()==0) and ARCH-017 bounded the final deferred StopScheduler with a hard stop timeout plus a real-entry shutdown drill. Overall deadline guarantees and game-side exactly-once remain open (see ARCH-018, GAME-010). See the latest review. High-risk production writes are not approved.
Reviewed 2026-10-30 against source wiring and repository deployment templates. This is not an inventory of a running production deployment. Implemented means production wiring can be traced; target means a runtime gap remains; unverified requires real configuration, accounts or infrastructure. No application behavior was changed. The root todo.md is the active delivery ledger; the earlier audit (docs/review/architecture-audit-2026-10-28.md) is historical evidence.
Full English topology SVG · 中文 SVG
Deployable units and package boundaries
| Unit / placement | Entry point (existing build output) | Responsibility and evidence |
|---|---|---|
| Server / control network | bin/croupier-server --config configs/server.yaml | One modular process: Gin HTTP, registry, dispatch, approvals/audit, contracts/pages, Ops and scheduling. cmd/server/root.go, internal/svc/service_context.go. These modules are not separate microservices. |
| Web / browser plus nginx container | dashboard in docker/docker-compose.quickstart.yml | Umi/React client; nginx serves assets and proxies APIs. web/config/proxy.ts, docker nginx configuration. |
| Mobile / operator device | Flutter, mobile/lib/main.dart | HTTP client wired in mobile/lib/app/providers.dart. Feature parity and production installation are unverified. |
| sidecar / game host or VPC | bin/croupier-agent --config configs/agent.yaml | SDK gateway, function dispatch, tasks, managed processes, probes and extensions. cmd/sidecar-agent → internal/app/agent → agents/sidecar. |
| capture / source-reachable host | bin/capture-agent --config configs/capture-agent.yaml | CDC, checkpoints, filters/rules, alert spool and optional event journal. agents/capture/runner/runner.go. |
| synthetics / consumer network viewpoint | bin/synthetics-agent --config configs/synthetics-agent.yaml | Role-specific probes and external probe plugins. agents/synthetics/runner/runner.go; this does not imply every sidecar Checker is wired here. |
| devops / operations network | bin/devops-agent --config configs/devops-agent.yaml | Registration, allowlist synchronization and SSH Broker/Hub/recording foundations. agents/devops/runner/runner.go. Console relay is missing; RDP/VNC are explicitly rejected. |
| Game service / game-owned environment | Game executable embeds sdks/{go,js,python,java,csharp,cpp} | SDKs are libraries, not additional services. Game systems own authoritative game state. Recovery behavior must be checked per language against its implementation and SDK matrix. |
| Function/probe plugins / Agent child processes | Host launches configured commands | core/pluginhost/engine.go, agents/sidecar/funcplugin, agents/synthetics/pluginhost: local go-plugin gRPC. This is separate from SDK and Agent control transport. Host owns process exit/backoff; optional no_go_plugin builds omit it. |
| ingest / intake network | bin/ingest --addr :8088 | HTTP signature checking and event/payment publishing. cmd/ingest/cmd/root.go. |
| analytics-worker / analytics network | bin/analytics-worker with environment configuration | Redis consumer groups, ClickHouse batches, aggregation and dead letters. cmd/analytics-worker/main.go, internal/analytics/worker/worker.go. |
| One-shot tools / operator or build host | cmd/analytics-export, cmd/check-db, cmd/schema-validator, tools/protoc-gen-croupier | Export, diagnosis, validation and code generation; not mandatory resident services. |
core/ contains explicitly composed packages such as transport/register/configsync/process/pluginhost, not a separately running Agent. SQL, Redis and ClickHouse are external storage services. nginx/HAProxy are optional deployment ingress. Herald, OIDC, Vault, QuickSDK/extension platforms and observability backends are conditional integrations.
Connection inventory
Arrows in the overview identify connection establishment or the labeled data flow. A bidirectional session can carry requests opposite to the original TCP connection. External endpoints without a fixed port come from configuration; templates do not establish production addresses.
| Connection / trigger | Protocol and interaction | Authentication, content and evidence |
|---|---|---|
| Browser/mobile → Server / navigation or action | HTTP request/response; task SSE is a sustained Server → client response; optional nginx | JWT and scope middleware, except public endpoints. gameId/env, PageSpec bindings, inputs, approval/task queries. internal/handler/routes.go, internal/svc/service_context.go, game_middleware.go, internal/api/console, internal/api/task. |
Four Agent roles → control :19090 / startup, reconnect or snapshot update | Custom TCP frames and protobuf; Register/Heartbeat request/ACK; established sessions carry commands, configuration and uplink reports | Configurable TLS; CA can enable mTLS. No HTTP JWT registration flow. AgentID/gameId/env become session identity; uplink normalization prevents payload scope replacement, not certificate-to-business-identity binding. internal/server/tcp_listener.go, control_handler.go, agents/controlconn/controlconn.go, core/transport/tcp. |
SDK → sidecar provider :19091 / game connects | ProviderConnect/ACK and Heartbeat/ACK; Server → sidecar → SDK Invoke with JSON result; SDKs can also invoke through the gateway | Controlled local network by default, configurable TLS. Connect validates serviceId and records metadata; Web JWT is not automatically inherited. internal/agent/tcp_local_listener.go, local_handler.go, agents/sidecar/provider_session.go. |
| sidecar → Server HTTP / extension sync enabled | Periodic GET /api/v1/agents/:id/extensions under CROUPIER_EXTENSION_SYNC_API; 8s timeout, versioned payload; machine identity via X-Croupier-Agent-Token | internal/app/agent/extension_sync_puller.go sends ARCH-021 machine JWT (CROUPIER_EXTENSION_SYNC_TOKEN); internal/svc/service_context.go restricts machine tokens to the endpoint (403 elsewhere), internal/api/extension/service.go:AgentSyncPayload enforces agentID scope. Issuance: croupier-server token agent-sync. |
| Server A → owner Server B / target session not local | TCP interconnect, hello and one-hop invoke/start/cancel with caller context and epoch; mTLS when cluster.interconnectTls is configured | Hello + mTLS peer-certificate identity (dual EKU server role; Agent certs rejected); unhandshaked forward rejected; epoch fences stale ownership. cmd/server/cluster.go, mesh_forwarder.go, internal/cluster/transport.go, internal/cluster/identity.go. |
| Server → relational DB / requests and background jobs | GORM/driver SQL for metadata, business records, contracts, pages, tasks and audit | DSN credentials/TLS configuration; metadata DB versus selected dbctx game DBs. internal/svc/service_context.go, internal/db/router, internal/db/dbctx. |
| Server → shared DB or Redis / cluster enabled | Periodic membership/owner leases, epochs and discovery snapshots | Backend credentials; does not share net.Conn. cmd/server/cluster.go, internal/cluster. Cache and analytics uses of Redis are separate roles. |
| capture → source DB / startup and source reconnect | MySQL/MariaDB binlog, including GTID paths; PostgreSQL pgoutput; MongoDB change streams. Source changes stream back to capture | Configured credentials and replication permissions; local checkpoints/source acknowledgment. agents/capture/source, agents/capture/connector/{pg,mongo}, runner/runner.go. Raw CDC does not automatically flow through ingest into ClickHouse. |
| capture → Server / rule hit | AlertEventRequest/ACK; spool retries failures; Server uses deterministic alert IDs | Session-bound identity; rule, position, key, occurrence time and scope. runner/alert_spool.go, control_handler.go:handleAlertEventAsAgent. Optional journal remains on the capture host. |
| Probe host → target / interval | Role/target-dependent HTTP, TCP, DB or protocol request/response; status, latency and failure phase | Target credentials from configuration/controlled synchronization; separate from control-plane authentication. core/healthprobe, internal/app/agent/probe_manager.go, agents/synthetics/probe. Server-local probes are also wired. |
| synthetics → Server / each result | MsgAlertEvent protobuf notification on session, no application ACK; 5s send budget | agents/synthetics/runner/runner.go:execute, agents/controlconn/controlconn.go:SendProbeEvent: failures are logged without durable replay; capture spool guarantees do not apply. |
| Agent host → plugin child / first call or restart | Local HashiCorp go-plugin gRPC: Describe then Check/Invoke | Handshake contract and local process boundary, not remote authorization. Scoped credentials are supplied and probe output is sanitized. core/pluginhost/engine.go, agents/synthetics/pluginhost/result.go. |
| devops Hub → SSH host / local Broker invocation only | SSH stream, window changes, closure and asciicast | Allowlist, user credentials and known_hosts. agents/devops/session/{broker,hub,sshtarget}.go. Console relay to this foundation is missing. |
External producer → ingest :8088 | HTTP JSON, HMAC/time-window verification, response after queue publication | Configured shared/per-secret credentials, limits and optional Redis deduplication. Without shared or per-game secrets, returns 403 ingest_disabled; production credentials remain unverified. |
| ingest / Server telemetry bridge → Redis Streams → worker → ClickHouse | XADD publication, XREADGROUP/XAUTOCLAIM/XACK consumption, native ClickHouse driver batches | Redis URL/password and ClickHouse DSN; bridge is opt-in. internal/analytics/mq, internal/telemetry, internal/analytics/worker/worker.go. Kafka publishing exists but the built-in worker has no Kafka consumer. |
| Server → Herald / configured alert or report | SDK HTTP trigger request/response; asynchronous notification trigger, station message stored first | Token environment variable, app/audience and dedup key. Missing configuration selects noop; bounded retry. internal/platform/outlet/{outlet,herald}.go, internal/svc/service_context.go:registerOutlets. |
| Server/sidecar extension → external platform / function call | HTTP API | QuickSDK OpenID/OpenKey signing and extension driver settings. internal/extensions/official/externalplatform/client.go, internal/app/agent/extension_external_bridge.go. Source code is not evidence of real-account acceptance. |
OIDC login, Vault secret resolution, SMTP/object storage and OTel/monitoring endpoints are conditional supporting integrations. Inspect internal/svc/service_context.go, internal/config/config.go, configs/server.yaml; the overview groups these under optional integrations. Actual enabled endpoints remain DEPLOY-001, not assumed universal connections.
Discovery, routing, scheduling and storage ownership
- Discovery: SDK Connect/Heartbeat/disconnect update the sidecar LocalStore and ProviderSession. The sidecar registers full function/process snapshots upstream and debounces updates. Server registry holds scoped functions/providers/expiry and persists
agent_sessions; startup reloads snapshots, not live connections. Evidence:internal/app/agent/upstream.go:buildRegisterPayload/updateLoop,internal/platform/registry/store.go,internal/server/control_handler.go. - Expiry: registration TTL defaults to five minutes; heartbeats refresh using the default TTL. Disconnection removes the live
(agentID, sessionID)conditionally, so old cleanup cannot delete a newer session. Registry maintenance expires snapshots/provider projections. Historical DB identity anchors are not online proof. Evidence:internal/server/agent_session.go:RemoveSession,tcp_listener.go,internal/platform/registry/agent_session_db.go. - Routing:
internal/platform/dispatch/dispatcher.gofilters scoped, enabled candidates and selects by strategy; local sessions or owner forwarding reach the Agent. The sidecar selects a Provider, built-in function or plugin. Server does not directly dial the game. Default invoke ceiling is 15s; metadata budgets clamp to 1s–ceiling. Retry eligibility depends on path/error and is not a guarantee of safe side-effect repetition. - Scheduling:
internal/tasks/scheduler/manager.goreads task definitions and dispatches functions or runs server-local reports.internal/app/agent/ops_schedule.godrives managed-process cron locally. Sharedcore/processparsing does not create a standalone scheduler or distributed exactly-once execution. Local minute-slot deduplication does not backfill missed slots; cross-slot stale claims (crash after claim) are reaped toindeterminateper ARCH-023, with no re-dispatch. - Storage: SQL holds tasks/pages/contracts/audit. scope is an authorization boundary; multiGame routes selected models through dbctx, not every table. Production routing uses binding.database_name; the Open-phase budget still has a gap (ARCH-009). Production function approvals persist via
approvals.NewSQLStore(db)(wired since 9066d7c10, 2026-10-30) with CAS decisions and durable dispatch claims; approval tickets still carry no TTL and renewalapprovalBypass=approvedremains. Evidence:internal/svc/service_context.go,internal/svc/game_middleware.go,internal/db/router/router.go.
Separate lifecycles and failure behavior
Time moves down each sequence diagram; dashed vertical lines are lifelines. ALT boxes contain mutually exclusive outcomes. ACK semantics follow the text. Crossings without junction dots are not connected.
Registration and reconnection
Server constructs ServiceContext/database and registration materialization, scheduler, session resolver and optional cluster before control/HTTP listeners. DB ping may only warn; some cluster initialization failures fall back to standalone. healthz is not complete readiness. Agents validate scope, connect TCP/TLS, Register and await ACK before heartbeats. SDKs may arrive later; function changes trigger registration updates.
core/register applies a 10s registration budget to every register call (DialAndRegister, SyncOnce and SyncAttempts via registerCtx); an earlier caller deadline wins. A hung Register no-response exits within budget instead of blocking reconnect. Sync retries back off 200ms→2s. Heartbeats default to every 3s, 3s timeout and reconnection after two failures. Initial-failure RunReconnectLoop backs off 5→60s ×1.5; heartbeat recovery dials directly on its tick (already rate-limited by the heartbeat interval, so no additional backoff). Relevant defaults are configurable. Replacement closes the old connection; Stop/context cancellation ends loops and releases goroutines; dialInflight CAS prevents duplicate parallel reconnects. New registration rebuilds the current business snapshot; it does not replay in-flight commands. SDK recovery varies by language. Evidence: core/register/{register,registration,loops}.go, internal/app/agent/upstream.go.
Governed invocation, approval and tasks
HTTP identity/scope → published binding or governed draft → functioninvoke disable/assignment/schema/policy gates. Denial, approval and execution are exclusive outcomes. Tasks and schedules now use Govern, and Govern runs the explicit per-function ACL (CheckInvokePermission) in the same chain as /tasks Start — ordinary, manual and automated entries share one authorization (ARCH-024). Contract-risk source failures fail closed instead of silently downgrading to medium (ARCH-025); GetPolicy and descriptor query errors also deny. Create checks invocability; execution rechecks per trigger. Production TaskRunWriter persistence failures block StartTask (ARCH-026); descriptor query errors deny, while genuinely absent schemas skip validation (ARCH-027). A returned taskId acknowledges acceptance. Cancel records intent and routes to the Agent; its ACK does not reverse external effects.
Limits: sidecar TaskRunner starts goroutines with Background contexts and stores cancellation functions by taskId. Duplicate Start of the same ID lacks durable deduplication; event reporting errors are discarded. Completion defers map removal/cancel. This is not durable event replay or process-crash recovery. Page DB idempotency does not protect game rewards/payments; a timeout can mean unknown outcome, requiring game-side receipts and deduplication. Evidence: agents/sidecar/task_runner.go, internal/platform/dispatch/{dispatcher,task_routing_store}.go, internal/server/control_handler.go:handleTaskEvent, internal/api/approval/service.go.
CDC alerts and outlets
capture loads its bookmark, opens the source, Polls, optionally journals/consumes, acknowledges the connector checkpoint and periodically flushes its local bookmark. Source EOF flushes/closes before reopening. Corrupt bookmarks are not silently treated as empty. Rule hits enter a durable local spool before asynchronous Server requests; success ACK removes the spool item. Queue pressure/persistence failures are logged/counted. Server idempotently stores the alert, then station/optional Herald delivery follows. Dispatch starts an asynchronous goroutine after persistence, before constructing the ACK; delivery can precede or follow ACK receipt. An alert-storage ACK does not prove audience delivery. Outlet defaults are three attempts, 2s delay and 15s call budget; permanent errors stop retries and maintenance gates can suppress notifications. Raw CDC is not a default analytics event bus. Evidence: agents/capture/runner/{runner,alert_spool}.go, internal/server/control_handler.go, internal/platform/outlet/outlet.go.
Plugins and shutdown
Host acquires a concurrency gate, starts a child on demand, handshakes/Dispenses and Describes before Check/Invoke. Failures kill the process and update backoff/breaker state; healthy children are reused. Stop rejects new work, waits up to 5s for in-flight work, then kills children. Controlled credentials and output redaction do not make the plugin a security sandbox. Evidence: core/pluginhost/engine.go.
Provider drain has a Draining flag, RPC in-flight counts, routing rejection and a grace wait; undrain uses a reason sentinel. Accepted work not yet in its RPC is routed via session store after registration removal (R30-09, ARCH-016), and drain waits TaskRunner.Count()==0. Grace expiry does not force-close active work. Normal Server shutdown is StopAccepting → HTTP drain → rootCancel → StopScheduler/ControlService.Stop → WaitConnections → ServiceContext.Close and template-regenerator cleanup. The final deferred StopScheduler is bounded by a hard stop timeout (R30-07, ARCH-017): a tick that ignores context cancellation cannot stall shutdown past the bound; the loop still exits once unblocked. sidecar Stop closes plugins/listeners/upstream/telemetry/Ops; worker main waits only a fixed 200ms after cancellation. Evidence: internal/agent/local_handler.go, cmd/server/root.go, internal/svc/service_context.go, internal/app/agent/app.go, cmd/analytics-worker/main.go. Failure acceptance: ARCH-015–018 and DATA-015.
Deployment and operational failure handling
- Binaries: Makefile targets server/agent/agent-capture/agent-synthetics/agent-devops/ingest/worker produce the entries above. No compilation was run for this documentation change. Each Agent instance declares one gameId/env; ports are configurable defaults.
- Quickstart:
docker/docker-compose.quickstart.ymlstarts one Server, sidecar, dashboard, PostgreSQL and Redis. Host8443 → container 19090is port mapping, not evidence of HTTPS. analytics/sdk-examples profiles add components; capture/synthetics/devops are absent from the default stack. - HA template:
docker/docker-compose.deploy.ymlprovides two Server/sidecar instances with HAProxy, dashboard nginx for HTTP and L4 Agent ingress. Coordination is shared, live sessions stay in each owner process. Templates and healthchecks do not establish production failover. Interconnect still needs trusted network isolation; mTLS is a target. - TLS and volumes: development templates leave certs empty and enable insecure transport. Verify termination, CA/certs and DB/Redis credentials in actual deployments. Preserve Server data, capture bookmark/spool/journal, devops casts/logs, sidecar desired_state/schedule_pause files and plugin versions. DB backups now cover approval tickets (SQLStore); running tasks remain in-process and are not recoverable from backups.
- Diagnosis: verify scope/configuration/process → registration ACK → owner/live session → function/Provider snapshot → governed rejection → task events/game receipt. Do not repair online state by editing DB snapshots. Observe Provider removal/reregistration after SDK disconnects. For high-risk timeouts, query outcomes/receipts before considering a retry.
- Analytics reliability: detail batches now ACK only after Send; retry/dead-letter XADD errors leave messages pending. This does not make aggregation safe: revenue/flush shared-field races are reproduced (DATA-014), and shutdown does not join worker goroutines (DATA-015). Real crash/replay acceptance remains ARCH-012.
Current behavior versus targets
| Implemented / limitation | Target or unverified work | TODO |
|---|---|---|
| One-hop owner routing / epochs; partial standalone fallback | Authenticated interconnect, readiness and lease-loss removal | ARCH-003–005 |
| SQL approvals wired with CAS decisions/claims (9066d7c10) | Approval ticket TTL; renewal bypass re-review | ARCH-001/002 |
| SQL page/task records; UI idempotency does not cover game effects | Task replay contract and real-game receipts | ARCH-014/015, GAME-001 |
| Scope validation; binding-driven physical routing | Open-phase budget and pool capacity | ARCH-006/009/010 |
| Drain/shutdown wired; queued-task and total-deadline gaps remain | Disconnect/drain/SIGTERM drill, force-close after grace | ARCH-018 |
| SSH foundations; missing console relay | Relay and playback UI; no automatic RDP/VNC expansion | AGENT-002/003 |
| SLP/protocol skeleton and plugin runtime | Real-account login-level acceptance | PROBE-001–003 |
Official references and version boundaries
Checked 2026-10-29. References establish upstream semantics, not acceptance of this implementation. Versions below come from the repository; running image digests remain DEPLOY-001.
| Product/library | Repository version/template | Official reference and checked scope | Unverified |
|---|---|---|---|
| Redis | quickstart 7-alpine, floating tag | XACK: removes acknowledged entries from the consumer group's PEL, not a downstream commit | Actual version, persistence/trimming and fault windows |
| HashiCorp go-plugin | go.mod v1.8.0 | Official repository: child-process RPC with multilingual gRPC; this repository permits local gRPC only | Platform/language/real-protocol acceptance |
| PostgreSQL | quickstart 15-alpine | 15 logical replication: publication/subscription and replication identity; pgoutput here requires source slot/permissions | Source publication/slot/WAL retention and actual version |
| MySQL | go-mysql v1.9.1, source version unknown | MySQL 8.0 GTID: replication positioning | MySQL/MariaDB flavor, permissions, retention and recovery samples |
| ClickHouse | driver v2.43.0, template 23-alpine | Batch behavior traced through worker.go/driver interface; no new product-selection study | Server compatibility/deduplication/durability: ARCH-012 |
| Herald | v0.1.3-0.20261014084113-9875146dc50a | Repository SDK/outlet calls are evidence of integration, not external delivery | Trigger configuration, audience and real receipts |
Full MongoDB change-stream, OIDC/Vault, external-account and image/license matrix investigations were not undertaken. DEPLOY-001/PROBE-003 register this work without expanding implementation scope.
Failure-boundary recheck, 2026-10-30
The normal paths above do not establish full failure guarantees. An accepted task that has not entered its Provider RPC can fail after drain ACK because pickInstance sees a removed registration; the later taskId routing exception cannot repair that lookup. The outer 30s Server wait does not bound the final deferred StopScheduler. Terminal persistence is now atomic — handleTaskEvent persists the guarded status update and the event append in one transaction, so a failed event write rolls back and a retry after source recovery converges the row (ARCH-015). Some audit callers still discard strict Log errors. ARCH-016/017/008 are reopened. The worktree watchdog is in progress, not ARCH-018 drill acceptance. See the latest review.
