Skip to content

feat: v5 - #227

Open
patrickleet wants to merge 601 commits into
mainfrom
v5
Open

patrickleet wants to merge 601 commits into
mainfrom
v5

Conversation

@patrickleet

Copy link
Copy Markdown
Collaborator

No description provided.

@coderabbitai

coderabbitai Bot commented Sep 6, 2026 •

Copy link
Copy Markdown

Walkthrough

Warning

Review details and warnings were omitted to fit the comment limit.

Agents get one skill for the game layer: plain Rust zones, facts settled
into cells (batched on celld), interest-managed replication with update
rates, and zones watching world cells as pushed read models.

[[world-scale-game-services]]
A watched neighbour room gave each observer the whole room from its
centre, so interest management stopped at the border. Clients now send
Focus {x, y} (tag 0x07, observers only) with the player's position in
the neighbour's coordinates; Zone::on_observer_focus recentres that
observer's view. Mob Pit applies VIEW_RADIUS, so interest and update
rates continue across rooms. JS: ZoneWatch.setFocus, throttled and
resent after reconnect.

[[observer-focus-neighbour-interest]]
A sink opted into batches by overriding both `FactSink::max_batch` and
`FactSink::commit_batch` (a host: `max_fact_batch` and
`dispatch_fact_batch`). Overriding only the size once batched a sink
through the default one-by-one `commit_batch`, which held settlements
back until the whole batch committed.

Now one override opts in and supplies the batch commit:
`FactSink::batches() -> Option<&dyn FactBatchSink>` and
`FactHost::fact_batches() -> Option<&dyn FactBatchHost>`, both `None`
by default. The feed batches only a sink that returns one (up to
`FactFeed::with_max_batch` / `ZONE_FACT_BATCH`); the rest get one fact
at a time. `DurableFacts`, `CommandFactSink`, `CelldObjectHost` and the
test sinks moved over; behaviour is unchanged. New test: a sink without
batches settles each fact as it commits.

[[zone-fact-batches]]
mobpit-recovery wakes N rooms with one bot each, waits for (or runs)
the kill, probes every room with real joins and reports when each
answered (p50/p90/max, per 10 s), then each room's ticks over a hold.
Bots record when their Welcome came (joined_after). Rooms report a
wake trace in /info: when the object was built, its first call, and
the awaited storage spans of its first wake and join.

[[celld-fleet-recovery-hops]]
`AggregateCell::dispatch_idempotent_batch` runs commands in order, each
exactly as `dispatch_idempotent` (own ledger entry, identity, session),
under one command guard and one alarm reschedule instead of one per
command. A rejected command leaves the earlier ones committed and the
later ones run; the first retryable result (in progress, 408, 429,
5xx) ends the batch; one result per command attempted.

The `__batch` wire moves to `distributed_game::cell::run_fact_batch`
(host-testable); `serve_cell` parses, calls it and drains the outbox
once. An entry that does not parse is answered in its place.

Each entry is still its own transaction: a handler runs between its
reservation and its commit, outside the synchronous cell SQL
transaction, and must see the entries before it committed.

Tests: a batch runs in order and replays as a whole; a rejected entry
leaves the others committed; a replayed `__batch` body answers only
replays and credits once.

[[zone-fact-batches]]
Mob Pit's crawler and presence cells used their own router, which took
`__batch` for a command name and answered 400. The object host only
fell back to one-by-one on 404, so it read that 400 as the first fact's
permanent refusal: a batch of kills for one crawler dropped its first
kill.

The cells now use `serve_cell`, and the object host sends the facts
one by one whenever the batch request as a whole gets a 4xx other than
408/429, so each fact gets its own answer.

[[zone-fact-batches]]
Plain integer counts that do not move with machine load, so A/B runs of
one build compare exactly: WorkCounters (records encoded per patch,
creates/updates sent, updates held by rates, Delta bytes, fact commands,
cell and __batch requests, outbox deletes, world reads and pushes) in
GET /zones/{zone}/info as `work`, with the switches in effect; watched
cells answer GET /{kind}/{shard}/__watchers with WatcherStats.

New A/B switches: ZONE_UPDATE_RATES=0, ZONE_WORLD_PUSH=0. The zone-side
reconcile schedule moves into world::watch::WorldSync, with a fake-clock
test that a reconcile repairs missed pushes within one period.

[[framework-work-counters]] [[zone-world-views-pushed]]
[[replication-encode-once-lod]] [[zone-fact-batches]]
Each step prints the rooms' and watched cells' work counters normalised
per room patch, room-second or room-minute; --ab VAR=VAL with --pairs N
alternates fresh-celld runs (A,B then B,A) and prints medians per side
and of the per-pair change. Skill and README "Checking your work".

[[framework-work-counters]] [[mobpit-zone-load-test]]
Fact rates follow the fighting, which moves with machine load; the
ratios are what a fact-batch A/B compares.

[[framework-work-counters]] [[zone-fact-batches]]
Hello offered only version 1 and decoders reject trailing bytes, so
Welcome could not grow and a new client message (Focus) made an old
celld zone close the connection: servers had to deploy first.

Servers (native net, celld zone object) now answer v1 or v2 in the
client's version (ZoneHost::speaking) and refuse others with
VERSION_MISMATCH "protocol ..." before the ticket is touched. Welcome v2
appends runtime features (bit 0 FOCUS) and the zone's world origin
(Zone::origin). The JS SDK offers 2, resends the same Hello once with 1
to a v1-only server (remembered per URL, not surfaced as an error) and
sends Focus only when FOCUS is announced. Golden fixtures cover v1 and
v2; PROTOCOL.md gains a negotiation section. Game surfaces keep
protocolVersion 1 (payload encodings are unchanged).

[[zone-protocol-v2-negotiation]]
Each game converted the player's position into every neighbour's
coordinates and called setFocus, and Mob Pit overrode on_observer_focus
only to use its view radius.

Zones now declare their world origin and player view radius once
(Zone::origin, Zone::view_radius); the default on_observer_focus gives a
focused observer that radius. The JS GameClient takes the player's
position with one call (setPosition(x, y, zoneId?), local to a zone or
world) and focuses every observed zone with an origin itself, also after
its Welcome; setFocus stays for unplaced zones. Mob Pit declares both
and drops its override; its client and the SvelteKit loop drop their
coordinate math.

[[zone-placement-auto-focus]]
[[zone-protocol-v2-negotiation]] [[zone-placement-auto-focus]]
celld holds a room's frames until the writes issued before them are
durable. A wake wrote the zone id, the status and the activity fact
before the first player's Welcome (and the join wrote the status
again), so under a recovery burst Welcomes waited on the bucket.

Now the wake only reads; the zone id is written once per zone, the
status only when it changed and in the same batch as the facts, after
the Welcome. Own celld node on the Hops RustFS, 150 fresh rooms:
wake joins 89 -> 150 of 150 in the ramp; after a SIGKILL p50 38 ->
16 s, p90 44 -> 31 s; 2709 -> 2157 txns shipped in recovery.

[[celld-fleet-recovery-hops]]
Probes and the staying bot reuse the room's principal (a reconnecting
player, not new Crawler and Presence cells per attempt), send the
game's content version, log why a wake bot was lost and count rooms
that lose their player again; t0 is when the socket dropped.

[[celld-fleet-recovery-hops]]
[[framework-work-counters]] [[zone-world-views-pushed]]

# Conflicts:
#	distributed_game/src/celld_zone/object.rs
The watched world views (f93b24a) added the `hood` and `borough` zone
messages; the generated client was not regenerated, so CI's
`game-client --check` failed in the game demos smoke job.

[[zone-world-views-pushed]]
Hood, borough and city are separate watched cells, so a waking room's
views arrive independently. The test waited for the hood tier only and
then asserted the borough count and city banner at once (failed in CI
and 2 of 3 local runs). Wait for each, and retry a polled tiers read
that fails while celld is busy.

[[zone-world-views-pushed]]
Same hood/borough messages as e487715; the SvelteKit copy of the
generated client was stale, so `npm run check:games` failed in CI.

[[zone-world-views-pushed]]
One tick of walking is exactly the 0.25 m bound (5 m/s over a frame of up
to 50 ms); crossing into the next room's coordinates adds f32 rounding,
so CI saw 0.251 m (also on #291). Bound 0.26 m: a real doorway jump is a
whole room or a visible snap.
A cell pushed each view once and logged only transport errors; a busy
zone's 5xx/429 went unnoticed, so it caught up only at its next
reconcile (45 ± 15 s). That is too late for a content rollout's freeze
(the content headless test timed out waiting for both rooms frozen in
CI). Retry after 0.25, 1 and 3 s on transport errors, 5xx and 429; a
zone answers every parsed push with 204, so other 4xx are not retried.

[[zone-world-views-pushed]]
feat(game): world-scale game services (watched views, fact batches, replication)
feat(game): Mob Pit through the framework gateway at /zones
fix(game): keep celld rooms smooth on a long-lived state
fix(game): stop celld dev stalling Mob Pit rooms
feat(game)!: Mob Pit world, fold demos in
feat(game)!: zones as celld objects, Mob Pit room grid
- `schedule` keeps the data types and a crate-private store trait; the
  worker, session vocabulary and guard move to `microsvc::schedule`
  and dispatch through `Service`, so they no longer need `graphql`.
  `ScheduleWorker::attach(repo, cfg)` replaces `with_schedule_worker`.
- `VerifiedPrincipal` lives in `command_dispatch` only.
- Durable Object clone/replace hooks are crate-private in `cell_host`,
  which also owns `cell_migrations()`. Game wording leaves core docs.
- `SurfaceSpec { id, contract, fingerprint }`: the contract is built
  once in `application/surface.rs` as a typed `SurfaceContract`
  (serde names, no dialect); the copies and the re-serializer that
  checked them are gone. Manifest schema version 3. `manifest.rs` is
  split into compose, canonical, validate and ownership.
- The schedule crash test again proves a crashed worker's claim holds
  until `claim_ttl` (injectable clock, settle-failing trigger), on
  SQLite and Postgres.

BREAKING: `graphql::VerifiedPrincipal` -> `command_dispatch`;
`schedule::{worker, schedule_session, schedule_guard, ...}` ->
`microsvc::schedule`; `SurfaceSpec` fields replaced by `contract`;
manifest schema 2 -> 3.

Implements [[tasks/v5-review-25]]
refactor!: core owns schedule data; manifest stores a surface once
Core gains a generic external read source extension point
(ExternalReadSource / ExternalReadExecutor) that owns selection, SDL,
contract, manifest, envelopes and @LiVe refresh via ChangeHub. Sorted-set
leaderboards move to their own crate on top of it.

BREAKING CHANGE: distributed::leaderboard is gone (use
distributed_leaderboard); BackgroundLeaderboard and the
leaderboard-background feature are deleted; the redis feature is now
redis-streams; GraphqlEngineBuilder::leaderboard becomes
external_read_source(LeaderboardRoots); LeaderboardChangePublisher::spawn
takes a capacity (overflow coalesces to one every-board notice); manifests
list leaderboards under "external": {"leaderboards": [...]}.

Implements [[tasks/v5-review-25]]
…ard-crate

refactor!: move leaderboards into distributed_leaderboard
Native and worker gateways now drive one sans-IO LiveCoordinator,
FlightTable, origin verdict and GraphQL-WS codec; adapters keep locks,
timers, sockets and spawning. The worker implements GatewayAdapter and
gains a Zones binding. Drift resolved fail-closed in one place.

BREAKING CHANGE: Authorization sent as several fields or containing a
comma is rejected (401) on both adapters; one hop rule (508 at >=8
incoming hops or >1024 bytes); worker validation failures are HTTP
502/503 responses instead of errors.

Implements [[tasks/v5-review-25]]
A plain YAML scalar ending in "gateway::" parses as a mapping key, so
the workflow failed to load.

Implements [[tasks/v5-review-25]]
Row budget is the product of resolved page limits, checked per root
field against max_rows before SQL runs; engine and CLI share the cost
functions. CompileError/ExecuteError replace substring classification.
One execute_plan generic over the backend: Postgres opens the read-only
transaction and sets the timeout in one round trip (5 -> 3 per root
field). GraphqlEngine::plan replaces sentinel-error plan capture;
PROOF_TABLES comes from the projection store; manifests are borrowed on
request paths; the root_field metric label is the schema field.

BREAKING CHANGE: max_complexity becomes max_fields and max_rows
(default 200,000) is new; the manifest execution shape and every schema
fingerprint change; "query too complex" is now "row budget exceeded";
client_application_surface_with_schema_roles and
surface_for_application_contract are renamed; graphql_sdl_from_schemas
and core_sdl_for_catalog are removed.

Implements [[tasks/v5-review-26]]
One producer loop (src/graphql/subscribe.rs) drives catalog live roots
and external read roots. Subscribers whose read compiles to the same
(role, SQL, binds, cache scope) share one execution per change; each
keeps its own hash gate, envelope and resume-exact catch-up. Live
executions are capped per engine (live_concurrency, default 8); slow
subscribers skip to the latest frame instead of stalling others; the
entry is torn down with its last subscriber. 100 subscribers: 100 -> 1
execution per change.

BREAKING CHANGE: live_subscriber_count counts producers (distinct
reads), not subscribers; an external root's failed first read ends the
stream instead of failing the subscription future.

Implements [[tasks/v5-review-26]]
…delivery

refactor!: share gateway live/delivery core across adapters
refactor!: one GraphQL row-cost model, typed errors, one executor
Origin sharing made live_subscriber_count count producers, so the
gateway load test (CI-only, ignored) saw 1 origin subscription instead
of 100 in the non-sharing modes. live_producer_count now counts shared
reads and live_subscriber_count counts streams; the load test asserts
the gateway's savings on subscriptions and one origin producer in
every mode.

Implements [[tasks/v5-review-26]]
Removes source-grep, constant, self-compare and pre-release upgrade tests
and sagas/orchestration; replaces macro expansion-string tests with
runtime suites; moves the brittle rustc-pinned snapshots into a
substring-asserting rustc_fail harness; replaces wall-clock assertions
with ordering or paused time; PostgresTestSchema drops its schema on
drop; framework checks living in e2e-ui move into the framework.

Implements [[tasks/v5-review-27]]
…ring

feat!: share live GraphQL refreshes across identical subscriptions
…ning

test: delete cannot-fail tests, make macro and timing tests behavioural
A tests/common dev-dependency crate holds the single Todo aggregate,
read models, sessions, TempDb, PostgresTestSchema, env helpers and the
conformance suites. Repository, lease, lock and schedule contracts run
one identical case list per backend; exclusions are named capabilities
that must be stated explicitly. The #[path] support idiom is gone from
tests/. typed_commands fixtures use projection!/mutation! and assert
typed error kinds (GraphqlServiceBindError is now an enum).

Implements [[tasks/v5-review-27]]
test: one tests/common crate and backend conformance suites
Postgres timestamps went through f64 epoch seconds both ways
(`to_timestamp($n)` and `EXTRACT(EPOCH ...)::double precision`). At
present-day magnitudes an f64 resolves only about 240 ns, so a
scheduled outbox message's `deliver_at` read back about 76 ns off even
for a whole millisecond.

The Postgres backend now carries timestamps as i64 microseconds, the
resolution `timestamptz` stores: writes are `TIMESTAMPTZ 'epoch' + $n *
INTERVAL '1 microsecond'` and reads are `(EXTRACT(EPOCH FROM col) *
1000000)::bigint`, both exact on Postgres 14+. `push_timestamp_cmp`
takes a `SystemTime` so each backend encodes it exactly. The scheduled
outbox conformance case asserts equality again instead of a 1 ms
tolerance.

Resolves [[incidents/postgres-outbox-deliver-at-precision]]
Implements [[tasks/v5-review-28]]
`TypedCommandContract::canonical_value` validated the contract's
domain-event projections with `.expect`, so a hand-built or
deserialized contract carrying declaration errors panicked deep inside
fingerprinting.

`canonical_value` and `fingerprint_bytes` now return `Result`.
`CommandSpec::from_contract` validates projections, so registration
fails through its existing "typed command contract cannot compile"
path, and binding a GraphQL service maps the error to
`GraphqlServiceBindError::InvalidInventory`. A direct-projection bind
that fails leaves the registered contract unchanged.

Resolves [[incidents/typed-command-canonical-value-panics]]
Implements [[tasks/v5-review-28]]
The root crate built 81 integration test binaries, each relinking the
whole crate. They are now eight area binaries (core, repositories,
read_models, graphql, gateway, transports, services, observability);
each former target is a module, so `--test <name>` becomes
`--test <group> <name>::`. Same 2,277 tests, name for name.

Relinking after touching src/lib.rs drops from 57.7 s to about 13 s.
Process-global state was audited: the metrics recorder shares a binary
only with otel_export, which records none; no test sets env vars or a
global subscriber. Every CI and Makefile `--test` invocation is
rewritten and selects the same tests as before (listed per job in the
PR). The coverage job gets rust-cache.

graphql_query_protocol is gated on gateway-graphql-native, the feature
its load module always needed.

BREAKING CHANGE: integration test target names changed; use
`cargo test --test <group> <old_name>::`.

Implements [[tasks/v5-review-27]]
The reference app's identity path wrote `auth_users` twice: the scrape
upserted the row directly and also published the event a hand-written
projector (dispatching on `name.contains("deactivated")`) applied
again. It also hand-wrote HTTP routes with a copied
`session_from_headers` that put every request header into the session.

- `publish_external(source, event)` on the causal command context and
  commit builder publishes a typed fact whose identity is its external
  source. It commits with the ledger receipt and carries its causation,
  so `projection!` projects it like an aggregate event. `AUTH_USERS` is
  now declared with `projection!` and a mutation program, like TODOS.
- `Service::with_http_command(command, edge)` exposes one command at
  `POST /{command}`. The edge authenticates from headers and body and
  returns the command id, input, session and principal; nothing else
  from the request reaches the command. `command_router` mounts only
  exposed commands, and `command_gateway_routes` sends every command
  path to the service, so an unexposed one is a 404, never the UI.
- `RepositoryError::DuplicateOutboxMessageInBatch` is renamed
  `DuplicateOutboxMessage`: one message id repeated in a batch or
  already committed.

Deleted from e2e-ui and e2e-celld: `project_auth_user`, the direct
`auth_users` upsert, `publish.rs`, the hand-written ingress and scrape
routes, `session_from_headers` and the closed-route loop.

BREAKING CHANGE: `DuplicateOutboxMessageInBatch` is renamed; the two
Zitadel commands answer the wait-path shape (`{payload, receipt}`).

Implements [[tasks/v5-review-28]]
fix: exact Postgres timestamps; no panic on invalid command projections
…aries

test!: consolidate integration tests into eight binaries
feat!: typed external facts and per-command HTTP edges

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant