Skip to content

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.

Croupier current architecture: console, Server, four Agent roles, SDKs, shared state and separate analytics pipeline
Source review: 2026-10-30 · Open the full SVG

Full English topology SVG · 中文 SVG

Deployable units and package boundaries ​

Unit / placementEntry point (existing build output)Responsibility and evidence
Server / control networkbin/croupier-server --config configs/server.yamlOne 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 containerdashboard in docker/docker-compose.quickstart.ymlUmi/React client; nginx serves assets and proxies APIs. web/config/proxy.ts, docker nginx configuration.
Mobile / operator deviceFlutter, mobile/lib/main.dartHTTP client wired in mobile/lib/app/providers.dart. Feature parity and production installation are unverified.
sidecar / game host or VPCbin/croupier-agent --config configs/agent.yamlSDK gateway, function dispatch, tasks, managed processes, probes and extensions. cmd/sidecar-agent → internal/app/agent → agents/sidecar.
capture / source-reachable hostbin/capture-agent --config configs/capture-agent.yamlCDC, checkpoints, filters/rules, alert spool and optional event journal. agents/capture/runner/runner.go.
synthetics / consumer network viewpointbin/synthetics-agent --config configs/synthetics-agent.yamlRole-specific probes and external probe plugins. agents/synthetics/runner/runner.go; this does not imply every sidecar Checker is wired here.
devops / operations networkbin/devops-agent --config configs/devops-agent.yamlRegistration, 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 environmentGame 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 processesHost launches configured commandscore/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 networkbin/ingest --addr :8088HTTP signature checking and event/payment publishing. cmd/ingest/cmd/root.go.
analytics-worker / analytics networkbin/analytics-worker with environment configurationRedis consumer groups, ClickHouse batches, aggregation and dead letters. cmd/analytics-worker/main.go, internal/analytics/worker/worker.go.
One-shot tools / operator or build hostcmd/analytics-export, cmd/check-db, cmd/schema-validator, tools/protoc-gen-croupierExport, 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 / triggerProtocol and interactionAuthentication, content and evidence
Browser/mobile → Server / navigation or actionHTTP request/response; task SSE is a sustained Server → client response; optional nginxJWT 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 updateCustom TCP frames and protobuf; Register/Heartbeat request/ACK; established sessions carry commands, configuration and uplink reportsConfigurable 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 connectsProviderConnect/ACK and Heartbeat/ACK; Server → sidecar → SDK Invoke with JSON result; SDKs can also invoke through the gatewayControlled 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 enabledPeriodic GET /api/v1/agents/:id/extensions under CROUPIER_EXTENSION_SYNC_API; 8s timeout, versioned payload; machine identity via X-Croupier-Agent-Tokeninternal/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 localTCP interconnect, hello and one-hop invoke/start/cancel with caller context and epoch; mTLS when cluster.interconnectTls is configuredHello + 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 jobsGORM/driver SQL for metadata, business records, contracts, pages, tasks and auditDSN 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 enabledPeriodic membership/owner leases, epochs and discovery snapshotsBackend 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 reconnectMySQL/MariaDB binlog, including GTID paths; PostgreSQL pgoutput; MongoDB change streams. Source changes stream back to captureConfigured 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 hitAlertEventRequest/ACK; spool retries failures; Server uses deterministic alert IDsSession-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 / intervalRole/target-dependent HTTP, TCP, DB or protocol request/response; status, latency and failure phaseTarget 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 resultMsgAlertEvent protobuf notification on session, no application ACK; 5s send budgetagents/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 restartLocal HashiCorp go-plugin gRPC: Describe then Check/InvokeHandshake 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 onlySSH stream, window changes, closure and asciicastAllowlist, user credentials and known_hosts. agents/devops/session/{broker,hub,sshtarget}.go. Console relay to this foundation is missing.
External producer → ingest :8088HTTP JSON, HMAC/time-window verification, response after queue publicationConfigured 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 → ClickHouseXADD publication, XREADGROUP/XAUTOCLAIM/XACK consumption, native ClickHouse driver batchesRedis 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 reportSDK HTTP trigger request/response; asynchronous notification trigger, station message stored firstToken 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 callHTTP APIQuickSDK 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.go filters 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.go reads task definitions and dispatches functions or runs server-local reports. internal/app/agent/ops_schedule.go drives managed-process cron locally. Shared core/process parsing 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 to indeterminate per 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 renewal approvalBypass=approved remains. 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 ​

Registration and recovery

Full SVG

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 ​

Execution and tasks

Full SVG

Task lifecycle

Task SVG

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 ​

CDC and alerts

Full SVG

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 ​

Plugin lifecycle

Full SVG

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.

Shutdown and limits

Full SVG

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.yml starts one Server, sidecar, dashboard, PostgreSQL and Redis. Host 8443 → container 19090 is 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.yml provides 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 / limitationTarget or unverified workTODO
One-hop owner routing / epochs; partial standalone fallbackAuthenticated interconnect, readiness and lease-loss removalARCH-003–005
SQL approvals wired with CAS decisions/claims (9066d7c10)Approval ticket TTL; renewal bypass re-reviewARCH-001/002
SQL page/task records; UI idempotency does not cover game effectsTask replay contract and real-game receiptsARCH-014/015, GAME-001
Scope validation; binding-driven physical routingOpen-phase budget and pool capacityARCH-006/009/010
Drain/shutdown wired; queued-task and total-deadline gaps remainDisconnect/drain/SIGTERM drill, force-close after graceARCH-018
SSH foundations; missing console relayRelay and playback UI; no automatic RDP/VNC expansionAGENT-002/003
SLP/protocol skeleton and plugin runtimeReal-account login-level acceptancePROBE-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/libraryRepository version/templateOfficial reference and checked scopeUnverified
Redisquickstart 7-alpine, floating tagXACK: removes acknowledged entries from the consumer group's PEL, not a downstream commitActual version, persistence/trimming and fault windows
HashiCorp go-plugingo.mod v1.8.0Official repository: child-process RPC with multilingual gRPC; this repository permits local gRPC onlyPlatform/language/real-protocol acceptance
PostgreSQLquickstart 15-alpine15 logical replication: publication/subscription and replication identity; pgoutput here requires source slot/permissionsSource publication/slot/WAL retention and actual version
MySQLgo-mysql v1.9.1, source version unknownMySQL 8.0 GTID: replication positioningMySQL/MariaDB flavor, permissions, retention and recovery samples
ClickHousedriver v2.43.0, template 23-alpineBatch behavior traced through worker.go/driver interface; no new product-selection studyServer compatibility/deduplication/durability: ARCH-012
Heraldv0.1.3-0.20261014084113-9875146dc50aRepository SDK/outlet calls are evidence of integration, not external deliveryTrigger 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.