Compare commits

..

627 Commits

Author SHA1 Message Date
Josh Creek c02aad66a0 fix(ui): keep menu content reachable at any window size
The main menu clipped its own title and bottom button in debug builds. The
project lays out in a hard-fixed 1920x1080 logical viewport
(window/stretch/mode="viewport"), and the only overflow strategy in the
scene was a CenterContainer, which centres its child rather than clipping
and scrolling. With DevSection visible the content measures 1133px against
1080, so roughly 53px spilled off both ends with no way to reach it — and
main_menu.gd grabs focus on a button that may itself be off-screen.

Worth recording because it is counter-intuitive: this is not
resolution-dependent. Because the viewport is fixed, a 4K display magnifies
the same clipped 1080p frame rather than giving the menu more room, so the
fix has to make the layout scroll, not scale.

Each menu is now MarginContainer > ScrollContainer > CenterContainer >
VBoxContainer. ScrollContainer sizes its child to max(own size, child
minimum), so an expanding CenterContainer keeps today's centred look when
the content is short and grows past the viewport when it is tall — which is
exactly when scrolling should start. follow_focus is on so keyboard and
controller navigation cannot strand focus off-screen. Lobby and matchmaking
share the same shape and get the same treatment before they hit the same
wall; settings gained its wrapper alongside the Controls tab.

Also stops the dev bot dropdowns widening the whole menu: they are filled
from res://bots filenames and expand horizontally, so a long checkpoint
name dragged the layout past its 420px minimum.

test_menu_layout asserts each screen's bottom-most control really sits
inside a ScrollContainer. That is a structural guard against the wrapper
being removed or a new section being added outside it — not proof that
nothing visually clips, which was checked by hand at 1000x600, 1280x720 and
1920x1080.
2026-09-06 20:41:41 +01:00
Josh Creek 076d27a564 feat(input): full controller support, rebindable controls, and rotation fixes
Playing with a gamepad did not work: all six move_* actions had no joypad
event at all, so a pad could yaw/pitch/roll/turbo but could not translate.
Nothing caught it because every action existed and the game booted fine —
no assertion checked that an action is reachable on *both* devices.

Controller layout, on the 6DOF convention (left stick aims, right stick
translates), using all six of the pad's analog axes for the ship's six
degrees of freedom:

  left stick   yaw + pitch        right stick  strafe + vertical
  LB / RB      roll               RT / LT      forward / back
  L3           turbo              R3           ball camera

Input is now read with Input.get_axis instead of is_action_pressed, so
triggers and sticks are proportional. Keyboard values are unchanged.

Three rotation bugs found by measuring a real Ship rather than reading the
code:

- apply_torque() is world-space and the torque was never rotated into the
  hull's frame (unlike thrust, which uses -ship_basis.z). Roll input became
  pitch after a 90 degree turn and inverted at 180, so the controls were
  correct flying up-field and backwards flying back.
- ship.tscn's inertia is Vector3(7, 1, 7) but a flat torque was applied to
  every axis, giving yaw 7x the angular acceleration of pitch and roll
  (172 deg/s vs 52). Torque is now scaled per-axis by inertia, so
  rotation_acceleration means rad/s^2 and all three axes match. Yaw is
  unchanged.
- pitch_down pitched the nose UP: get_axis's arguments were reversed, so
  the I/K keys and the stick each did the opposite of their label.

Menus were unusable on a pad for a separate reason: Godot 4.7 gives
ui_up/down/left/right joypad events by default but leaves ui_accept and
ui_cancel with none (verified against a pristine project), so a controller
could move the highlight and never press anything. A confirms and B goes
back. Gameplay exits on a new leave_gameplay action (Escape / Start) rather
than ui_cancel, so carrying B for menus cannot abandon a live match.

Bindings for both devices are rebindable in Settings -> Controls, persisted
to user://input.cfg — a separate file from settings.cfg because
VideoSettings.save() rewrites that file wholesale and would drop any
section it does not know about. project.godot stays the source of truth for
defaults; overrides are only ever a delta on top of a boot-time snapshot.

Verified: 268 unit tests, the ENet integration gate, and a 16-sample
before/after comparison of networked prediction residuals showing the
physics change does not regress them (median 0.083m -> 0.065m).

Note for follow-up: every policy in Game/bots/ was trained against the old
sluggish, world-axis rotation and will over-rotate until retrained.
2026-09-06 20:41:20 +01:00
Josh Creek 00b900d864 Merge pull request #30 from jcreek/feat/multiplayer
Feat/multiplayer
2026-09-06 10:58:50 +01:00
Josh Creek fe453ab607 docs: add a version inventory to TECH_STACK.md, refresh stale claims
TECH_STACK.md explained why each choice was made but never listed what is
actually pinned, so there was no single place to answer "what version of X do
we use". Adds a Version inventory section covering the shipped game, the Go
control plane's four direct dependencies, the datastore/platform versions and
the exactly-pinned training stack, plus a Verification toolchain subsection for
the Make/Docker/kind/Kustomize/Actions harness.

Also corrects two things the doc had outgrown: the allocation pipeline is now
wired end to end and gated in CI, so only the provider deployment remains; and
the Steam section covered only the GodotSteam client transport, omitting the
server-side Web API ticket verifier in server/steam.
2026-09-05 23:16:10 +01:00
Josh Creek 52cc478b38 docs: record the assertion-first debugging habit, and refresh CLAUDE.md
Adds the lesson this branch paid for repeatedly: the expensive failures
were not broken behaviour but assertions that could not distinguish the
two states they implicitly claimed to, each reporting its own ambiguity
as a confident verdict about the system under test. Waiting on a Fleet
field that does not exist, treating not-yet-started as exited, a p99
that conflated regression with scheduler noise, a validator reading a
response shape Agones never sends, and a build guard that verified stale
code. Five in one session, several costing multiple CI round trips.

Two habits go with it, both of which beat reading code every time they
were tried: make the script report what it saw before theorising about
why, and verify the diagnostics actually fire -- two dumps were added
here and neither ran, one suppressed by a reachability guard and one by
an ERR trap that cannot fire inside functions without errtrace.

Also fixes two stale claims and one gap. Audio is no longer "none at
all"; a procedural AudioManager covers UI, countdown, impact, goal and
engine cues, and only authored assets remain. Five docs/ contracts that
server/security asserts against the manifests were unlisted. And the Go
control plane -- a third of the codebase and the current focus -- had no
structural description at all, so it now gets one: package layout, which
binary is test-only, and the three things easiest to get wrong
(integration tests hidden behind a build tag, start-time config, the
versioned wire contract).

TODO.md's entry now points at its ordered backlog rather than describing
it as deferred non-multiplayer work.

Every factual claim in the new section was checked against the tree.
2026-09-05 23:10:06 +01:00
Josh Creek 4ea72be581 fix(compose): stop calling a still-starting game server dead
Allocated Compose failed on a docs-only commit, so nothing functional
had changed. Its own diagnostics showed why: the game server logged a
clean `server_started` -- the exact string the readiness loop waits for
-- and the script reported "game server exited before becoming ready".

The guard asked whether the service was absent from
`compose ps --status running`, which is also true of a container that
has been created but has not started yet. On a slow runner the first
poll can land in that window, and the script concluded the server was
dead when it was still coming up. Ask whether it actually exited
instead.

Also set errtrace. This failure produced no "failed at line N" report
despite the ERR trap added in 432e5a11, because a bare `trap ... ERR`
does not fire inside functions or subshells without it -- the
instrumentation had a blind spot exactly where a readiness loop lives.

The other --status running check, after an explicit `compose stop`, is
correct and unchanged: stop is synchronous, so absence there really does
mean stopped.

Verified by two consecutive local runs.
2026-09-05 23:00:03 +01:00
Josh Creek 4560d2de8a docs: say what order the outstanding work goes in
The backlog listed what is left but not what to do first, and priority
labels do not answer that: #33 is P2 yet belongs before the P0 cluster,
because standing the cluster up first means migrating a running one
afterwards.

Add an explicit ordering to TODO.md in three parts -- a critical path
where each item unblocks the next, a Steam track that runs in parallel
and should start early because its lead time is Valve's, and the set
that is unblocked today and waiting on nobody. The playtests, training
runs and asset work need no cluster and could start now, which was not
obvious from a flat list sorted by priority.

#31 is called out as the highest-leverage item: two answers unblock the
whole of Phase 8, and the work behind them is an agent's.

Two open issues were in no list at all -- #23's design question and
#32's backfill work -- so TODO.md now covers every open issue.

Also record the dependency direction on GitHub rather than only here:
#17, #32 and #33 carried no blocked-by statement, so the graph was
invisible from the issue tracker. And note in §7 task 8.12 why the
workload namespace enforces privileged and where the split is tracked.
2026-09-05 22:50:26 +01:00
Josh Creek 4912837dd7 docs: narrow what #31 actually needs from a person
The issue read as broadly human-gated. Most of it is not: GHCR accepts
the built-in GITHUB_TOKEN with packages: write for the repository's own
namespace, so publishing needs no account, stored secret or spend
approval, and signing and tagging policy can land as a reviewable
default rather than waiting on a decision.

Two things genuinely block. Every manifest references
ghcr.io/cosmic-clash/*, and no such organisation exists -- the API
returns 404 and it is not among this account's orgs -- so nothing can be
pushed there. And this repository is private, so GHCR packages inherit
that, while no manifest declares imagePullSecrets; public packages work
as written, private ones need pull secrets threaded through every
workload.

Same optimistic-to-pessimistic drift the §7 audit found in fifteen other
entries: work described as blocked on a person when the person only owes
a decision.
2026-09-05 22:45:26 +01:00
Josh Creek aac00f148e fix(tests): stop the ENet residual gate failing on host scheduling noise
The client-bot smoke asserted remote_residual_position_p99 < 0.3. Commit
52ee1810 both passed and failed on that assertion, in runs three seconds
apart on identical code: two clients in one run reported 0.324 and 0.187
with matching snapshot counts, scores and slot checks.

A p99 over a few hundred samples is its worst handful, so on a shared CI
host it measures how often the process was descheduled as much as how
well the interpolator tracks. Locally the same test reports p95 0.025m
and p99 0.081-0.149m; CI's p99 runs 2-4x higher on a healthy build,
which is the entire margin the 0.3 bar had.

Assert two bars instead of one. The tight numeric bar moves to p95,
which is stable run to run, and p99 is bounded by the product's own
REMOTE_VISUAL_MAX_OFFSET/REMOTE_VISUAL_MAX_ROTATION_DEGREES: past those
the visual smoother stops absorbing a correction in a single step, so
exceeding them is a real defect rather than a slow runner. Referencing
the constants also means the test follows the product if that tolerance
is ever retuned.

This is a genuine trade, not a free win: a regression that pushed p99
from 0.2 to 0.35 while leaving p95 healthy now passes where it once
failed. That band is exactly where the noise lives -- 0.324 was observed
on a healthy build -- so the old bar could not tell that regression from
a busy runner either, and paid for the ambiguity with false reds.

Both percentiles are printed with their bars so a future failure shows
which one moved.

Checked first whether goal-driven kickoff teleports were polluting the
metric; they are not. Both the ship and ball paths already skip
accumulation across a reset_gen change.
2026-09-05 22:22:30 +01:00
Josh Creek 52ee181042 fix(kind): validate the allocation response Agones actually returns
With the Fleet readiness wait corrected, the gate reached the allocation
check for the first time and failed with "allocation did not return a
GameServer" -- while the cluster dump shows the allocation plainly
succeeded: one GameServer Allocated, Fleet reporting ALLOCATED 1.

GameServerAllocationStatus is flat: state, gameServerName, address,
ports, nodeName. It does not embed the allocated GameServer. The
validator read status.gameServer.metadata.name and
status.gameServer.status.{address,ports}, a shape Agones never sends,
and its unit tests asserted that same invented shape -- so validator and
tests agreed with each other while both disagreed with Agones. Nothing
caught it because the gate had never once allocated anything.

Read the real fields, keeping every existing check: non-empty name,
address neither blank nor unspecified, exactly one named "game" port in
range.

Also print the response body when validation fails. work_dir is removed
by the EXIT trap, so a shape mismatch was otherwise invisible from CI --
which is how this survived. If the shape is still not what I expect, the
next run says so instead of costing another round trip.
2026-09-05 22:03:41 +01:00
Josh Creek 4f48f0a6a8 fix(kind): wait on the Fleet field that exists
The gate asserted `--for=jsonpath='{.status.ready}'=2`. An Agones Fleet's
status carries replicas, readyReplicas, reservedReplicas and
allocatedReplicas -- there is no `ready` -- so the wait could never match
however healthy the Fleet was.

It failed in the most misleading way available: as "the Fleet never
became ready", which sent three separate investigations after the game
server. Two of those found genuine bugs, but the gate would have stayed
red with both fixed.

The evidence is in the previous CI run's own dump, which the new
per-container diagnostics produced: both GameServers Ready and stable for
5m6s, and the Fleet reporting DESIRED 2 / CURRENT 2 / READY 2, while
kubectl wait timed out beside it. That same dump also confirms the health
fix in 0de97381 worked -- those GameServers had been churning every ~20s
before it.

Assert the corrected jsonpath in test_fleet_manifests.py and reject the
old one, alongside the build-by-default behaviour, so neither silently
regresses.
2026-09-05 21:55:20 +01:00
Josh Creek 0de97381b7 fix(agones): stop a dead health loop from passing as a healthy server
Every allocated GameServer reached Ready and was recycled by Agones ~20s
later. Health pings are the game process's job by design -- the
supervisor has no health implementation at all -- so a server that stops
pinging is exactly what Agones is built to reclaim.

start_health() armed a Timer on a node that might not be inside the
SceneTree. A Timer only ticks inside the tree, so the node reported
itself configured, sent nothing, and said nothing about it. It now
returns a bool, refuses loudly when unconfigured, and defers to _ready()
when called before parenting, so the SDK arms its own timer and no
caller has to get the ordering right. server_boot.gd defers the add like
every sibling does (§9 gotcha 27) and logs when AGONES_SDK_HTTP_PORT is
missing, which previously read identically to a healthy start.

Also bounded the in-flight latch: it is set across an await, so a request
that never completes would silence health permanently. Defence in depth
rather than an observed fault.

Tests target the contract rather than the mechanism: a test that parents
the SDK correctly and asserts pings passes with the bug present, because
the defect was in the wiring. The unit tests assert start_health()
cannot claim success out of tree, and were confirmed to fail against the
previous code. The smoke gains a counting sidecar and asserts a
*repeating* ping -- it reports "health pings in 3.0s = 1, want at least
2" when the loop is broken, which is the production symptom exactly. It
is also now actually run: nothing referenced it before.

Two diagnostic fixes, both of which changed conclusions during this work:

The kind gate only built the game-server image when the tag was absent,
so a local rerun silently verified whatever was built last. That is why
local runs and CI disagreed about the same commit. It now builds by
default, with KIND_REUSE_GAME_SERVER_IMAGE=1 as the opt-in fast path.

The failure dump logged only not-ready pods, and used --all-containers
with a shared tail. A GameServer recycled after reaching Ready leaves no
unready pod behind, and the Agones sidecar out-logs the game server, so
the relevant output was never captured. It now dumps every pod, per
container, current and previous, plus the GameServer and Fleet resources
-- Agones' own state machine is what rejects these.
2026-09-05 21:35:50 +01:00
Josh Creek ca70568fad fix(agones): make the kind gate's Agones lifecycle actually work
Several independent causes, all of which had to be right before the
Fleet could reach Ready.

The supervisor pointed --sdk-base-url at 127.0.0.1:9357, which is the
Agones sidecar's gRPC port; its HTTP surface is 9358, and that is what
AGONES_SDK_HTTP_PORT carries and what agones_sdk.gd reads. An HTTP
client against the gRPC port could never have worked, in kind or in
production.

The supervisor also treated the sidecar's first incomplete /gameserver
response as fatal. The sidecar accepts requests before the controller
populates status.address and status.ports, so this produced a restart
loop precisely during normal Agones startup. It now polls until the
endpoint is assigned or ReadyTimeout elapses.

server_boot.gd started ServerControl and the Agones SDK only under
--allocated-mode, but the kind smoke deliberately strips that flag, so
nothing served the readiness probe and the GameServer could never become
Ready. Lifecycle now keys on AGONES_SDK_HTTP_PORT, which Agones injects
into every managed container, while allocation and roster semantics stay
tied to --allocated-mode. The SDK node is added to the tree
non-deferred, since start_health() creates a Timer immediately.

Fleet: Agones assigns its own SDK service account and masks that token
from the game container while keeping it for the injected sidecar, so
the manifest must not pin serviceAccountName or
automountServiceAccountToken. Godot stores user:// under HOME, so HOME
points at the writable runtime volume to keep the root filesystem
read-only, and fsGroup makes that volume writable for the non-root user.

Namespace: Agones' Dynamic port policy injects a hostPort, which both
the baseline and restricted Pod Security Standards forbid, so the
workload namespace enforces privileged while continuing to audit and
warn against restricted.

NetworkPolicy: the injected sidecar reaches the Kubernetes API over
HTTPS, and NetworkPolicy applies to the whole Pod rather than to the
container whose token was masked.

The kind runner creates the namespace before Helm so Agones can install
its per-namespace SDK RBAC, scopes gameservers.namespaces to it, forces
the allocator and ping Services to ClusterIP because LoadBalancer
ingress never becomes ready in plain kind, and labels the node so the
production Fleet's on-demand/zone constraints are exercised rather than
edited out of the rendered manifest.
2026-09-05 20:50:01 +01:00
Josh Creek 8aa4af3a3a test(kind): always dump on failure, and record the second Agones failure
The dump added in 9ab1bec8 never ran. A `kubectl cluster-info`
reachability guard suppressed it, so its first exercise produced exactly
the silence it was written to prevent. Every command inside is already
`|| true`, so the guard bought nothing and cost the whole dump; removed.

That run did establish something the CI logs cannot: after clearing
local Docker pressure, the Agones install completes cleanly (controller
and allocator both reach "condition met") and the gate instead fails
later, waiting for the Fleet's game-server pods to become Ready. CI
never reaches that point because the Agones install times out first.

So there are likely two failures stacked, and fixing the CI timeout will
probably expose the Fleet one. Recorded in AGONES-CI-INVESTIGATION.md
along with the reasons the Fleet failure warrants suspicion -- fleet.yaml
changed its join-signing key mount from raw bytes to a JSON map this
branch -- and the reasons it may be unrelated.
2026-09-05 20:03:16 +01:00
Josh Creek 9ab1bec89a test(kind): dump cluster state before the Agones gate deletes its cluster
This gate fails with nothing but Helm's "context deadline exceeded" and
three Deployments reporting Available: 0/1, then the EXIT trap deletes
the cluster -- so there is no way to learn why the pods never became
ready. Both CI runs and a local run are equally uninformative.

Dump node capacity and conditions, pods and recent events for
agones-system and cosmic-clash, and describe plus current/previous logs
for every not-ready pod, on any failure and before deletion. Events
matter as much as pod status here: FailedScheduling, ImagePullBackOff
and probe failures are all invisible in a status column.

KIND_KEEP_ON_FAILURE=1 retains the cluster for interactive inspection.

Same approach that just found the allocated-Compose cause, where a
silent assertion had hidden a real 422-instead-of-409 API bug across
several CI runs.
2026-09-05 19:57:05 +01:00
Josh Creek 14da286e11 fix(store): return 409 for idempotency key reuse, not 422
Both idempotency paths returned a bare fmt.Errorf, and writeDomainError
maps anything it does not recognise to its 422 "invalid_request"
default. So reusing a key with a different payload answered 422 where
openapi.json declares 409 and state-transitions.json requires
"reject_conflict_without_state_change".

That is the difference between "your request was malformed" and "that
key is taken". A client acting on 422 would rewrite a request that was
never wrong, and the 409 branch of every generated client was
unreachable.

Wrap domain.ErrConflict on both the create and mutate paths, and add an
integration test covering identical replay and conflicting reuse.

Pre-existing: both bare errors are unchanged from 089c127c, which is why
verify-allocated-compose failed in CI before this branch's work as well.
Found only after adding the diagnostics in 432e5a11 and fc2f5c86 --
until then the assertion aborted silently and three CI runs reported
nothing but "make: *** Error 1".
2026-09-05 19:30:41 +01:00
Josh Creek fc2f5c8669 test(compose): report the actual status when the idempotency conflict check fails
The ERR trap added in 432e5a11 located the CI failure at the
`[[ "$conflict_status" == 409 ]]` assertion, but the request discarded
its body and the assertion printed nothing, so three failing runs never
revealed what the API actually returned.

Print the status and body on mismatch.
2026-09-05 19:27:35 +01:00
Josh Creek 432e5a11e8 test(compose): make the allocated smoke explain its own CI failures
This suite fails on GitHub Actions while passing locally, and it failed
the same way at 089c127c -- the branch head before any of this branch's
recent work -- so it is pre-existing rather than newly broken.

Diagnosing it is currently impossible from CI alone. The script is
mostly `curl -fsS` and bare [[ ]] assertions under `set -e`, all of
which abort with no output, so the run log contains nothing but
"make: *** Error 1". Both failing runs are equally silent.

Add an ERR trap that reports the script line and the failing command,
and dump `compose ps` plus the service logs on any non-zero exit rather
than only when COMPOSE_KEEP_ON_FAILURE is set. The next CI run should
therefore say what actually broke instead of needing another round trip
to find out.

No behaviour change on success; the target still passes locally.
2026-09-05 19:19:45 +01:00
Josh Creek 707aea5898 docs: mark the 8.48 Compose fixture item done
compose.allocated-smoke.yml and verify_allocated_compose.sh are already
independent of compose.phase6-smoke.yml -- the script says so explicitly
and reuses none of its ports -- so the allocated-mode flow no longer
inherits that fixture's hardcoded port, first-come slots or
--max-matches=2.

Fifteenth stale backlog entry found this session, and the first in
TODO.md rather than multiplayer-next.md §7. It was also the only
remaining item marked agent-actionable.
2026-09-05 18:21:51 +01:00
Josh Creek 8ba045063d fix(compose): give the allocated smoke's allocator its signing key
Making cmd/allocator refuse to start without join-signing material was
right -- an allocator that binds allocations it can never publish rosters
for strands every match silently -- but I updated the Kubernetes
manifests and the kind fixture without updating the Compose one. The
allocator container exited at startup, so no allocation was ever bound
and verify-allocated-compose failed with "allocator did not bind a
provider allocation".

Mount the same join-signing-keys.json fixture the game server already
uses and name the key it was written with. Caught by running the target
locally rather than by CI after a push.
2026-09-05 18:19:56 +01:00
Josh Creek 654f20e28f docs: record the backfill roster-delivery decision and remaining work
A backfilled player's join authorisation is issued after their server
started, but the supervisor fetches the roster once before launching the
game child and the game process has no reload path, so backfill cannot
work end to end regardless of how good the selection rule is.

Decided: the control plane marks the roster changed, the supervisor
re-fetches and rewrites the roster file, then signals the game process to
reload. Chosen because it reuses the authenticated channel and roster
endpoint that already exist -- no inbound path into the game pod, no new
trust boundary -- and keeps the roster an allowlist the server was told
to expect rather than admitting anyone holding a valid signature.
Signature verification is untouched and already binds match, server, slot
and generation.

Recorded in docs/MATCHMAKING.md, which the repo treats as the design
source of truth, so the decision is not re-litigated from a task row.
Remaining implementation is tracked in #32 and summarised in §7 8.19.
2026-09-05 18:09:10 +01:00
Josh Creek 1becfb4f3f feat(domain): add casual backfill candidate selection
First slice of task 8.19. docs/MATCHMAKING.md specifies the choice
precisely -- "the oldest ordinary casual ticket that meets the same
build, region <=100 ms and current anchor-tolerance rules for the
vacated human slot; ties use ticket ID" -- and that rule is needed
whatever is decided about delivering a late authorisation to a running
server, so it is worth landing on its own.

Kept a pure function over an already-fetched candidate set: the choice
is then reproducible and testable without a database, and claiming the
ticket stays a durable transaction as it is for ordinary proposals. Ties
break on ticket ID rather than scan order, so two replicas evaluating
the same queue cannot offer one slot to different players.

Region matching is stricter than ordinary formation: the server already
exists in one region, so a candidate must have RTT evidence for that
region specifically, not merely share some region with the others.

Eligibility is re-checked here as well as at the durable boundary, so an
ineligible mid-play or human-occupied slot never reaches selection at
all. Ranked is refused outright.

Corrected a comment I had written claiming the backfill window is
shorter than an ordinary proposal's; both are 10 seconds. What makes a
backfill offer separate is its payload and the absent decline penalty,
not its timing.

This does not yet make backfill work end to end -- see the roster
delivery question raised alongside this commit.
2026-09-05 17:32:49 +01:00
Josh Creek 61a073099d fix(store): widen the serializable retry budget, stop leaking test volumes
Two things that made the integration gate untrustworthy.

The retry budget was too small for expected contention.
TestPostgreSQLConcurrentIdenticalResultSubmission fires five identical
concurrent submissions and requires all five to succeed; it failed 4 runs
in 20. The error was retryable and retries did fire -- three attempts
simply was not enough. Contention here is normal rather than
exceptional: several game servers can submit results, and several
matchers can claim candidates, against the same rows at once. Raised to
five attempts, which is 0 failures in 40 runs.

Also jittered the backoff, but measured rather than assumed: my first
theory was a thundering herd, since the delay was exactly
RetryBackoff*(attempt+1) and every loser of a race woke at the same
instant. Isolating the two changes showed jitter alone moved 4/20 to
3/20, while the budget alone reached 0/20. The budget was the real
constraint. Jitter is kept because it costs nothing and its benefit
grows with the number of contending writers -- production is not capped
at five -- but the comment now says plainly that it is the smaller half,
so nobody inherits my wrong explanation.

Second, the integration scripts leaked one throwaway database volume per
run. --rm does reclaim anonymous volumes on a normal exit, but these
scripts force-remove the container from a trap, and `docker rm -f`
without -v keeps the volume. Sixty-four accumulated during this branch
until PostgreSQL stopped starting, surfacing only as the scripts' own
readiness timeout rather than as a disk error -- which is what the
"Docker storage exhausted locally" notes were really describing.
Measured at one volume per run before, zero after, across all five
scripts.
2026-09-05 17:14:43 +01:00
Josh Creek a1f30f6af9 test(store): prove the audited claims instead of asserting them
The audit established which rows understated what was built by locating
implementations and their call sites. That proves code exists, not that
it works, so each corrected claim is now tied to an executable test.

Seven of the nine were already covered and just needed naming: the
allocated ServerConfig fields, signed-authorisation admission, endpoint
wiring, casual lineup being reached through formation, three of the four
penalty kinds, signed roster metadata, the season countdown, and the
matcher deployments.

Two had no proof at all:

- INITIAL_CONNECT_NO_SHOW was the one penalty kind with no integration
  coverage, so "all four penalty kinds are written durably" rested
  entirely on reading the code.
- Cross-replica revocation is a behavioural property. An in-memory cache
  in front of the session read would break it while leaving every call
  site looking correct, so no amount of reading establishes it.

Writing the first one found my own error rather than a defect: casual
deliberately waits past InitialConnectWindow to CasualBotStartAfter
before deciding a no-show, giving a slow-loading player longer than the
ranked deadline. Reconciling at the earlier window only yields WAIT.

Both new tests were mutation-checked -- removing the penalty insert and
removing the revoked_at check each make them fail -- so they assert
something real rather than passing incidentally.
2026-09-05 17:07:05 +01:00
Josh Creek 8033d52db3 docs: audit every Phase 7/8 task row against the code
Three tasks in a row this branch turned out to be partly built already:
8.20's allocation wiring was complete end to end, 8.22's client UI was
built, and 7.4/8.7 listed durable ban storage and the Steam adapter as
outstanding after both had landed. That is a systematic problem, not
three coincidences, so this checks all 56 rows rather than fixing them
one at a time as they are picked up.

Nine more rows understated what exists:

- 8.6  every allocated-mode ServerConfig field is present, signed
       authorisation admission is in MatchNet, endpoint wiring is in
       AssignmentState
- 8.8  distributed revocation needs no cross-replica protocol: sessions
       are durable and read on every authenticated request
- 8.19 casual lineup formation is built and wired, and all four penalty
       kinds are written durably; only the backfill proposal path is
       genuinely missing
- 8.30 signed roster metadata landed with 8.31
- 8.42 the season countdown is implemented
- 8.16/8.43 the matcher is deployed; what remains is soak, not integration
- 8.13/8.52 cross-referenced to #31 rather than described loosely

The drift runs one way -- rows keep listing work that has since landed --
which inflates the apparent backlog and invites rebuilding what exists.
8.19 is the clearest case: it reads as four missing pieces and is one.

The §7 preamble claimed every row lists only what is still open. It
doesn't, so it now says so and points at the audit note, with the
standing instruction to verify a row against the code before planning
against it.
2026-09-05 17:01:00 +01:00
Josh Creek 2702e53068 feat(ranked): make tier thresholds durable instead of compiled in
Task 8.22. Tier bands lived in domain.DefaultTierPolicy(), compiled into
every API binary, so retuning one meant building and rolling a new image
-- least attractive exactly when it is most needed, as the rating
distribution settles after launch.

Bands now live in a tier_bands table, seeded by the migration with the
exact policy the binaries hardcode, so this changes durable state without
changing behaviour. Retuning is a rolling restart rather than a rebuild.

Three properties the loader deliberately holds:

- A malformed durable policy stops startup. Falling back on error would
  silently mis-tier every player, which is worse than not starting.
- An empty table is supported and falls back to the compiled default, so
  an operator can truncate back to known-good without a deploy, and a
  fresh database works before the seed is reviewed.
- PROVISIONAL is rejected as a band. It is derived from ranked game
  count, not rating, so a band claiming it would be unreachable at best
  and would shadow a real tier at worst.

Bands stay backend-owned; clients still receive only the resulting label,
per docs/MATCHMAKING.md. UNIQUE(min_rating) rejects two bands sharing a
threshold, catching an ambiguous policy before NewTierPolicy does.

testkit-api loads it too, so the control-plane integration scripts
exercise the durable path rather than the compiled default.

Integration tests cover the seeded policy matching the compiled one,
retuning taking effect from the database alone, truncation falling back,
and each invalid-policy shape being rejected. Verified they fail against
a loader that ignores durable bands.

The other two parts of 8.22 needed no work: the client UI already renders
tier, provisional status, ranked games and the season countdown, and
reconnect transport is 8.42's, dependent on live backend events.
2026-09-05 15:38:24 +01:00
Josh Creek 8b9ae35b43 test(domain): guard the ranked arena list against Godot registry drift
Task 8.20. `arena_registry.gd` is the documented single source of truth
for arenas, but `domain/ranked.go` keeps a hand-maintained mirror of its
floor-goal entries and nothing checked the two against each other --
ranked_test.go asserts the same three paths the production code
hardcodes, so both could drift together silently.

Drift is not hypothetical in either direction. The registry's own comment
anticipates flipping an elevated variant to random:true once a checkpoint
trained on that geometry is promoted, which ranked would then keep
excluding indefinitely. A rename or removal is worse: the allocator would
hand out a scene path that no longer exists, and the ranked server fails
to load its arena at match start -- after allocation, so it burns a real
match and a real server.

Keeping the two copies is deliberate rather than a wart: ranked arena
selection is server-authoritative and happens before any Godot process
exists. So this guards the relationship instead of removing it, the same
way the golden join-authorisation token guards the signing format. It
parses the registry and fails if the sets disagree either way, if
rotation order diverges from declaration order, or if a ranked path has
no scene behind it. The parser asserts it found both eligible and
ineligible entries, so a format change cannot make everything pass
vacuously. Verified against four drift scenarios.

The allocation-wiring half of 8.20 turned out to be already complete end
to end, with coverage at each hop; recorded in the task row rather than
rebuilt.

Add a Server Unit Tests workflow, because none of this would otherwise
run: the only Go tests CI executed were multiplayer-load's two load
tests, so ~24k lines of control plane gated nothing. Docker-free so it
can gate every push, and it vets the integration-tagged files too, since
those are excluded from the default build and could otherwise rot
uncompiled.

CLAUDE.md's CI section claimed two workflows and no unit-test job; there
were seven and now eight.
2026-09-05 15:05:49 +01:00
Josh Creek a4b362cb01 fix(deploy): supply Steam credentials to the control plane, refresh stale status
The Steam adapter took --steam-publisher-key/--steam-app-id and the
matching env vars, but no manifest supplied them, so a deployed control
plane would have kept sign-in returning 503 even once the App ID from
#15 arrived -- that issue would have unblocked nothing on landing.

Mount them from a new cosmic-clash-steam Secret, into the control-plane
Deployment alone: the publisher key is issued to us, never to a client,
and no other workload (least of all a game server) has any use for it. A
manifest test asserts both the wiring and that the Secret appears in no
other manifest; verified it fails in both directions.

Both keys are optional, so the Deployment still rolls out before the App
ID exists and sign-in simply stays 503.

Also correct task rows this branch made stale: 7.4 (durable ban storage
landed), 8.7 (adapter, bans and secret store landed), 8.39 (cross-replica
fan-out landed), and 8.5's migration range, which stopped at 0013.

Move the branch review into docs/ with a header marking it a point-in-time
artefact -- all thirteen findings are addressed, and its present tense
would otherwise read as current behaviour.

Record gotcha 52: the integration scripts use `docker run --rm`, which
reclaims the container but not its anonymous volume. Sixty-four of them,
~4 GB, accumulated during this session until PostgreSQL stopped starting
-- surfacing only as the script's own readiness timeout, not as a disk
error. That is the real cause behind the "Docker storage exhausted
locally" notes those rows carried.
2026-09-05 12:38:15 +01:00
Josh Creek 0a8f3924d0 docs: cross-reference the new image-publishing issue in TODO.md
Issue #31 covers the gap that no workflow builds or pushes the images
deploy/k8s/base references, and that every digest there is still an
all-zero placeholder which the supply-chain gate accepts because it runs
without --require-concrete. It blocks #17.
2026-09-05 12:18:32 +01:00
Josh Creek ccf7d0fbfe docs: record the closed root blocker and the new probe/rotation contract
docs/MATCHMAKING.md is the stated source of truth for this design, so it
changes first: the probe challenge endpoint and why probing gates
matching rather than merely improving it, and the key-ID rotation
procedure that makes overlapping-key rotation concrete.

multiplayer-next.md §0's root blocker is closed rather than deleted --
what it was, why it blocked everything, and how it was resolved, since
the reasoning is what a future reader needs. Tasks 7.6, 8.15 and 8.31
updated to what actually remains, which in every case is now external
rather than unbuilt.

TODO.md #14 asked for a join-signing design decision; that decision is
recorded with its rationale. CLAUDE.md no longer says a real deployment
cannot complete a match end to end.
2026-09-05 11:00:50 +01:00
Josh Creek f628ccfd35 feat(auth): wire production Steam sign-in and the client login flow
newAPIService never supplied SteamLogin, so POST /v1/session/steam
always returned 503 auth_unavailable in production. The only
implementation was cmd/testkit-api's fake, which derives an identity
from the ticket string itself and accepts anything -- so the passing
integration path was neither deployable nor secure. On the client side
the game started with an empty token and a loopback base URL, and no
production code called configure() or login_steam(); the menu entered
matchmaking directly, so every request failed ERR_UNAUTHORIZED before
reaching the network.

Add a real ISteamUserAuth/AuthenticateUserTicket adapter behind an
interface, so the production login path is testable with only the Valve
call stubbed. It rejects family-shared copies (the account playing does
not own the app) and, by default, VAC- or publisher-banned accounts, and
refuses malformed tickets locally rather than forwarding them.

Crucially it separates our faults from the player's: a Valve outage or a
revoked publisher key returns 503, not 401. Answering 401 would tell a
legitimate player their login failed and send them to fix an account
that is fine while the real fault went unnoticed. A banned identity now
returns 403 rather than a misleading 503.

Sign-in is configuration-gated on the publisher key and App ID: without
them the endpoint keeps returning 503, since silently accepting an
unverified ticket would be worse than refusing to authenticate. A
returning player keeps the player ID they already had, so ratings,
penalties and bans follow the account rather than the session.

Client side: acquire a web-API ticket through GodotSteam's async
signal -- requesting one returns a handle, not a ticket -- using the
existing dynamic-call pattern so stock Godot still parses the project.
The endpoint is configurable for release builds, and matchmaking
completes sign-in before it will queue.

Verified against real PostgreSQL; 232 Godot tests pass.
2026-09-05 10:57:50 +01:00
Josh Creek d40344a2c0 fix(deploy): ship runnable control-plane and matcher workloads
The Kubernetes base deployed a control-plane image the Dockerfile never
built -- cmd/control-plane was absent from the Go build stage and no
target existed -- while the Dockerfile built a matcher image no manifest
ever deployed. Applying the checked-in base therefore could not produce
the advertised topology: one required workload had no repository-defined
artifact, and nothing consumed queued tickets. Tickets could be created
but never became proposals.

Add the production control-plane build and image target, explicitly not
the testkit-api target, which injects a fake login accepting any ticket.
Add casual and ranked matcher Deployments as separate workloads: they
have different match sizes, and separating them keeps a ranked backlog
from delaying casual formation. One replica each -- CreateProposal's
SKIP LOCKED fences make more replicas safe, but they would halve the
candidate pool each worker sees per poll and worsen formation for no
throughput gain at this scale. Their PDB uses maxUnavailable, since
minAvailable against a single replica blocks node drains outright.

Also fix both blocked traffic directions. No ingress policy admitted
UDP/7777 to game-server pods, so an allocated server was unreachable
from the internet under the namespace-wide default deny. And
control-plane ingress admitted only edge-gateway pods, so roster fetch,
registration, connection receipts, shutdown and result submission from
game servers were dropped even inside the cluster, despite their egress
being permitted. The default deny stays.

Manifest tests now assert every required role is deployed, both
playlists are scheduled, every referenced image maps to a real
Dockerfile target, and both traffic directions are permitted. Each was
verified to fail against the defect it covers. The control-plane image
was built and run to confirm the target works.
2026-09-05 10:52:52 +01:00
Josh Creek 801fca7cb0 fix(matchmaking): make regional RTT evidence obtainable end to end
domain.validCandidate hard-requires a non-empty PredictedRTT map, but
CreateQueueTicket persisted an empty one and the only endpoint that
could fill it returned 503 in every real binary, because Service.Probe
was assigned nowhere outside api tests. No client-created ticket could
ever be selected by the matcher. The Godot client had no probe method at
all, so even a wired backend was unreachable from the game.

Four distinct defects had to be fixed for this path to work:

Nothing issued the nonce ProbeProvider was meant to compare against, so
the contract could not be satisfied even in principle. Add
POST /v1/probes/{region}/challenge, backed by a durable single-use
challenge -- durable because any replica may serve the answer for a
challenge another replica issued. RTT is the interval between issuing
and receiving, so no client-reported latency reaches placement.

CreateQueueTicket marshalled a nil map to JSON `null`, a JSONB scalar
rather than an object, and jsonb_set rejects that with "cannot set path
in scalar". RecordProbe would have failed at runtime even once wired.
Persist an object, and normalise non-object values in the update for
rows already written.

A nil ProbeRecorder made the handler report success while persisting
nothing, which silently leaves the ticket unmatchable. That is a
misconfiguration, not a successful probe; it now returns 503.

A successful probe updated PostgreSQL only. The candidate inserted at
enqueue time carries an empty RTT map, and the Redis keyspace has its
TTL continually refreshed, so the stale entry need never repair itself.
Refresh that player's projection after the probe commits.

Client side: add the challenge/answer round trip and have the
matchmaking screen collect evidence before creating a ticket, since
queueing first produces a search that can never match. Probing every
region fully is not required -- placement uses whichever regions
answered -- but queueing with none is refused rather than silently
stalling.

New integration test drives the real enqueue and probe paths and then
asks the actual matcher predicate, rather than hand-building a candidate
the way the unit tests do -- which is exactly why they missed this.

Also make the integration schema reset drop the whole public schema: the
enumerated table list silently broke with each new migration.
2026-09-05 10:49:28 +01:00
Josh Creek 5765532409 fix(allocator): publish signed assignment rosters before servers start
The root blocker (issue #14). The worker bound the provider allocation
and stopped. Service.PublishRoster and store.SaveVerifiedAssignmentRoster
both existed, fully tested, with zero non-test callers, and the
production allocator configured neither a roster store nor a signing
key. Nothing ever wrote the assignments table.

The allocated supervisor fetches a non-empty roster before it launches
the game child, so every real allocation failed at that fetch: no match
could reach ASSIGNMENT_READY or accept a player. Existing tests seeded
assignments directly, which is exactly why the missing hand-off went
unnoticed.

The worker now builds one join authorisation per durable participant,
signs each with the active key, and publishes them. Participants are
read through the same query SaveVerifiedAssignmentRoster re-validates
against, so the allocator cannot construct a roster the persistence
boundary would reject. The manifest commits to a digest over the whole
roster, so a server cannot be handed a truncated roster whose surviving
entries are each individually valid.

Persist the provider endpoint on the allocation: it arrived on the
provider response and was never stored, so a worker crashing between
allocating and publishing had no endpoint to recover and would have
stranded the match permanently. Republishing is idempotent, so that
crash now simply retries.

cmd/allocator refuses to start without key material rather than running
an allocator that binds allocations and silently strands every match.
The k8s allocator Deployment mounts the same key set the Fleet does, and
both now take the JSON key map so a rotation can publish several.

New integration test drives the real worker through to the supervisor's
own roster read path without seeding the assignments table. Verified it
fails with "assignments = 0, want 2" when the publish step is removed.
2026-09-05 10:42:31 +01:00
Josh Creek b8bcc1f3c1 feat(join-auth): add key-ID rotation to signed join authorisations
Prerequisite for wiring the allocator to publish rosters. The signing
key is a shared HMAC secret mounted into both the allocator and the
allocated game server; without a key ID, rotating it would invalidate
every authorisation already issued for an in-flight match, because a
server holding only the new key cannot verify a token signed with the
old one.

Add KeyID to JoinAuthorisation and append it to the canonical claim
bytes, so it is covered by the signature and cannot be repointed at a
different key than the one that actually signed. Allocated servers now
hold a set of currently-valid keys and select by ID: a rotation
publishes the new key alongside the old, and the old is dropped once no
live match can still reference it.

The key file becomes a JSON map of key ID to base64 key. A file of raw
key bytes is still accepted as a single key under the empty ID, which is
what an unrotated deployment and the kind fixture use.

Game/scripts/match_net.gd builds the canonical bytes independently, so
it changes in lockstep; the cross-language golden token in
test_match_net.gd is regenerated from the Go implementation and now
carries a key ID. Added tests cover accepting either key mid-rotation,
rejecting a retired key ID, and rejecting a token whose key ID was
swapped to name a key the server does hold.

Go suite and 223 Godot tests pass.
2026-09-05 10:36:06 +01:00
Josh Creek 5453e19761 feat(server): add retention for idempotency, outbox and session records
Each ten-second queue heartbeat mints a fresh idempotency key and
permanently inserts a row. Published outbox rows and expired/revoked
sessions were never purged either -- the maintenance role performed
lifecycle reconciliation only. At 10,000 queued players heartbeats alone
add roughly 60,000 durable rows per minute, so table and index growth,
vacuum pressure, backup size and recovery time were all unbounded on a
service intended to scale horizontally.

Add retention windows chosen to exceed every retry and recovery horizon
that could still consult the row -- deleting an idempotency key early
would turn a client replay into a second real mutation, so this is a
correctness bound, not just a housekeeping one. Dead-lettered outbox
rows are kept longest, being the record of events never delivered.

Deletes run in bounded SKIP LOCKED batches so a purge never blocks live
traffic, never holds a long transaction, and concurrent maintenance
replicas do not contend. Indexes back each predicate so a pass cannot
degrade into a sequential scan of the table it is bounding. The
maintenance role reports rows purged, the backlog past its window
(deletion lag), and any dead-lettered events.

Also make the migration-rollback test derive its step counts instead of
hardcoding them: adding a migration silently shifted the fixed counts so
the failure surfaced as an unrelated "0006 rollback did not drop
matches.allocation_id".
2026-09-05 10:32:08 +01:00
Josh Creek 129b0c7ef0 fix(server): fan outbox events out to every control-plane replica
The Deployment runs two replicas, but WebSocket subscribers live only in
each process's in-memory hub. Every replica races to read the same
global unpublished outbox rows, and publishing succeeded even when the
winning replica held no matching local subscriber -- that replica then
set the single global published_at. A client connected to the other
replica never received the event, and delivery degraded further with
each replica added. REST recovery eventually converged, but short-lived
proposal transitions could be observed late or not at all.

Publish committed events through PostgreSQL LISTEN/NOTIFY so the replica
that owns the subscriber's connection delivers it, regardless of which
replica drained the row. The listener holds its own pgx connection --
LISTEN is session state, so a pooled database/sql connection cannot
carry it -- and reconnects with backoff, since losing it would silently
downgrade that replica's subscribers to REST-only recovery.

The fan-out is optional: without EventFanout configured, behaviour is
unchanged local-hub publication, which stays correct for a single
replica and for tests. Only outbox-sourced events are routed through it;
the in-request-path publishes remain local, as those are a latency
optimisation for the caller's own connection.

Fan-out needs a wire shape of its own because ControlPlaneEvent hides
PlayerID from clients, and the recipient is exactly what a peer replica
needs to route on.
2026-09-05 10:29:23 +01:00
Josh Creek 4248e51c60 fix(server): enforce durable identity bans on session issuance and auth
banned_until and ban_reason have been in the schema since 0001, but no
production query ever read them -- grepping the tree found no reference
outside the migration itself. The only ban check was an in-memory map on
domain.TicketVerifier used by domain tests. Once real Steam login is
wired, a banned identity would keep full access through every existing
session until expiry and could obtain new ones.

Make the ban part of the durable authentication transaction rather than
a policy each login adapter must remember to re-implement:

- Session issuance inserts only when the identity exists and has no
  active ban, so a banned player cannot mint a session.
- Authentication joins the identity and rejects an active ban on every
  request, so a ban takes effect immediately on every replica rather
  than at session expiry.
- ApplyIdentityBan sets the ban and revokes that identity's sessions in
  one serializable transaction, closing the window where the ban is
  durable but another replica still accepts an issued session.

Bans are time-bounded and clearing one does not resurrect sessions the
ban revoked.

Tests cover enforcement across two independently constructed stores
standing in for two replicas, expiry/unban semantics, and -- separately,
because revocation would otherwise mask it -- that a ban applied without
revoking anything still blocks the next request.
2026-09-05 10:26:25 +01:00
Josh Creek 320ec46ba2 fix(server): partition and bound the Redis candidate projection
Both playlists shared one hash and sorted set, causing two independent
failures.

Starvation: Snapshot performed an unbounded ZRANGEBYSCORE and HMGET,
decoded the whole queue, and the matcher then truncated to its candidate
limit *before* filtering by playlist. A large casual prefix could
therefore leave the ranked worker with zero candidates indefinitely even
while ranked tickets were queued further down the set.

Mutual erasure: each matcher captured only its own playlist as the
durable source, but Rebuild replaced the shared keys, so a casual repair
wiped ranked projections and vice versa.

Namespace the keys per playlist, push the limit into Redis (LIMIT 0 N)
so reads no longer scale with total queue depth, and scope Rebuild to
one namespace. Rebuild now rejects a candidate whose playlist does not
match the namespace, which would reintroduce the starvation. Upsert
derives the namespace from the candidate; Remove takes the playlist,
since a ticket ID alone no longer identifies its namespace.

Add tests for a 300-deep casual backlog not starving ranked, for neither
playlist's rebuild erasing the other, and for the limit being applied
without losing enqueue ordering.
2026-09-05 10:23:52 +01:00
Josh Creek f6a87463c5 fix(server): load authoritative ratings into ranked candidates
The candidate projection selected only from queue_tickets and its scan
never set Candidate.Rating, so every PostgreSQL-sourced ranked candidate
arrived with Go's zero value. Rating tolerance, selection scoring and
team partitioning all read that field, so ranked matchmaking treated a
900-rated player as identical to a 2100-rated one. Unit tests missed it
because they construct candidates with ratings already populated.

Join the ratings table, defaulting to domain.GlickoInitialRating for a
player with no ratings row yet -- a genuinely new profile, matching the
column default.

Fix the same defect on the Redis path too, which is reached differently:
the projection is seeded from the candidate CreateQueueTicket builds,
not from the candidate query, and that candidate also left Rating unset.
Resolve the rating inside the enqueue transaction so both projections
agree on one authoritative value. The rating is never client-supplied.

Add a store-backed test with deliberately distant ratings (900 vs 2100)
plus an unrated player, asserting both projections and that the spread
survives. Verified it fails without the fix.
2026-09-05 10:19:23 +01:00
Josh Creek 1dd05c75f1 fix(server): repair the initial-connect outbox envelope and unblock dispatch
ApplyInitialConnectPlan wrote a payload of {match_id,state,action},
omitting event, revision, resource_id, occurred_at and player_ids --
every field deliverStateOutboxEvent requires. Delivery rejected the row,
dispatch returned on the first error so it was never acknowledged, and
because reads are ordered oldest-first it was retried ahead of every
later state_changed event on every 100ms poll. One initial-connect
transition therefore blocked lifecycle delivery for all matches, not
just its own.

Two independent fixes, since either alone leaves the system fragile:

Build envelopes through one validating helper (MarshalOutboxEnvelope)
and convert all five writers to it. A writer that omits a required
field now fails its own transaction instead of committing a row that
can only ever poison the queue. The helper takes revision as int64 so
the -1 "nothing matched" sentinel some CTEs return surfaces as an error
rather than wrapping to a huge uint64.

Make dispatch resilient regardless: a delivery failure is now counted
against that row and the batch continues, with the row dead-lettered
after MaxOutboxDeliveryAttempts so a poison event degrades to one lost
notification instead of a stalled queue. Ordering within an aggregate
is still honoured -- later events of a failed match are deferred, so no
client observes that match's newer state before its older state. An ack
failure still stops the batch, being a database rather than a payload
problem.

Initial-connect events now address every participant, not just the
connected ones: a no-show needs to learn their ticket was failed and a
penalty applied.
2026-09-05 10:17:16 +01:00
Josh Creek 2c648514ba test(server): fix and wire up the two unrun Python suites
test_contracts.py required operation ID `recordPlayerConnected`, but
openapi.json names that endpoint `claimPlayerConnection` — the accurate
name, since POST /servers/{id}/connect claims a connection lease and
returns a generation. Align the test on the document and assert the set
difference, so a future mismatch names the missing operation instead of
reporting "False is not true".

test_observability_manifests.py copied only two of the four files the
checker reads, so it died on a missing kustomization.yaml before ever
reaching the mutated namespace. Copy the full fixture, split the
namespace and scrape-path mutations into separate cases so either
defect produces its own diagnostic, and add an unmutated-copy case so a
broken fixture can't make the mutation cases pass vacuously.

Neither suite was invoked by any Make target or workflow, which is why
both could sit red. Add them, plus test_threat_model.py, to
verify_multiplayer_local.sh.
2026-09-05 10:10:11 +01:00
CosmicClash Training Bot 6983ddd7df chore(training): generation 5 progress after 20260903-1146-gen5-s6-league-retry3 2026-09-05 01:01:25 +01:00
CosmicClash Training Bot 7d247bc516 chore(training): Add 20260903-1146-gen5-s6-league-retry3 checkpoints, logs, and exported policy 2026-09-05 00:55:28 +01:00
Josh Creek 089c127cc3 docs: cross-reference the human-actionable backlog to GitHub issues
File the outstanding work that needs a person — hardware, an external
account, a playtest, a design decision — as GitHub issues (#14-#29),
labelled needs:human plus a P0-blocker..P3-low priority, an area and a
phase. Link each one inline from the doc bullet it came from.

The split: issues carry status for human-gated work, these documents
keep the detail, and the numbered agent-actionable tasks in
multiplayer-next.md §7 deliberately get no issues. Mark the 8.48 Compose
fixture bullet as agent-actionable so its lack of an issue does not read
as an omission.
2026-09-04 22:56:46 +01:00
Josh Creek b43ad207c1 docs(multiplayer): split spec into MULTIPLAYER_SPEC.md, trim task doc to outstanding work
multiplayer-next.md was a 1662-line mix of standing architecture spec
and task-completion tracking, most of which was dense per-task DONE
evidence for finished Phases 0-6. Split it:

- MULTIPLAYER_SPEC.md (new): the locked architecture decisions, wire
  format, server-side input handling, prediction/reconciliation,
  latency/frame-rate budget, and match lifecycle state machine -
  standing design reference, not task-tracked.
- multiplayer-next.md (trimmed 1662 -> ~370 lines): only outstanding
  work remains - §0 status, §7 Phase 7/8 task tables condensed to
  "what's left" per task, §8-11 reference material (refactoring notes,
  gotchas, testing, flagged items). Phases 0-6 collapsed to a pointer
  at git history instead of ~500 lines of DONE evidence.

Also:
- Repointed every `multiplayer-next.md §N` code comment (N 1-6) across
  Game/scripts, Game/tools and Game/tests to MULTIPLAYER_SPEC.md, since
  those sections moved. Task-number references (`task N.N`, §7-11)
  correctly still point at multiplayer-next.md.
- Updated CLAUDE.md's doc index and docs/TECH_STACK.md's spec-section
  citations to match.
- TODO.md: added a "what's left to actually finish multiplayer
  (human-actionable)" checklist pulled from multiplayer-next.md §0 and
  docs/MATCHMAKING.md - things that need a person (hardware, a design
  decision, a Steam App ID, hands on a controller), not more agent code.
2026-09-04 22:43:13 +01:00
Josh Creek de263f30e8 docs: explain why the matchmaking control plane is Go, fix stale status
Add a Go-vs-C#/Rust/C++ rationale for the matchmaking control plane to
TECH_STACK.md, and point at it from MATCHMAKING.md and README.md.

Also correct CLAUDE.md and README.md, which still described the backend
as unstarted/not built even though server/ has ~13k lines of Go across
matcher, allocator, api, store, security, supervisor and agones.
2026-09-04 19:10:09 +01:00
Josh Creek ad9289fb21 docs(multiplayer): flag the real root blocker of the allocation pipeline
Found while investigating why the connect-wiring fix (§8.41,
ControlPlaneClient._connect_when_assigned) would still not work
end to end in a real deployment: nothing in production ever
publishes a player's signed match assignment.

store.SaveAssignment/SaveAssignments/SaveVerifiedAssignmentRoster --
the only functions that ever write the assignments table -- are
called only from tests, never from allocator/worker.go, cmd/allocator,
or anywhere else in the real service. allocator.Service.PublishRoster
(wired to store.PostgresRosterStore) is likewise never called from
production code.

allocation_match_sql.go's AdvanceServerRegistration SQL requires an
assignments row for every match participant before allowing the
ASSIGNMENT_READY transition. With nothing ever creating those rows, a
real match cannot advance past PROCESS_READY -- no player can ever
receive a real assignment or connect, regardless of how correct the
client-side connect-wiring fix from earlier this session is.

TestRealSupervisorRegistersAllocatedServerThroughControlPlane -- the
test that was supposed to prove this end to end -- manually seeds
store.SaveAssignment in its own setup rather than exercising the real
production write path, which is why this was never caught.

Per the user's explicit direction, this is flagged rather than fixed:
closing it needs new security-relevant design (a join-signing key
shared between the allocator, which would sign, and the game server,
which fleet.yaml already mounts a verification key for via
--join-authorisations-key-file but which no control-plane binary has
a matching signing flag for; roster-digest computation; per-player
domain.JoinAuthorisation construction from match_participants/identities
via the already-built domain.SignJoinAuthorisationHMAC), not a simple
wiring fix -- a wrong design choice here is a join-authorization
forgery risk, not just a UX gap, so it isn't something to build
unprompted the way the smaller fixes earlier this session were.

Recorded in three places for visibility: a new root-blocker callout
in §0 (the outstanding-work index), the top Status line, and expanded
detail in §8.31's own row, which previously undersold this as merely
'production signer... remain'.

No code changes. Verified the doc edit didn't touch anything else:
go build/vet/test -race clean, full Godot suite 220/220 clean
(unchanged, as expected).
2026-09-04 18:18:22 +01:00
Josh Creek ae4a6f937f fix(multiplayer): surface matchmaking connect failures to the player
Closes §8.43's 'failed-reconnect UX' gap, found immediately after
wiring connect_to_assignment() itself: even with that fix in place, a
connection failure had nowhere to go. connect_to_assignment()'s
synchronous failures (assignment missing/expired, invalid endpoint,
NetworkManager.join() erroring immediately) only ever emitted
assignment_connection_failed -- a signal nothing in the client
listened to. state.phase would stay stuck at ASSIGNED, the UI would
keep showing "Your match server is ready" forever, with no way back
to a fresh search.

Worse, the likelier real-world failure mode had no handler at all:
NetworkManager.join() returns OK immediately once the attempt starts,
but the actual ENet handshake can still fail asynchronously afterward
(unreachable server, refused connection, ENet's own ~5s connect
timeout). This is exactly the gap main_menu.gd's own
_on_connection_failed exists to cover for the direct-join flow (see
its header comment) -- nothing covered the equivalent for a
matchmaking-driven connect.

ControlPlaneClient now connects both assignment_connection_failed and
NetworkManager.connection_failed (guarded to state.phase == CONNECTING,
so it never misattributes an unrelated direct-join failure to a
matchmaking search) to state.fail(...), so either failure mode now
surfaces as a failed search the player can actually retry from.

Verified: three new test_control_plane_client.gd tests cover the
synchronous failure path, the async NetworkManager.connection_failed
path (via a real end-to-end ASSIGNED -> CONNECTING flow), and that an
unrelated connection_failed outside CONNECTING is correctly ignored.
220/220 tests pass, stable across 3 repeated runs, no crash, no
engine-level error; full make verify-multiplayer-local and the
complete make verify-enet-integration suite (all five cases) both
clean; zero new crash reports throughout.

Also fixes a markdown table-integrity mistake introduced while
documenting this in the same edit pass: an earlier Edit call
accidentally duplicated a sentence and dropped the row's closing
'remains' clause in §8.43 -- caught and corrected before commit via
the usual pipe-count check.
2026-09-04 18:12:25 +01:00
Josh Creek 7d50612abb feat(multiplayer): reject outdated clients with distinct messaging
Closes §8.43's 'version-mismatch-specific client messaging' gap. Per
the user's explicit go-ahead to design new server behavior for this
(rather than only wiring up something that already existed, the
pattern every other fix this session followed): before this, there
was no server-side protocol rejection at all. queue_create accepted
any protocol_version >= 1 unconditionally, so an outdated client could
only ever discover a mismatch by waiting in the queue forever
unmatched -- the matcher's own compatibility check requires every
formed player to share an identical protocol_version -- with no error
and no explanation given to the player.

Server: Service.MinProtocolVersion (opt-in, zero by default so every
existing caller keeps accepting protocol_version 1 unconditionally)
rejects a below-floor queue_create with 426 Upgrade Required /
client_outdated before the request ever reaches the candidate
provider. Wired via cmd/control-plane's new --min-protocol-version
flag (validated non-negative at startup).

Client: ControlPlaneClient recognises HTTPClient.RESPONSE_UPGRADE_REQUIRED
on queue_create specifically and sets a distinct 'Your client is out
of date -- please update to continue searching' message instead of
the server's raw generic error string, and clears _last_queue_create
so can_retry_queue_create() never offers 'Retry Search' for a failure
that retrying with the same build can never fix.

Verified: go build/vet/test -race clean across every server package.
TestQueueCreateEnforcesMinProtocolVersion covers below-floor rejection
(candidate provider never reached), exactly-at-floor acceptance, and
the error body naming client_outdated; TestQueueCreateMinProtocolVersionZeroIsDisabled
proves the opt-in default doesn't change behavior for every existing
caller. Godot: test_outdated_client_receives_a_distinct_message_and_no_retry_offer
proves the distinct message and suppressed retry offer. Full Godot
suite (217/217, 0 failed, no crash), full make verify-multiplayer-local
gate, zero new crash reports.
2026-09-04 18:07:29 +01:00
Josh Creek 24620be5c1 docs(multiplayer): correct two more stale 'remains' notes
Investigating §8.16's 'arena selection... remain' note (looking for
the next real Godot-side gap) found the described work was already
fully done, not missing: domain.RankedArenaForProposal selects the
ranked arena deterministically at proposal time; agones.Client.Allocate
already requests it (plus playlist/region/build/protocol/transport) as
Agones GameServerAllocation annotations; supervisor.withAllocatedCompatibility
already overlays every one of those onto the allocated Godot process's
launch command, overriding the Fleet's static per-image defaults --
fully tested (TestWithAllocatedCompatibilityOverridesStaleFlagsAndRejectsUnsafeValues)
and wired into Supervisor.Start(). Casual deliberately leaves
proposal.ArenaPath empty and the allocated server falls back to its
own ArenaRegistry.path_for_match rotation -- the same mechanism the
community server already used, always the intended design, not a gap.

§8.41's 'dynamic per-match launch flags... remain' note was the same
stale claim about the same already-built mechanism, described from
the other side (the assignment/roster row instead of the matcher
row). Corrected there too, pointing back to §8.16 rather than
duplicating the explanation.

No code changes -- this is the same category of finding as the
crash-loop and connect-wiring fixes earlier this session, just
resolved by correcting the record instead of writing new code, since
the record was wrong rather than the implementation. Verified the
referenced test by name: go test ./supervisor/... -run
TestWithAllocatedCompatibilityOverridesStaleFlagsAndRejectsUnsafeValues
passes; full go build/vet/test -race clean across every server
package (unchanged from before, since only the doc changed).
2026-09-04 18:02:36 +01:00
Josh Creek 4c61b1e28d fix(multiplayer): actually connect once matchmaking assigns a match
A player who completed the entire queue -> proposal -> allocate ->
assign pipeline would reach ASSIGNED, see "Your match server is
ready", and then simply sit there forever. connect_to_assignment()
existed in control_plane_client.gd, fully validated (checks the
assignment is available and fresh, splits and validates the
endpoint, carries the join authorisation via MatchNet's hello payload
rather than the URL) with its own assignment_connection_started/
assignment_connection_failed signals, and multiplayer-next.md's own
§8.41 row already described it as wired -- but grepping the whole
client found zero callers. Nothing anywhere in matchmaking.gd or
control_plane_client.gd itself ever invoked it.

ControlPlaneClient._connect_when_assigned() now calls it automatically
the moment state.phase reaches ASSIGNED. Wired into the single call
site every queue-shaped HTTP response already shares (heartbeat,
recover, and resync-triggered recover alike, since the WebSocket
match-lifecycle path always funnels into a REST resync first), so
both the ordinary poll path and the WebSocket-push path are covered
without a second call site to keep in sync. Two orderings are handled:
if the assignment fetch triggered earlier by ASSIGNMENT_READY has
already completed, it connects immediately; if not, it defers via
_pending_connect_match_id and resolves once the assignment becomes
available. _connect_attempted_match_id guards against a duplicate or
replayed ASSIGNED event reattempting the connection.

Verified against the real Godot 4.7.1 binary now that headless
testing has resumed: two new test_control_plane_client.gd tests cover
both orderings and the duplicate-attempt guard directly (216/216
total, 0 failed, no crash, no engine-level error, stable across
repeated runs); full make verify-multiplayer-local and the complete
make verify-enet-integration suite (all five cases, including the
3-process match) both pass clean; zero new crash reports throughout.

multiplayer-next.md's §8.41 row is corrected to describe what was
actually true (connect_to_assignment existed but was never called)
rather than repeating the prior, inaccurate 'already wired' claim.
2026-09-04 18:00:42 +01:00
Josh Creek 8810bf7d8f test(multiplayer): cover generic mutation retry recovery
Closes most of §8.43's 'decline, regional outage retry UI, failed
reconnect, duplicate-action recovery beyond proposals' remaining
list -- turned out to be mostly stale doc, not missing code.

matchmaking.gd's decline button/handler already existed
(%DeclineButton, _on_decline_pressed, visibility toggled by
MatchmakingState.PROPOSED alongside accept). ControlPlaneClient's
can_retry_last_mutation()/retry_last_mutation() -- the generic
'duplicate-action recovery beyond proposals' and 'regional outage
retry' mechanism -- also already existed: any mutation (not just a
proposal response) becomes retryable on a transport failure or a
408/429/503 response, and matchmaking.gd's queue button already fell
back to it ('Retry Request'). Neither had any test coverage proving
the mechanism actually works for a non-proposal mutation --
is_retryable_mutation_response's pure classification was the only
thing tested.

Two new tests: test_generic_mutation_retry_recovers_after_a_transient_failure
proves can_retry_last_mutation() transitions from false (mutation
in flight) to true after a transport-level failure on an ordinary
queue_heartbeat, exactly the 'regional outage' case; test_generic_mutation_retry_is_not_offered_for_unsafe_failures
proves a 409 (revision conflict) is never offered as a blind retry
and that retry_last_mutation() fails closed with ERR_INVALID_DATA
rather than resending a stale mutation. retry_last_mutation's literal
network dispatch (HTTPRequest.request()) is not exercised -- it needs
a live SceneTree that test_runner.tscn's synchronous single-_ready()
execution model cannot provide mid-suite; the two tests cover the
can_retry_last_mutation() decision boundary and the fail-closed path
instead, which is what's actually new here.

Verified against the real Godot 4.7.1 binary now that headless
testing has resumed: test_runner.tscn 214/214 clean (no crash, no
engine-level error), full make verify-multiplayer-local re-run clean,
zero new crash reports.

Remaining in §8.43: version-mismatch-specific messaging (a protocol
rejection currently surfaces only as the server's generic error
string), failed-reconnect UX, and §8.16's arena selection/long-running
worker integration.
2026-09-04 17:51:54 +01:00
Josh Creek 91b3fc938c docs(multiplayer): resolve the Godot crash-attribution blocker
Godot testing had been paused since earlier this session after a run
of native engine crashes (macOS crash reporter, EXC_BAD_ACCESS/SIGBUS)
that the user had confirmed as caused by this session's headless
invocations, based on temporal correlation with the session's own
activity.

Read the actual crash reports at
~/Library/Logs/DiagnosticReports/Godot-*.ips instead of relying on
that correlation. Every one of the 25 reports on the machine names
ChatGPT/codex (17 directly, 6 via an already-exited process in that
same tree) or a manual iTerm2 session (1) as the responsible/parent
process in the crash's own process tree -- none name Claude Code.
Codex (via the ChatGPT desktop app) was apparently running headless
Godot invocations concurrently with this session that day; the
crashes were most likely misattributed to Claude Code on timing
alone, not on anything in the crash reports themselves.

Presented this finding to the user, who confirmed resuming Godot
testing. Re-verified clean with zero new crash reports: test_runner.tscn
(212/212), the full make verify-enet-integration suite (all five
cases including the 3-process match), scripts/verify_control_plane_proposal_integration.sh
(passed twice -- the real matcher forms the proposal and both real
headless clients accept it), and the complete make verify-multiplayer-local
gate end to end (Go tests/race/vet, all three fuzz targets, 212 Godot
tests, contracts, manifests).

This unblocks the Godot-side work multiplayer-next.md had been
holding open pending this question: the two-player proposal
integration script (already on disk, now proven to pass) and the
Phase 8 client-experience tasks (8.39-8.43) that were waiting on the
same answer.
2026-09-04 17:45:27 +01:00
Josh Creek 79ab0d1404 fix(multiplayer): serve queue candidates when Redis is down, not just empty
Closes part of the 'live Redis failover' gap in §8.46, found by
reproducing a genuine Redis outage (not just an empty/partial cache)
against CandidateProjection.Snapshot with a killed miniredis instance.

CandidateProjection.Snapshot funnelled two different situations into
the same code path: the index erroring outright (Redis unreachable)
and the index coming back empty (ambiguous — a genuinely empty queue,
or a lost keyspace). Both went through Repair, which itself calls
Index.Rebuild — a second Redis round-trip that fails for exactly the
same reason the first one did. The result: a real Redis outage, or
the window during a failover, made Snapshot fail outright even though
PostgreSQL — the documented authoritative source everywhere
(RedisCandidateIndex's own comment, cmd/matcher, cmd/control-plane's
--redis-addr help text all call it a rebuildable/optional
acceleration layer) — was completely healthy. Matchmaking would stop
entirely on a Redis outage despite the architecture explicitly not
requiring that.

Snapshot now falls back to serving Source (PostgreSQL) directly
whenever the index errors OR comes back empty, and only best-effort
attempts to repopulate Redis afterward — that attempt's outcome is
deliberately ignored, since a caller must never be denied service
just because the opportunistic rebuild also hit the same down Redis.
Snapshot still fails when Source itself is unavailable; the fallback
is not unconditional.

Verified: reproduced the bug first (killed-miniredis Snapshot call
failed even though Source was healthy), then fixed it. go build/vet
clean; all pre-existing store-package tests pass unmodified,
including the two live-redis:7-alpine-container tests
(TestRealRedisCandidateIndexUpsertSnapshotRemove,
TestRealRedisCandidateProjectionRepairsAfterFlush, run against a real
container and torn down after). Two new tests cover the fallback
directly (killed miniredis, Source still served, exactly one Source
call) and that the fallback is not unconditional (both Redis and
Source down still fails). Full go test ./... -race clean across
every server package.

Remaining: live matcher-worker-under-load-during-failover integration,
i.e. running the actual matcher process against a real Redis that
goes down mid-run under concurrent load, not just this unit-level
reproduction.
2026-09-04 17:37:58 +01:00
Josh Creek 5190cded56 fix(multiplayer): stop a doomed formation from wedging the matcher
Closes the 'innocent-ticket restoration' gap noted in §8.20 and found
by re-examining §8.16's matcher worker. domain.FormFromQueue's anchor
is always the single oldest candidate, deterministically. If
domain.PrepareProposal then rejected that exact formation for a
reason specific to those particular players — mismatched protocol,
incomplete ranked identity metadata, a duplicate-SteamID pair, ranked
admission generally — RunOnce returned immediately and the next
matcher interval reproduced the identical formation and failed again.
Forever: nothing in the queue ever changes, so the same doomed anchor
group would be retried every single pass, permanently head-of-line-
blocking every other waiting player behind it too, not just the
players actually at fault. This is worse than the already-fixed
no-common-region crash-loop (§8.16) — that one killed the process;
this one fails silently and just never matches anyone again.

Two changes, both required together:

1. RunOnce now excludes a failed formation's players and retries
   with the remaining candidate pool, bounded to 8 attempts per pass.
   A batch with no viable formation at all (the pre-existing
   no-common-region case) still returns immediately, since retrying
   that can't help.

2. That fix was inert without a second one: RunOnce was asking
   Source for exactly w.Size candidates, so after excluding one
   failed formation's players there was nothing left to retry
   against. domain.SelectCandidates was always designed to search a
   larger pool (anchor plus an arbitrary remainder, widening through
   it) — the call site just never gave it one. RunOnce now requests
   up to 10x w.Size, capped at 200.

Verified: go build/vet/test -race clean across every server package.
Three new matcher tests cover the exclusion retry (an 8-candidate
batch whose permanently-doomed oldest 4 still lets the remaining 4
form and claim, correctly excluding the doomed players from the
claimed ticket set), that exhausting every attempt surfaces the last
real error rather than a silent false/nil, and that Source is
actually asked for more than w.Size candidates — a regression guard
for exactly the companion bug above. All six pre-existing worker
tests still pass unmodified, confirming the fix preserves every prior
guarantee (mixed-playlist/duplicate-identity rejection, incomplete
batch handling, durable claim failure propagation, Run's existing
per-pass-error survival).
2026-09-04 17:33:00 +01:00
Josh Creek f09ef7da8f test(multiplayer): cover concurrent proposal-expiry recovery race
Closes the 'concurrent proposal-recovery expiry races' gap noted in
§8.46. GetProposal (read-side recovery) and RespondToProposal both
run the identical expiry-advance SQL in their own transaction, so any
number of them can observe the same past-expiry proposal at once —
this had never been exercised concurrently, only sequentially (the
existing late-response test drives one call at a time).

TestPostgreSQLConcurrentProposalExpiryRecoveryAppliesCooldownsExactlyOnce
races 8 concurrent GetProposal/RespondToProposal calls, each with a
distinct 'now' past the proposal window, against one proposal and
asserts: EXPIRED lands on the proposal and both tickets exactly once,
a PROPOSAL_TIMEOUT penalty lands exactly once per offending player
(not once per racing transaction), and no idempotency row survives a
closed-proposal response. The design already defends against this —
ProposalParticipantExpireSQL only ever flips a still-PENDING row
once, so a losing racer's 'now' can't match
recordProposalTimeoutCooldowns' responded_at filter — this test is
what actually proves that holds under real concurrent load rather
than by inspection.

Verified: real postgres:17-alpine container, go test -tags
integration ./store/... -run
TestPostgreSQLConcurrentProposalExpiryRecoveryAppliesCooldownsExactlyOnce
-race -count=3 clean; full -tags integration ./store/... -race run
clean; full non-integration go build/vet/test -race clean across
every server package; container removed after the run.
2026-09-04 17:26:44 +01:00
Josh Creek ce17a45afb feat(multiplayer): alert on workload server-mutation conflicts
Closes the 'live duplicate/conflict alerting also remains' gap noted
in §8.10: a durable domain.ErrConflict/ErrResultConflict rejection on
/v1/servers/{id}/{register,connect,disconnect,shutdown,result} was
already logged as a structured 'conflict' stage event, but had no
Prometheus signal distinct from the generic 4xx-class counter, which
also catches ordinary client noise (malformed bodies, expired
tokens). A real duplicate registration, raced reconnect, or replayed
result would have been invisible to alerting until someone went
looking through logs.

observability.Metrics gains ObserveServerConflict(kind), a bounded
counter keyed to serverMutation's own five routes (an unrecognized
kind folds into "other", so a caller mistake can't grow the label
set), exported as cosmic_clash_api_server_conflicts_total. Wired at
each of serverMutation's four conflict branches in server/api/service.go.
deploy/observability/prometheus-rules.yaml adds
CosmicClashControlPlaneServerConflicts, mirroring the existing
allocator quota-denial alert shape, firing on >3 conflicts of one
kind in 15 minutes.

Verified: go build/vet/test -race clean across every server package;
new unit tests cover per-kind counting, the bounded 'other' fallback,
the counter's absence until first observed, and a nil-receiver no-op;
a service-level test proves a real register conflict is exported
through the live /metrics endpoint. scripts/verify_observability_manifests.py
passes against the edited rules file.

Remaining, and explicitly out of scope here: this alert has only been
validated statically, never against a live Prometheus/Alertmanager
firing on real traffic — that requires the same live cluster this
sandbox has never had.
2026-09-04 17:24:09 +01:00
Josh Creek 817572a6ce fix(multiplayer): size kind agones smoke resources 2026-09-04 17:07:13 +01:00
Josh Creek a5cbba8ac9 fix(multiplayer): harden live registration verification 2026-09-04 16:48:25 +01:00
Josh Creek 482d4b0985 docs(multiplayer): record load gate verification 2026-09-04 16:40:21 +01:00
Josh Creek f7958f3102 docs(multiplayer): record chaos recovery verification 2026-09-04 16:39:53 +01:00
Josh Creek d64920b0f9 fix(multiplayer): repair allocated compose verification 2026-09-04 16:38:10 +01:00
Josh Creek e6733bd6cb fix(multiplayer): repair PostgreSQL integration invariants 2026-09-04 15:43:31 +01:00
Josh Creek 0acf144f45 docs(multiplayer): record latest Godot coverage 2026-09-04 11:07:21 +01:00
Josh Creek 61daf139c5 fix(multiplayer): fence workload control URLs 2026-09-03 21:31:09 +01:00
Josh Creek 4e1dd0d24e test(multiplayer): preserve result integrity state 2026-09-03 21:30:16 +01:00
Josh Creek 3f3dada35f docs(multiplayer): refresh verification evidence 2026-09-03 21:29:18 +01:00
Josh Creek 9a724bf562 test(multiplayer): recover from native Godot crashes 2026-09-03 21:28:21 +01:00
Josh Creek ea1c65acfb fix(multiplayer): bound workload credential lifetime 2026-09-03 21:27:26 +01:00
Josh Creek 8507472635 fix(multiplayer): submit allocated match results 2026-09-03 21:24:07 +01:00
Josh Creek 759dbe2b65 docs(multiplayer): state workload annotation residual risk 2026-09-03 21:17:20 +01:00
Josh Creek f50264dae6 docs(multiplayer): correct outbox ownership 2026-09-03 21:15:52 +01:00
Josh Creek 6632cdace7 fix(multiplayer): validate initial-connect backfill 2026-09-03 21:15:32 +01:00
Josh Creek b5b6bdea95 fix(multiplayer): validate legacy connection leases 2026-09-03 21:14:41 +01:00
Josh Creek 2050acd63d test(multiplayer): make local gate portable 2026-09-03 21:12:40 +01:00
Josh Creek 3b523cf525 docs(multiplayer): record current Godot harness evidence 2026-09-03 21:10:12 +01:00
Josh Creek 854d160f27 docs(multiplayer): align workload authentication model 2026-09-03 21:08:52 +01:00
Josh Creek 25cf1e0cfa fix(multiplayer): keep abandonment maintenance available 2026-09-03 21:07:50 +01:00
Josh Creek addcea9fed fix(multiplayer): refresh dedicated server build base 2026-09-03 21:06:22 +01:00
Josh Creek bcc2639a33 fix(multiplayer): deploy reconnect abandonment maintenance 2026-09-03 21:05:58 +01:00
Josh Creek a4de140424 fix(multiplayer): fail closed without durable leases 2026-09-03 21:04:07 +01:00
Josh Creek 947fefc95c fix(multiplayer): dispatch live abandonment lifecycle 2026-09-03 20:55:56 +01:00
Josh Creek bd93a2657e docs(multiplayer): reflect durable admission leases 2026-09-03 20:54:12 +01:00
Josh Creek 2463713cde feat(multiplayer): persist live reconnect abandonments 2026-09-03 20:53:28 +01:00
Josh Creek aac81c89b6 feat(multiplayer): bind admissions to durable leases 2026-09-03 13:45:39 +01:00
Josh Creek 3e0022ce9c feat(multiplayer): persist connection generation leases 2026-09-03 13:38:13 +01:00
Josh Creek 2e9da3032c fix(multiplayer): complete live results atomically 2026-09-03 13:29:31 +01:00
Josh Creek 8c28374eb4 fix(multiplayer): harden reconnect lifecycle fencing 2026-09-03 13:24:52 +01:00
Josh Creek cee0163eac fix(multiplayer): verify complete durable assignment rosters 2026-09-03 13:22:02 +01:00
CosmicClash Training Bot 4519f2db82 chore(training): generation 5 progress after 20260901-2301-gen5-s6-league-retry2 2026-09-03 11:46:05 +01:00
CosmicClash Training Bot 0f1a7403e4 chore(training): Add 20260901-2301-gen5-s6-league-retry2 checkpoints, logs, and exported policy 2026-09-03 11:40:08 +01:00
Josh Creek bef71e1dcf fix(multiplayer): fence provider allocation results 2026-09-03 00:19:03 +01:00
Josh Creek a15368ed29 fix(multiplayer): fence client queue cancellation states 2026-09-03 00:15:41 +01:00
Josh Creek 1976c6eac6 fix(multiplayer): promote accepted matches atomically 2026-09-03 00:13:18 +01:00
Josh Creek eaf7ea8748 fix(multiplayer): make match promotion replay lifecycle-safe 2026-09-03 00:10:57 +01:00
Josh Creek f8af212e3f fix(multiplayer): terminate proposal offenders atomically 2026-09-03 00:09:07 +01:00
Josh Creek aa446cfbfe fix(multiplayer): reconcile authoritative initial connections 2026-09-03 00:02:04 +01:00
Josh Creek 781cbc35aa docs(multiplayer): reconcile review progress 2026-09-02 19:15:47 +01:00
Josh Creek 51f8008a38 fix(multiplayer): gate API readiness on database 2026-09-02 19:14:21 +01:00
Josh Creek 1bce603c33 fix(multiplayer): bound adapter HTTP calls 2026-09-02 19:12:40 +01:00
Josh Creek cbefa86c5c fix(multiplayer): report allocator readiness 2026-09-02 19:11:01 +01:00
Josh Creek 6ebd6e59c1 fix(multiplayer): resolve client IP behind proxies 2026-09-02 19:08:34 +01:00
Josh Creek d59e0017f7 fix(multiplayer): lock signed team assignments 2026-09-02 19:05:45 +01:00
Josh Creek 0bca441ca1 fix(multiplayer): enforce drain at admission 2026-09-02 19:04:56 +01:00
Josh Creek 670466dbd7 fix(multiplayer): authenticate Agones Kubernetes API 2026-09-02 18:58:57 +01:00
Josh Creek 55b88a3aa5 fix(multiplayer): converge events through REST 2026-09-02 18:54:10 +01:00
Josh Creek 91658fbc13 fix(multiplayer): recover assignment handoff 2026-09-02 18:47:00 +01:00
Josh Creek 84d27d82da docs: narrow remaining font TODO 2026-09-01 23:31:27 +01:00
Josh Creek 3e9f3f2c4e docs: reconcile audio progress notes 2026-09-01 23:30:06 +01:00
Josh Creek 4353abfd97 feat(audio): add wall contact cue 2026-09-01 23:26:18 +01:00
Josh Creek f5fd3bb207 feat(audio): add turbo engagement cue 2026-09-01 23:24:42 +01:00
Josh Creek 5dc659007e docs: clarify video settings profiling gate 2026-09-01 23:23:17 +01:00
Josh Creek 19ef84c3cb feat(audio): drive engine tone from thrust 2026-09-01 23:22:20 +01:00
Josh Creek fcb38b3d57 feat(audio): connect ball impacts to feedback 2026-09-01 23:20:35 +01:00
Josh Creek 510138eb0a feat(audio): wire menu click feedback 2026-09-01 23:19:48 +01:00
Josh Creek b883338396 feat(audio): add procedural gameplay sound foundation 2026-09-01 23:18:48 +01:00
Josh Creek a9b8f53ef1 docs(multiplayer): record allocation outbox coverage 2026-09-01 23:15:47 +01:00
Josh Creek b15d19eec2 feat(multiplayer): explain queue and connection health 2026-09-01 23:11:37 +01:00
Josh Creek 9b14109727 test(multiplayer): retain failed database container 2026-09-01 23:08:01 +01:00
Josh Creek 870b89d279 test(multiplayer): expose database gate failures 2026-09-01 23:07:08 +01:00
Josh Creek bff71bfc2a docs(multiplayer): record live gate storage blocker 2026-09-01 23:06:21 +01:00
Josh Creek bfaf5d40ff fix(multiplayer): validate timestamp calendar 2026-09-01 23:02:31 +01:00
CosmicClash Training Bot 8a55c33666 chore(training): generation 5 progress after 20260831-0724-gen5-s6-league-retry1 2026-09-01 23:01:35 +01:00
Josh Creek 6a9b269798 fix(multiplayer): validate contract ticket input 2026-09-01 22:59:57 +01:00
Josh Creek badd0b1b47 fix(multiplayer): validate contract route ids 2026-09-01 22:58:28 +01:00
Josh Creek f7ab77dec5 fix(multiplayer): validate queue response contract 2026-09-01 22:56:33 +01:00
CosmicClash Training Bot ad6f9cc148 chore(training): Add 20260831-0724-gen5-s6-league-retry1 checkpoints, logs, and exported policy 2026-09-01 22:55:32 +01:00
Josh Creek fc3a7ea359 fix(multiplayer): validate proposal expiry 2026-09-01 22:54:33 +01:00
Josh Creek ffc7856993 fix(multiplayer): align proposal participant contract 2026-09-01 22:52:52 +01:00
Josh Creek 807aaa4478 fix(multiplayer): validate match admission context 2026-09-01 22:51:15 +01:00
Josh Creek 3bd2387dc3 fix(multiplayer): validate session expiry response 2026-09-01 22:50:00 +01:00
Josh Creek edd78d2548 fix(multiplayer): validate REST response ids 2026-09-01 22:47:57 +01:00
Josh Creek bda3fc5aff fix(multiplayer): validate persisted matchmaking ids 2026-09-01 22:46:40 +01:00
Josh Creek e9ed8923c9 fix(multiplayer): validate client resource paths 2026-09-01 22:45:04 +01:00
Josh Creek 56e8e2554c fix(multiplayer): validate allocated config ids 2026-09-01 22:44:12 +01:00
Josh Creek 75f9026ea1 fix(multiplayer): reject fractional assignment values 2026-09-01 22:42:46 +01:00
Josh Creek e376e1e80d fix(multiplayer): align websocket assignment ids 2026-09-01 22:42:04 +01:00
Josh Creek 2bdf876b47 fix(multiplayer): enforce assignment opaque ids 2026-09-01 22:40:43 +01:00
Josh Creek dac414274e fix(multiplayer): enforce ranked tier enum 2026-09-01 22:39:06 +01:00
Josh Creek c580e46125 fix(multiplayer): fail closed on ticket timestamps 2026-09-01 22:36:54 +01:00
Josh Creek 03bc723b70 fix(multiplayer): reject fractional ranked games 2026-09-01 22:36:05 +01:00
Josh Creek a10c6d47f9 fix(multiplayer): validate persisted matchmaking snapshots 2026-09-01 22:34:59 +01:00
Josh Creek 3985b74bcf fix(multiplayer): validate ranked season ids 2026-09-01 22:33:54 +01:00
Josh Creek ec0bc362cd fix(multiplayer): validate ranked season expiry 2026-09-01 22:33:00 +01:00
Josh Creek d819658ace fix(multiplayer): reject typed claim coercion 2026-09-01 22:32:05 +01:00
Josh Creek 4d8638e62f fix(multiplayer): harden join expiry validation 2026-09-01 22:30:36 +01:00
Josh Creek 82691eaf80 fix(multiplayer): validate assignment expiry format 2026-09-01 22:29:45 +01:00
Josh Creek 07fd0fde44 feat(ui): add shared cosmic clash theme 2026-09-01 22:28:02 +01:00
Josh Creek 889e30a434 fix(multiplayer): reset expiry on reauthentication 2026-09-01 22:26:39 +01:00
Josh Creek 27017043f9 feat(multiplayer): explain allocation lifecycle 2026-09-01 22:25:54 +01:00
Josh Creek 429fb87c08 fix(multiplayer): validate server event resource ids 2026-09-01 22:25:04 +01:00
Josh Creek fd1a4d9577 feat(multiplayer): show authoritative proposal countdown 2026-09-01 22:23:33 +01:00
Josh Creek 17e6a9bc20 fix(multiplayer): enforce opaque event resource ids 2026-09-01 22:22:34 +01:00
Josh Creek 87d43302e1 fix(multiplayer): validate event timestamps 2026-09-01 22:21:18 +01:00
Josh Creek 73e5d64ba2 test(multiplayer): cover queue conflict recovery wiring 2026-09-01 22:20:07 +01:00
Josh Creek 7534d8436c fix(multiplayer): recover queue revision conflicts 2026-09-01 22:19:02 +01:00
Josh Creek 1f05f6d524 fix(multiplayer): align resync recovery targets 2026-09-01 22:16:50 +01:00
Josh Creek cfc82bcea5 fix(multiplayer): expire client sessions proactively 2026-09-01 22:13:41 +01:00
Josh Creek 1e5825b096 fix(multiplayer): validate ticket timestamps 2026-09-01 22:08:19 +01:00
Josh Creek c08c761af3 fix(multiplayer): recover requeued tickets 2026-09-01 22:06:30 +01:00
Josh Creek 0c4ad6a5aa fix(multiplayer): preserve proposal requeues 2026-09-01 22:04:53 +01:00
Josh Creek 277ad4bf98 fix(multiplayer): validate ticket playlists 2026-09-01 22:02:01 +01:00
Josh Creek 0ce2a49419 fix(multiplayer): enforce proposal transitions 2026-09-01 22:00:37 +01:00
Josh Creek a60c1a097e fix(multiplayer): validate client revisions 2026-09-01 21:59:32 +01:00
Josh Creek f491725144 fix(multiplayer): stop recovery after completion 2026-09-01 21:58:20 +01:00
Josh Creek 0f1864f8bc fix(multiplayer): enforce client state transitions 2026-09-01 21:57:13 +01:00
Josh Creek 30a5a89164 fix(multiplayer): project complete queue lifecycle 2026-09-01 21:55:19 +01:00
Josh Creek 6ac2d0fbb1 fix(multiplayer): project accepted queue state 2026-09-01 21:54:10 +01:00
Josh Creek fa2c93ec06 fix(multiplayer): defer reconnect recovery during mutations 2026-09-01 21:53:07 +01:00
Josh Creek 47aa196b59 feat(multiplayer): publish ranked profile contract 2026-09-01 21:51:42 +01:00
Josh Creek 51f6e19339 feat(multiplayer): expose ranked season countdown 2026-09-01 21:49:48 +01:00
Josh Creek 9240cd4b27 feat(multiplayer): preserve authoritative queue wait 2026-09-01 21:45:07 +01:00
Josh Creek 950e879861 fix(multiplayer): bind allocation to accepted proposal 2026-09-01 21:41:44 +01:00
Josh Creek d3a457d8d0 fix(multiplayer): avoid quota double charge on recovery 2026-09-01 21:39:18 +01:00
Josh Creek eb3b685af0 feat(multiplayer): expose active ranked season 2026-09-01 21:34:57 +01:00
Josh Creek 3151e54ab3 fix(multiplayer): use locked rating for season rollover 2026-09-01 21:32:34 +01:00
Josh Creek 96f311c129 fix(multiplayer): finalize empty ranked seasons 2026-09-01 21:30:23 +01:00
Josh Creek 836cedec3c feat(multiplayer): publish allocation progress events 2026-09-01 21:27:24 +01:00
Josh Creek 614b87f7e1 fix(multiplayer): bound websocket writes 2026-09-01 21:24:38 +01:00
Josh Creek 30a22c366b fix(multiplayer): harden websocket frame parser 2026-09-01 21:23:20 +01:00
Josh Creek 3eb47bb9d3 fix(multiplayer): fence recovered arena identity 2026-09-01 21:21:10 +01:00
Josh Creek 701d7a9a2e fix(multiplayer): centralize arena path validation 2026-09-01 21:18:48 +01:00
Josh Creek bfeb822279 fix(multiplayer): persist arena identity on allocations 2026-09-01 21:17:39 +01:00
Josh Creek 2ff348adf0 fix(multiplayer): persist arena identity on allocations 2026-09-01 21:16:42 +01:00
Josh Creek d4bde67e0f test(multiplayer): harden ranked arena provider boundary 2026-09-01 21:13:04 +01:00
Josh Creek 0666d8d308 fix(multiplayer): verify recovered arena annotations 2026-09-01 21:12:06 +01:00
Josh Creek e83f84f527 test(multiplayer): refresh proposal cooldown evidence 2026-09-01 21:10:27 +01:00
Josh Creek b01db32908 docs(multiplayer): reconcile phase eight status 2026-09-01 21:09:43 +01:00
Josh Creek caa7e3e793 fix(multiplayer): constrain ranked arena paths in postgres 2026-09-01 21:09:01 +01:00
Josh Creek bd617dbf06 fix(multiplayer): validate ranked arena paths durably 2026-09-01 21:07:56 +01:00
Josh Creek ff80ab46b7 feat(multiplayer): rotate ranked arenas deterministically 2026-09-01 21:06:26 +01:00
Josh Creek 84372204fd feat(multiplayer): persist ranked arena allocations 2026-09-01 21:04:55 +01:00
Josh Creek 5630c5c8dc feat(multiplayer): harden ranked arena admission 2026-09-01 19:39:11 +01:00
Josh Creek 52e3d73678 fix(multiplayer): reject websocket caps before upgrade 2026-09-01 19:35:34 +01:00
Josh Creek ad59c5f567 test(multiplayer): cover cooldown response boundary 2026-09-01 19:34:16 +01:00
Josh Creek 957bb65a26 feat(multiplayer): enforce proposal timeout cooldowns 2026-09-01 19:32:38 +01:00
Josh Creek 455055c67c feat(multiplayer): enforce proposal decline cooldowns 2026-09-01 19:30:45 +01:00
Josh Creek da92be73ef feat(multiplayer): cap websocket connections per player 2026-09-01 19:27:45 +01:00
Josh Creek 515b06d97c feat(multiplayer): bound control-plane websocket traffic 2026-09-01 19:25:34 +01:00
Josh Creek b110bfc5f7 docs(multiplayer): reconcile session progress 2026-09-01 19:24:01 +01:00
Josh Creek b4d2dd8a9f feat(multiplayer): protect control-plane rollouts 2026-09-01 19:23:22 +01:00
Josh Creek bb9f25ee8d fix(multiplayer): wire control-plane runtime secrets 2026-09-01 19:22:06 +01:00
Josh Creek 81346ac149 feat(multiplayer): harden control-plane availability 2026-09-01 19:20:53 +01:00
Josh Creek e1abac1271 feat(multiplayer): enforce account and IP rate limits 2026-09-01 19:18:40 +01:00
Josh Creek aa97259165 feat(multiplayer): declare control-plane rate limits 2026-09-01 19:17:09 +01:00
Josh Creek 9cc68d7707 feat(multiplayer): wire control-plane request limits 2026-09-01 19:15:50 +01:00
Josh Creek 6366b5e1f6 feat(multiplayer): add degraded admission mode 2026-09-01 19:14:28 +01:00
Josh Creek d04523accd feat(multiplayer): package observability resources 2026-09-01 19:10:10 +01:00
Josh Creek 05e8a1b398 docs(training): record stage six league evidence 2026-09-01 19:08:52 +01:00
Josh Creek e56850a236 fix(training): make policy evaluation portable 2026-09-01 18:56:31 +01:00
Josh Creek 066aee96cc test(training): add reproducible verification target 2026-09-01 18:53:56 +01:00
Josh Creek e78f805c92 feat(multiplayer): spread allocator replicas 2026-09-01 18:52:15 +01:00
Josh Creek 34cc994598 feat(multiplayer): protect allocator availability 2026-09-01 18:51:18 +01:00
Josh Creek 398d6ade61 feat(multiplayer): harden allocator rollout 2026-09-01 18:50:09 +01:00
Josh Creek 2e1c010fa2 feat(multiplayer): deploy allocator role 2026-09-01 18:48:51 +01:00
Josh Creek 95e82cc719 feat(multiplayer): wire allocator metrics discovery 2026-09-01 18:46:31 +01:00
Josh Creek 9a72dd5eab feat(multiplayer): expose allocator quota metrics 2026-09-01 18:43:55 +01:00
Josh Creek fc000e71d5 docs(multiplayer): include quota migration in phase index 2026-09-01 18:39:44 +01:00
Josh Creek 4a1a6f6697 docs(multiplayer): record shared quota evidence 2026-09-01 18:38:44 +01:00
Josh Creek 72e8d27633 feat(multiplayer): add shared allocation quota 2026-09-01 18:38:06 +01:00
Josh Creek 55706ba9ea test(multiplayer): cover matcher load boundary 2026-09-01 18:32:40 +01:00
Josh Creek 71935e61b5 test(multiplayer): add chaos recovery smoke 2026-09-01 18:30:09 +01:00
Josh Creek 25236cc0a1 docs(multiplayer): update phase eight index 2026-09-01 18:28:25 +01:00
Josh Creek 4b243f1a47 test(multiplayer): add release promotion gate 2026-09-01 18:26:56 +01:00
Josh Creek 181a928c87 feat(multiplayer): add regional allocation budget 2026-09-01 18:25:25 +01:00
Josh Creek c4c2ada1f6 test(multiplayer): add api load gate 2026-09-01 18:23:22 +01:00
Josh Creek 76c1c3d600 fix(multiplayer): publish stalled allocation recovery 2026-09-01 18:19:28 +01:00
Josh Creek 7c044b7094 test(multiplayer): harden agones allocation gate 2026-09-01 18:16:54 +01:00
Josh Creek e3fad7064b fix(training): restore ai reward script parsing 2026-09-01 18:13:53 +01:00
Josh Creek c65cd2d17e docs(multiplayer): sync fleet wiring status 2026-09-01 18:11:14 +01:00
Josh Creek 3317574bf2 fix(multiplayer): fence recovered allocation tuples 2026-09-01 18:06:56 +01:00
Josh Creek bf396afcaf fix(multiplayer): recover ambiguous agones allocations 2026-09-01 18:05:43 +01:00
Josh Creek b72a7cf843 test(multiplayer): cover compose allocator binding 2026-09-01 18:02:05 +01:00
Josh Creek 063dff463d test(multiplayer): drive compose proposal orchestration 2026-09-01 17:58:37 +01:00
Josh Creek 00d6b1edd3 test(multiplayer): cover compose queue lifecycle 2026-09-01 17:56:47 +01:00
Josh Creek a57b582cf1 docs(multiplayer): record supervisor compose coverage 2026-09-01 17:54:40 +01:00
Josh Creek b33f681ffa test(multiplayer): exercise compose supervisor drain 2026-09-01 17:54:16 +01:00
Josh Creek b1783abdce test(multiplayer): isolate agones lifecycle smoke 2026-09-01 17:52:02 +01:00
Josh Creek 88eb510dc3 test(multiplayer): add allocated compose smoke flow 2026-09-01 17:50:52 +01:00
Josh Creek 8129bb2571 fix(multiplayer): correct allocated fleet entrypoint 2026-09-01 17:47:15 +01:00
Josh Creek 6042c3b154 ci(multiplayer): run agones integration gate 2026-09-01 17:44:13 +01:00
Josh Creek 9b76d47c52 test(multiplayer): add disposable kind agones gate 2026-09-01 17:43:35 +01:00
Josh Creek e934bbfe44 test(training): cover wall rebound geometry 2026-09-01 17:39:53 +01:00
Josh Creek e376675fa6 feat(training): add wall and rebound curriculum states 2026-09-01 17:37:52 +01:00
Josh Creek 7170400f49 test(multiplayer): verify observability manifests locally 2026-09-01 17:34:15 +01:00
Josh Creek 4c1ed87344 test(training): verify 2v2 evaluator command 2026-09-01 17:32:10 +01:00
Josh Creek 7b2f9c26f4 feat(training): add opt-in teamplay evaluation 2026-09-01 17:30:40 +01:00
Josh Creek 9004800326 test(training): require multi-seed curriculum evaluation 2026-09-01 17:26:44 +01:00
Josh Creek 533ac1afab ops(multiplayer): wire Prometheus service discovery 2026-09-01 17:24:21 +01:00
Josh Creek dc901f5951 docs(multiplayer): mark observability local gates 2026-09-01 17:23:25 +01:00
Josh Creek 67da422ea6 ops(multiplayer): add control-plane alert rules 2026-09-01 17:22:09 +01:00
Josh Creek 0bf33e7fe8 feat(multiplayer): export queryable API latency histograms 2026-09-01 17:21:13 +01:00
Josh Creek 20f376f713 docs(multiplayer): index local completion status 2026-09-01 17:17:37 +01:00
Josh Creek d0c96422b2 fix(multiplayer): harden observability redaction 2026-09-01 17:15:44 +01:00
Josh Creek 65f0ad5dfd test(multiplayer): strengthen local verification gate 2026-09-01 17:14:18 +01:00
Josh Creek 98ff2aed81 test(multiplayer): detect macOS Godot bundle 2026-09-01 17:13:18 +01:00
Josh Creek 0787702f23 test(multiplayer): record ENet integration gate 2026-09-01 17:11:55 +01:00
Josh Creek f1b9527d3f test(multiplayer): verify domain fuzz targets 2026-09-01 17:10:26 +01:00
Josh Creek c5f6c95ca5 docs(multiplayer): close snapshot disconnect race note 2026-09-01 17:09:23 +01:00
Josh Creek d1bcb51225 test(multiplayer): add consolidated local gate 2026-09-01 17:07:44 +01:00
Josh Creek f1b8366531 feat(multiplayer): export bounded API metrics 2026-09-01 17:06:38 +01:00
Josh Creek d85c8b8194 feat(multiplayer): expose action retry in matchmaking UI 2026-09-01 17:03:31 +01:00
Josh Creek 6ef55affcb feat(multiplayer): add idempotent client mutation retries 2026-09-01 17:02:55 +01:00
Josh Creek 9ae01ecc5a fix(multiplayer): propagate allocated playlist 2026-09-01 17:00:37 +01:00
Josh Creek 8bd1455a2c feat(multiplayer): propagate allocated launch configuration 2026-09-01 16:58:09 +01:00
Josh Creek 315c524c42 feat(multiplayer): propagate allocated launch configuration 2026-09-01 16:57:27 +01:00
Josh Creek 75cb8faac4 feat(multiplayer): acknowledge supervisor shutdown 2026-09-01 16:54:40 +01:00
Josh Creek cc12260225 feat(multiplayer): expose server shutdown acknowledgement 2026-09-01 16:50:26 +01:00
Josh Creek 1d926e705b fix(multiplayer): preserve planned shutdown reason 2026-09-01 16:44:42 +01:00
Josh Creek 4e88ea80f3 feat(multiplayer): handle planned shutdowns on clients 2026-09-01 16:43:47 +01:00
Josh Creek b24f9fc448 feat(multiplayer): notify clients before server shutdown 2026-09-01 16:42:15 +01:00
Josh Creek 8c2dc66c7c fix(multiplayer): release innocent no-show participants 2026-09-01 16:39:46 +01:00
Josh Creek 334d8a26ac feat(multiplayer): enforce allocated initial connect policy 2026-09-01 16:36:26 +01:00
Josh Creek 74e50caf70 feat(multiplayer): publish allocation state events 2026-09-01 16:31:17 +01:00
Josh Creek d15d16d593 feat(multiplayer): publish allocation state events 2026-09-01 16:30:35 +01:00
Josh Creek ec82367c50 fix(multiplayer): close initial connect sweep rows 2026-09-01 16:28:08 +01:00
Josh Creek a6d2bdf8bd feat(multiplayer): sweep initial connect outcomes 2026-09-01 16:27:15 +01:00
Josh Creek bae7458668 feat(multiplayer): apply initial connect outcomes durably 2026-09-01 16:26:06 +01:00
Josh Creek b7642ad2be feat(multiplayer): model initial connect outcomes 2026-09-01 16:21:40 +01:00
Josh Creek 3dbecb0bd5 fix(multiplayer): fence roster topology at persistence 2026-09-01 16:20:31 +01:00
Josh Creek a439a1059b fix(multiplayer): fence roster topology at persistence 2026-09-01 16:20:01 +01:00
Josh Creek 80d6ee8cf5 fix(multiplayer): validate allocated roster shape 2026-09-01 16:18:31 +01:00
Josh Creek 69a8402f11 fix(multiplayer): honor assigned team and slot 2026-09-01 16:17:10 +01:00
Josh Creek 5812386676 feat(observability): log authenticated read routes 2026-09-01 16:14:20 +01:00
Josh Creek e62909d457 docs(multiplayer): mark identity and launch gates 2026-09-01 16:10:39 +01:00
Josh Creek 12b9712a8d test(multiplayer): lock allocated launch overrides 2026-09-01 16:09:57 +01:00
Josh Creek b4ea50d76a fix(multiplayer): reclaim slots by signed identity 2026-09-01 16:08:01 +01:00
Josh Creek bdb3c8f4a7 fix(multiplayer): gate allocated matches on full roster 2026-09-01 16:03:43 +01:00
Josh Creek 498f219ab9 fix(multiplayer): align NA fleet region runtime 2026-09-01 16:01:38 +01:00
Josh Creek c0861bfcad feat(multiplayer): wire allocated fleet runtime 2026-09-01 16:00:03 +01:00
Josh Creek 68e76b5feb feat(multiplayer): deliver allocated server rosters 2026-09-01 15:54:07 +01:00
Josh Creek 863cf61f1a test(multiplayer): verify result websocket fanout 2026-09-01 15:47:08 +01:00
Josh Creek 802e5fc96f test(multiplayer): fence conflicting result races 2026-09-01 15:44:47 +01:00
Josh Creek f3b56f70e3 feat(multiplayer): dispatch completed result events 2026-09-01 15:43:32 +01:00
Josh Creek 9ec707674a test(multiplayer): verify allocated supervisor registration 2026-09-01 15:39:28 +01:00
Josh Creek 207ab47866 test(multiplayer): verify allocator worker lifecycle 2026-09-01 15:34:51 +01:00
Josh Creek dad26a164c fix(multiplayer): recover stale proposal mutations 2026-09-01 15:31:01 +01:00
Josh Creek 04b5d3b29d feat(multiplayer): verify ranked profile delivery 2026-09-01 15:29:49 +01:00
Josh Creek d081a72b9a feat(multiplayer): wire ranked profile runtime policy 2026-09-01 15:28:37 +01:00
Josh Creek f096e8ff0b test(multiplayer): verify live assignment delivery 2026-09-01 15:25:36 +01:00
Josh Creek 79a6092b28 feat(multiplayer): wire production proposal outbox delivery 2026-09-01 15:21:49 +01:00
Josh Creek aa93aeec95 test(multiplayer): verify two-player proposal round trip 2026-09-01 15:17:53 +01:00
Josh Creek 1e1db3525e docs(multiplayer): record the workload-token delivery channel closing
Updates §8.10 and §8.28's cross-reference to reflect the previous two
commits: the token now binds allocation_id only (resolved durably at verify
time, not embedded match/server), and the delivery channel itself is wired
end to end (cmd/allocator mints -> Agones annotation -> supervisor reads ->
Authorization header), not just the verification core. Records what's left:
this has only run against HTTP-level Agones fakes, never a real cluster, so
the object_meta JSON casing remains unverified from this sandbox; fleet.yaml
still needs its own environment-specific manifest values.
2026-09-01 14:58:30 +01:00
Josh Creek 544f76c502 feat(multiplayer): deliver signed workload tokens via Agones allocation annotation
Closes the remaining gap the previous two commits left open: WorkloadVerify
itself worked, but nothing minted a real token at allocation time or handed
it to a running pod, so it had no real caller yet.

agones.Client gains WorkloadSecret/WorkloadTokenTTL. When set, Allocate
mints a signed workload token for the allocation (allocation_id is known at
request-construction time, before Agones has picked a server -- see the
previous commit for why that's the only identifier the token can bind) and
requests it as a third cosmic-clash.io/workload-token annotation, alongside
the existing match-id/allocation-id ones. Left unset (the default), Allocate
requests no such annotation, so a deployment not yet using this path is
unaffected. cmd/allocator wires it from a new --workload-secret /
COSMIC_CLASH_WORKLOAD_SECRET flag (must match cmd/control-plane's own), with
a startup warning if left unset.

supervisor.Supervisor.workloadToken() resolves the bearer credential for
control-plane registration: an explicitly configured --workload-token-path
always wins (kept for a future Kubernetes-projected-JWT WorkloadVerify path,
not yet wired server-side), otherwise it falls back to the
cosmic-clash.io/workload-token annotation on the allocated GameServer --
the same annotation-fallback pattern matchID already used for
cosmic-clash.io/match-id. WorkloadTokenPath is accordingly no longer
required at construction time when ControlPlaneURL is set.

Verified: new agones test proves the annotation is requested (and parses/
verifies against the same secret, naming the right allocation) when
WorkloadSecret is configured, and that it's absent when it isn't; new
supervisor tests prove the annotation-sourced token is what's actually sent
as the Authorization bearer, and that Start fails closed with neither a
configured path nor an annotation present. Full
`go build ./... && go vet ./... && gofmt -l . && go test ./... -race` and
`go test -tags integration ./... -race` both clean.
2026-09-01 14:57:45 +01:00
Josh Creek d588898f5d fix(multiplayer): bind signed workload tokens to allocation_id only
The just-landed signed workload token embedded (allocation_id, match_id,
server_id) as claims. That doesn't actually work for its intended delivery
channel: the token is meant to be requested as a GameServerAllocation
annotation in the SAME request that asks Agones to pick a server, so at mint
time the allocator knows allocation_id (it generates it) but not yet which
server_id Agones will return -- server_id only exists in Agones's response,
after the annotation request has already been sent. Embedding it was simply
not possible for the real caller this was built for; only the (allocator ->
signed_token) unit tests and hand-constructed integration tests happened to
supply it directly, masking the gap.

Fixes it by having the token bind only allocation_id (the one identifier
actually known at mint time) plus expiry. match_id/server_id are resolved at
verify time from the durable allocations table via the new
store.AllocationBindingByAllocationID, keyed by allocation_id -- which the
allocator already records immediately after Agones responds. This is
strictly stronger, not just a workaround: a caller can no longer claim any
match/server pairing at all, even one that happens to be internally
consistent -- the binding returned is entirely durable-record-derived.

Verified: server/workload's unit tests updated for the new two-field claim
shape; server/api's Postgres integration suite gains
TestWorkloadVerifierFromSignedTokenNeverTrustsCallerSuppliedBinding (two
distinct real allocations each resolve to their own, and only their own,
match/server pairing) replacing the now-inapplicable mismatched-triple test.
Full `go build ./... && go vet ./... && gofmt -l . && go test ./... -race`
and `go test -tags integration ./... -race` both clean; the api integration
suite re-run 3x clean against a live postgres:17-alpine container.
2026-09-01 14:54:38 +01:00
Josh Creek 939b7a9584 docs(multiplayer): record WorkloadVerify closed via self-issued token
Updates §8.10 and §8.28's cross-reference in multiplayer-next.md to reflect
the previous commit: the WorkloadVerify blocker both rows named as the actual
next thing standing in the way of a working server registration/result route
is closed, via a control-plane-self-issued signed token rather than the
Kubernetes-JWT approach originally assumed necessary. Records precisely what
remains: the real delivery channel (an Agones annotation carrying a minted
token, and the supervisor reading it) and fleet.yaml's still-unaddressed
manifest wiring.
2026-09-01 14:52:07 +01:00
Josh Creek 520613aab0 feat(multiplayer): implement WorkloadVerify without a Kubernetes trust boundary
WorkloadVerify (api.Service.WorkloadVerify) was permanently unwired: both
/v1/servers/{id}/register and /v1/servers/{id}/result always 503, because
the only design considered so far was verifying a Kubernetes-projected
service-account JWT (server/workload/jwt.go), which needs a live cluster's
TokenReview/JWKS endpoint to validate against safely -- something this
sandbox cannot do without guessing at a trust boundary.

The API layer doesn't actually require that specific mechanism. serverMutation
only compares WorkloadBinding.ServerID and .MatchID (server/api/service.go);
AdvanceServerRegistration only uses .MatchID/.ServerID/.AllocationID. Nothing
downstream needs Namespace/ServiceAcct/PodUID/GameServerUID populated.

This adds a self-contained alternative: a short-lived, HMAC-signed token the
control plane mints and verifies with a secret only it holds (server/workload/
signed_token.go), the same trust model domain.SessionStore already uses for
player sessions elsewhere in this codebase. It needs no cluster to verify --
signature + expiry is fully self-contained and unit-testable.

The design's soundness rests on the delivery channel, not the crypto: the
token is meant to reach the allocated GameServer via the same Agones
GameServerAllocation annotation channel allocation.go already uses for
match-id/allocation-id, readable only by that pod's own local SDK sidecar. A
caller presenting this token has already proven, via that channel, that it is
the pod Agones allocated. (Wiring the actual annotation delivery -- extending
agones.Client.Allocate and the supervisor's token source -- is a separate,
follow-up change; this commit lands the verification core it depends on.)

store.AllocationBindingStillValid adds defense-in-depth on top of signature
and expiry: it cross-checks the token's claims against the durable
allocations table (append-only, never leaves 'ALLOCATED'), so a validly-signed
token naming an allocation that was never recorded -- or a real allocation id
paired with a mismatched match/server -- is still rejected.

api.WorkloadVerifierFromSignedToken wires the two together and is now plugged
into cmd/control-plane (new --workload-secret / COSMIC_CLASH_WORKLOAD_SECRET
flag; a startup warning is logged if it's left unset, since the route then
stays 503 exactly as before) and cmd/testkit-api (fixed test secret, since
that binary is test-only already).

Verified: new unit tests in server/workload (signature tamper, wrong secret,
expiry boundary, malformed input) and a new Postgres integration suite in
server/api (real allocation row, real signed token, acceptance / unknown-
allocation rejection / mismatched-triple rejection / the previously-503
Service.WorkloadVerify field itself) -- both run clean with -race across
multiple passes against a live postgres:17-alpine container. Full
`go build ./... && go vet ./... && gofmt -l . && go test ./... -race` and
`go test -tags integration ./... -race` both clean.
2026-09-01 14:51:21 +01:00
Josh Creek 330f99bb0e docs(multiplayer): record the cancel-cascade fix in task 8.17 2026-09-01 14:40:48 +01:00
Josh Creek 79318b56bd feat(multiplayer): cascade a queue-ticket cancel into an open proposal
The last two commits fixed the severe stranding bug in decline and
timeout, but left a real responsiveness gap: cancelling a ticket
directly while it's part of an OPEN proposal used to leave the OTHER
participant waiting out the full response window for something the
system already knew couldn't happen -- their proposal partner just
abandoned the queue. ProposalExpireRequeueSQL eventually rescues them,
but only after the full window elapses, not immediately.

CascadeCancelToOpenProposal runs inside the same transaction as the
cancel itself: if the cancelled ticket belonged to a currently-OPEN
proposal, decline that proposal right now and requeue every other
participant immediately via the same ProposalDeclineRequeueSQL the
decline path already uses. The cancelling player's own ticket
correctly stays CANCELLED, not swept back into the requeue meant for
everyone else (ProposalDeclineRequeueSQL only touches tickets still at
PROPOSED).

Covered by a real PostgreSQL integration test: cancelling one
participant's ticket mid-proposal immediately declines the proposal
and requeues the other participant with a refreshed expiry, while the
cancelling player's own ticket stays CANCELLED. First draft used a
stale expected revision (0) for the cancel call -- CreateProposal's
own QueueTicketProposeSQL already bumps a ticket's revision to 1 when
forming the proposal, caught immediately by actually running the test
against real Postgres rather than assuming. Clean across 5 runs after
the fix, plus the full integration and unit suites.
2026-09-01 14:40:30 +01:00
Josh Creek fe0a0b72a8 docs(multiplayer): record the proposal-timeout requeue fix in task 8.17 2026-09-01 14:36:50 +01:00
Josh Creek 4627dd58fb fix(multiplayer): requeue every participant after a proposal times out
The timeout sibling of the previous commit's decline fix: a proposal
that simply times out (the 10s window elapses with no unanimous
response) hits ProposalExpireSQL/ProposalParticipantExpireSQL, and
neither of those -- same as the decline path -- ever touched
queue_tickets. Same severe consequence: every participant still
holding a PROPOSED ticket, response pending or already accepted, is
left stranded (invisible to the matcher, blocking a fresh
queue_create, renewable forever by heartbeat) with no automatic way
back into matchmaking. This path is reached from both GetProposal
(the recovery/read boundary -- a client that missed the expiry event
entirely) and RespondToProposal (a response arriving after the
window), so both needed the fix.

ProposalExpireRequeueSQL mirrors ProposalDeclineRequeueSQL, guarded on
state = 'EXPIRED' so it's safe to call unconditionally right after
ProposalExpireSQL: a no-op on a proposal that's still OPEN, and a
no-op on a proposal that was already EXPIRED on a prior pass (nothing
left at PROPOSED to requeue a second time).

Covered by a real PostgreSQL integration test via GetProposal (nobody
ever responds; recovering the proposal well after its window expires
it and must requeue both participants), confirming both tickets land
back at QUEUED with a refreshed expiry and are visible again to
ListQueuedCandidates. Clean across 5 runs, plus the full integration
and unit suites.
2026-09-01 14:36:34 +01:00
Josh Creek c8c363e667 docs(multiplayer): record the proposal-decline requeue fix in task 8.17 2026-09-01 14:33:46 +01:00
Josh Creek 6237a25a69 fix(multiplayer): requeue every participant after a proposal is declined
Found by reading the code, not a failing test: no path anywhere
transitioned a queue ticket from PROPOSED back to QUEUED after a
proposal was declined. A stranded PROPOSED ticket is invisible to the
matcher (ListQueuedCandidates only ever reads state='QUEUED'), still
counts as that player's one active ticket (blocking a fresh
queue_create), and is renewable forever by an ordinary heartbeat --
a player proposed a match with someone who then declines had no way
back into matchmaking without realising, on their own, that they
needed to manually cancel first. This affects every participant, not
just the decliner: an uninvolved player who never even responded was
left stuck by someone else's decision.

ProposalDeclineRequeueSQL requeues every participant's ticket,
including the decliner's own -- nothing yet enforces the decline
cooldown task 8.17 documents as a separate, not-yet-built feature, so
leaving anyone behind at PROPOSED today isn't "cooldown behaviour",
it's just broken. Once that cooldown exists it can exempt the
decliner from this immediate requeue; today nothing does.

Covered by a real PostgreSQL integration test: after one player
declines, both the decliner's and an uninvolved participant's tickets
land back at QUEUED with a refreshed expiry, and -- the actual
end-to-end regression -- both are visible again to
ListQueuedCandidates, the same query the matcher itself uses. Clean
across 5 runs, plus the full integration and unit suites.
2026-09-01 14:33:30 +01:00
Josh Creek 801a8487f5 docs(multiplayer): record the matcher crash-loop fix and pause on native Godot crashes
The two-player proposal integration attempt (Game/tests/control_plane_proposal_smoke.*,
scripts/verify_control_plane_proposal_integration.sh) is left uncommitted
on disk: it found the matcher crash-loop bug, but running it required two
simultaneous headless Godot processes, and this session had been
intermittently crashing the native Godot engine (confirmed by the user
to be caused by this session's testing, not unrelated activity) --
9 macOS crash reports today, clustered in a way that doesn't obviously
implicate only the concurrent-process case. Stopped launching further
Godot processes pending that investigation rather than keep reproducing
a crash to chase a test result.
2026-09-01 14:29:53 +01:00
Josh Creek 3168dd9897 fix(multiplayer): stop the matcher worker crashing on a routine no-match pass
Found building the two-player proposal integration test (next commit):
Worker.Run treated ANY RunOnce error as fatal to the whole loop,
including domain.FormFromQueue's "no compatible candidates" -- which
is not a failure, it's the completely routine and expected outcome of
a queue whose currently-waiting players don't share a verified region
yet. Two real players with no common region formed exactly this
shape, and the entire matcher process exited -- taking matchmaking
down for every OTHER player in the same playlist, not just the
incompatible pair, since cmd/matcher runs one process per playlist.
Worse: on a real supervisor restart, the same still-incompatible
candidates are still queued, so it would crash again immediately --
an actual crash loop, not a one-off.

RunOnce's own per-call contract (return an error for source failure,
bad formation, mixed playlist, an incomplete batch, a lost durable
claim) is deliberately tested and unchanged. The fix is entirely in
Run's loop: only the three genuinely static misconfiguration errors
(nil dependencies, unsupported playlist, invalid size -- true on every
future pass just as much as this one, so retrying can never help) now
stop it, via new exported sentinels (ErrWorkerNotConfigured,
ErrUnsupportedPlaylist, ErrInvalidMatcherSize) and errors.Is. Every
other RunOnce error is a single pass's worth of "no match formed this
time" and Run keeps polling.

Covered by two new tests: Run recovering from a first-pass error and
still forming a proposal once the pool becomes viable (a real
concurrent goroutine driving Run, not just calling RunOnce directly --
Run's own loop had no test coverage at all before this), and Run still
stopping immediately on a genuine configuration error. Both clean
across 3 runs with -race.
2026-09-01 14:26:19 +01:00
Josh Creek 01bb9a9431 docs(multiplayer): record the RankedProfileProvider fix and its coverage 2026-09-01 14:20:44 +01:00
Josh Creek 57fe6f4acc test(multiplayer): extend the real integration test to cover ranked profile fetch
Adds fetch_ranked_profile() right after login, asserting the expected
404 for a brand-new identity round-trips correctly through the real
RankedProfileProvider (previous commit) before proceeding to the
existing queue_create -> heartbeat -> cancel sequence. Verified stable
across 3 consecutive full runs.
2026-09-01 14:20:09 +01:00
Josh Creek a1ae36a54c fix(multiplayer): wire a durable RankedProfileProvider
Same discovery pattern as ResultSubmitter/SessionIssuer, one level
deeper: api.Service.rankedProfile and .profile both only ever read
from an in-memory RankedProfiles map with no durable-store equivalent
at all -- not "adapter exists but unwired" this time, there was no
adapter. Every real request to GET /v1/profile/ranked or /api/v1/profile
always 404'd regardless of a player's actual rating.

Add RankedProfileProvider (an interface, not a struct-literal adapter
this time) and store.PostgresRankedProfiles reading the ratings table;
Service.rankedProfileFor prefers it when set and falls back to the
map otherwise, so every existing test/direct Service literal keeps
compiling and passing unchanged. A missing ratings row maps to the
exact same (zero value, false, nil) the map lookup already produced,
preserving existing not-found semantics rather than reinterpreting
them. LastSeasonID/SeasonHistory are deliberately left unset -- the
ratings table has no season pointer, and reconstructing history needs
its own query and display semantics, not bundled in here speculatively.

Wired into both cmd/control-plane and cmd/testkit-api. Verified
against real PostgreSQL via curl: a fresh identity's ranked profile
correctly 404s through the real adapter (same behavior as before,
now for a real reason instead of an empty map).
2026-09-01 14:20:04 +01:00
Josh Creek 8a9972b6fc docs(multiplayer): record cancel_queue coverage in the integration test 2026-09-01 14:16:24 +01:00
Josh Creek f7657ad9ad test(multiplayer): extend the real integration test to cover queue cancel
Adds a fourth real round trip to control_plane_smoke.gd: heartbeat ->
cancel_queue -> CANCELLED, using the same idle-wait pattern the
heartbeat step already needed. Verified stable across 3 consecutive
full runs (real Postgres, real testkit-api, real headless Godot
client), plus the full Go and Godot unit suites clean.
2026-09-01 14:16:06 +01:00
Josh Creek 6edaedb50d docs(multiplayer): record the real Go+Postgres+Godot integration test and its findings 2026-09-01 14:14:37 +01:00
Josh Creek 521b8122ac test(multiplayer): add a real Go+Postgres+Godot end-to-end integration test
Every existing test of the client/control-plane boundary is either a
Go unit test with a mocked HTTP layer or a GDScript unit test with no
network at all (multiplayer-next.md 8.40's own evidence names "live
multi-process control-plane/game verification" as remaining). Nothing
before this actually ran the real compiled Go binary, a real
PostgreSQL instance, and a real headless Godot process talking real
HTTP to each other -- and it immediately found a real bug (previous
commit).

server/cmd/testkit-api is a new, deliberately separate, clearly-marked
test-only binary wired identically to cmd/control-plane except for
SteamLogin: cmd/control-plane has no way to authenticate against a
real Steam Web API from this sandbox (task 8.7's own documented
blocker), so testkit-api accepts any non-empty ticket string and
derives a deterministic identity instead. This bypass is confined to
its own binary -- never a flag on cmd/control-plane, never referenced
by any Dockerfile stage or Kubernetes manifest -- specifically so it
can't become a footgun on the real one.

Game/tests/control_plane_smoke.gd drives the real ControlPlaneClient
autoload through login -> queue_create -> heartbeat against a real
server and prints SMOKE PASS/FAIL, matching the existing net_smoke.gd
convention. scripts/verify_control_plane_integration.sh orchestrates
both sides (real postgres:17-alpine, the built testkit-api binary, the
Godot client) end to end.

Two real bugs surfaced building this, both fixed and re-verified, not
just the target bug: the smoke script's own use of `go run` left a
zombie process that survived cleanup and squatting on its port
corrupted the NEXT run with a misleading "http=401 unauthorized" (now
builds and runs a real binary directly, plus a belt-and-suspenders
port-kill in cleanup); and calling heartbeat() synchronously from
within a request_succeeded handler produced a spurious "Busy" because
ControlPlaneClient's own internal resync (see previous commit) was
still in flight -- the test now waits for ControlPlaneClient to go
idle via a real Timer (call_deferred alone floods the message queue
without ever yielding a frame for the in-flight request to complete).

Verified stable across 3 consecutive full runs: real PostgreSQL
container up, migrations applied, testkit-api built and started, real
headless Godot client round-tripping login/queue/heartbeat, clean
teardown with no leftover processes, containers, or bound ports each
time.
2026-09-01 14:13:52 +01:00
Josh Creek 8fa53b778c fix(multiplayer): stop an infinite queue-ticket resync loop at revision 0
Found via a new real end-to-end integration test (next commit), not by
inspection: a client that just called begin_queue() and receives the
server's first confirmation at the same revision (0) always treated
it as a conflict and requested a resync -- forever, since the resync
response is itself a same-revision confirmation hitting the exact same
false mismatch. A real Godot client against a real running server
would loop on GET /v1/queue/{id} without ever settling into QUEUED.

Root cause: apply_ticket_update()'s incoming_revision == revision
branch never adopts fields on acceptance, but _ticket_differs()
compared expires_at_unix -- a field begin_queue() has no way to set in
advance, since it doesn't know the server-assigned expiry yet. Every
first same-revision confirmation therefore looked like a conflict
unconditionally, not just occasionally.

Fix: exclude expires_at_unix from the conflict check (a differing
expiry at the same revision is expected, not a sign of corruption --
real conflicts are still caught via state/playlist), and adopt it on
acceptance so the field doesn't just become permanently stale instead.
The existing "same-revision conflict requests recovery" unit test
still passes unchanged: its fixture differs on `state`, not
expires_at_unix, so it was never actually exercising this bug.
2026-09-01 14:13:36 +01:00
Josh Creek e5c4e0b89a fix(multiplayer): wire SessionIssuer in the real control-plane binary
Same pattern and same discovery method as the ResultSubmitter fix:
store.PostgresSessions already implements SessionIssuer.Issue (used by
steamSession() to mint sessions) as well as SessionBackend.Authenticate
(used to verify them), and was already wired for the latter -- but not
the former, so /v1/session/steam always 503'd with auth_unavailable
even before considering whether SteamLogin (the real, still-correctly-
unwired Steam blocker) was available. Wire it: same struct value,
second field.

Not independently visible via a black-box HTTP test yet -- SteamLogin
still nil means the handler's first guard clause still 503s before
ever reaching SessionIssuer, so the observable symptom is unchanged
until Steam access exists. Verified by reading the handler's actual
branch order, not by a test that would currently pass for the wrong
reason.
2026-09-01 14:04:10 +01:00
Josh Creek 77c04a57a9 docs(multiplayer): record the WorkloadVerify gap as the real blocker for 8.9/8.10/8.28 2026-09-01 14:00:12 +01:00
Josh Creek 80a47d850e fix(multiplayer): wire the ResultSubmitter adapter; pin the deeper gap it exposed
Investigating the fleet.yaml wiring task found something more
fundamental than a manifest problem: cmd/control-plane/main.go never
wires WorkloadVerify, and store.PostgresResults (a ready-made,
already-correct ResultSubmitter adapter matching the interface
exactly) was referenced from nowhere outside its own file -- not even
a test. Both server-authenticated routes this session built
(/v1/servers/{id}/register and the pre-existing /result) are
completely unreachable in the actual running control-plane binary
today: Service.serverMutation treats a nil WorkloadVerify as fatal
for both routes regardless of ServerRegistrar/ResultSubmitter being
present, so every real request 503s.

Wire the safe, obviously-correct half: ResultSubmitter now uses
store.PostgresResults{DB: db}, same pattern as ServerRegistrar.

Deliberately NOT attempting a WorkloadVerify implementation here.
server/workload/jwt.go's ParseAndValidate needs a pre-known "expected"
WorkloadBinding to construct its policy against (itself needing a
durable per-allocation lookup that doesn't exist yet) plus a real
cryptographic SignatureVerifier -- which for a Kubernetes projected
service account token means either fetching/caching the cluster's own
JWKS or delegating to the API server's TokenReview endpoint, a
different verification model that doesn't fit ParseAndValidate's
signature-callback shape at all and would need its own domain-level
adapter. This is authentication-critical code with no existing
wiring example anywhere in the codebase to follow, and the actual
trust boundary (a live cluster's key material) can't be validated
from this sandbox regardless of how carefully the client code is
written. Building it fast under this session's already-heavy pace
risked a subtle, dangerous mistake far more costly than leaving the
gap named precisely, which is what this commit does instead.

Added TestServerRoutesRequireWorkloadVerifyToBeWired: pins the
current 503-on-every-request behavior as an explicit, visible
regression trip-wire rather than a silent gap -- it's designed to
start failing (and be updated, not deleted) the day WorkloadVerify is
actually wired.
2026-09-01 13:59:34 +01:00
Josh Creek bf160e4237 docs(multiplayer): record stalled-allocation reclaim, closing 8.28's health-reclaim item 2026-09-01 13:55:22 +01:00
Josh Creek fc2faf9723 feat(multiplayer): reclaim stalled allocations without penalising players
Closes the last named item on task 8.28 (Health-reclaim): nothing
currently detects or cleans up a match stuck in
ALLOCATING/PROCESS_READY/ASSIGNMENT_READY forever because its server
crashed or was reclaimed by Agones as unhealthy before ever
registering -- players would wait indefinitely for a match that was
never coming.

The design question this was blocked on -- does an abandoned match
auto-requeue its players, or fail and make them re-queue -- isn't
actually open: task 8.50's own stated acceptance criterion already
answers it ("infrastructure-caused cases cannot penalise affected
players"). A server-side crash/reclaim is exactly that, not player
behaviour, so store.ExpireStalledAllocations fails the match but
requeues every participant's ticket to QUEUED with a fresh expiry
(matching the ordinary 30s queue window), releases their
match_participants row (participation_active = false, so they're
matchable again immediately), all inside one FOR UPDATE SKIP LOCKED
pass so a second maintenance replica continues past whatever a
concurrent one is already reclaiming.

Wired into cmd/maintenance alongside the existing season-rollover
sweep: --stalled-allocation-deadline (default 2m) and
--stalled-allocation-batch (default 100).

Covered by a SQL-fragment test and a real PostgreSQL integration test:
two matches (one genuinely stalled, one recent), confirming the
deadline boundary is respected (recent match untouched), both
stranded participants' tickets requeue with a refreshed expiry, the
match_participants row releases, and a second pass doesn't reprocess
an already-FAILED match. Verified clean across 5 runs, plus the full
integration and unit suites.
2026-09-01 13:54:54 +01:00
Josh Creek d8245047a9 docs(multiplayer): record the stdout-buffering fix, closing 8.28's detached-container item 2026-09-01 13:50:36 +01:00
Josh Creek c0a1ef94f0 fix(server): force line-buffered stdout so a detached server actually logs
Godot's stdout is fully (block) buffered whenever it isn't attached to
a TTY -- true of every real deployment path this repo documents:
'docker run -d' (Docker's log driver presents a pipe), a plain
'docker run' without -d, and systemd's journal capture (also a pipe).
Confirmed directly, not from the existing gotcha note alone: a real
'docker run -d' container sat for 20+ seconds with 'docker logs'
showing nothing at all -- not even the startup line -- while the
process was confirmed alive and running (ps aux inside the container).
'docker stop' then killed it via SIGTERM (Godot has no SIGTERM hook)
without ever flushing that buffered output, losing it permanently
rather than merely delaying it.

This affects the already-shipped community server path today, not
just the not-yet-built Agones fleet path multiplayer-next.md's task
8.28 gotcha originally flagged this for -- SERVER.md's Docker AND
native-systemd instructions both route through this exact launcher
script, and journald's capture has the same non-TTY-pipe buffering
problem docker logs does.

Wrap the exec in 'stdbuf -oL -eL' (LD_PRELOAD-based line buffering,
touches no binary) when available, falling back to the unwrapped exec
otherwise so a minimal image without GNU coreutils still starts.
Re-verified the same failing scenario against the actual launcher
script in a real image: the startup line now appears within 3s of a
genuinely detached 'docker run -d'. Re-ran the full make verify-phase6
gate end to end afterward to confirm no regression: both arenas
rotated, both clients observed both goals, clean teardown.
2026-09-01 13:50:09 +01:00
Josh Creek 21c57a6d22 docs(multiplayer): record assignment-ready reporting in task 8.28 2026-09-01 13:44:53 +01:00
Josh Creek 4cad0f0cce feat(multiplayer): report assignment-ready from the supervisor
Closes the second blocker named last commit. Re-traced the actual code
path rather than trusting the earlier assumption: server_boot.gd
verifies its mounted roster file synchronously in _ready(), before
NetworkManager.host() runs and before ServerControl.set_process_ready
is ever called -- so by the time the loopback /ready probe (and thus
Agones Ready, and thus process-ready registration) succeeds, Godot has
already verified its own roster. And the API's ASSIGNMENT_READY gate
(AdvanceServerRegistrationSQL) checks only durable `assignments` rows
server-side, nothing Godot reports. No new Godot-side state was needed
-- the earlier 'needs Godot's own roster-verification state exposed'
claim was overcautious and is corrected here.

The supervisor now calls registerControlPlane(ctx, true) right after
process-ready succeeds, with a bounded retry (default 5 attempts, 2s
apart, both configurable) rather than a single attempt: the durable
`assignments` rows the server-side gate checks may not have propagated
by the first attempt, and that is expected, not fatal. Unlike a
process-ready registration failure, a persistent assignment-ready
failure does NOT kill the child -- the process is already legitimately
listening and usable, and killing a healthy process over a lagging
control-plane read would be actively harmful; it's logged to stderr
instead.

Covered by two tests: the full process-ready-then-assignment-ready
sequence and body shapes, and a retry test that fails the assignment-
ready call twice with 409 (simulating the real gate not yet
satisfied) before succeeding on the third attempt, asserting Start()
still succeeds and the child is never killed.
2026-09-01 13:44:27 +01:00
Josh Creek 4c2ade3930 docs(multiplayer): fix malformed 8.28 table row and record this session's work
An earlier edit this session (commit 4278c04d) had appended new
content to the row's evidence column using the same duplicated-prefix
text twice with an extra '|' between them, silently turning a 3-column
markdown table row into 4 columns -- caught only by literally counting
pipe characters, not by reading the rendered text. Rewritten as a
clean 3-column row: task description, then evidence, deduplicated.

Also records the game-server Docker image, the allocation-annotation
match-ID channel, and the dead ubuntu digest fix from this session's
commits.
2026-09-01 13:40:17 +01:00
Josh Creek 14e1e62deb feat(multiplayer): add game-server Docker image with the supervisor as PID 1
New additive targets, the existing server/exporter/smoke-client/enet-test
targets are byte-for-byte unchanged (make verify-phase6 re-run clean
after this, see previous commit):

  - supervisor-build: builds server/cmd/game-server-supervisor with a
    pinned golang:1.23-alpine (matching go.mod's go 1.23)
  - game-server: the same dedicated-server export as `server`, plus the
    supervisor binary, with the supervisor as ENTRYPOINT instead of the
    direct launcher script -- this is what makes the process-ready/
    assignment-ready control-plane registration from the last two
    commits actually reachable in a real deployment.

Verified with a real docker build --target game-server, not just by
reading the file: both binaries land at the expected paths with
correct permissions, and the supervisor prints its usage text when
run directly.

deploy/k8s/base/fleet.yaml does not reference this image or invoke the
supervisor's flags yet -- documented inline and in
multiplayer-next.md; that's the next concrete step, not attempted here
since the exact flag values (control-plane URL, workload-token mount
path) are deployment-environment decisions this sandbox can't make.
2026-09-01 13:38:19 +01:00
Josh Creek 9b26f867bc fix(docker): re-pin dead ubuntu base image digest
The server stage's ubuntu@sha256:571c2ab1... no longer resolves from
Docker Hub (docker pull by that exact digest returns 'not found',
verified directly, independent of anything in this Dockerfile) --
make verify-phase6 was currently broken for anyone building from a
clean cache. Found while adding a new build stage below it and
actually running the build rather than just editing the file.
Re-pinned to a digest verified to pull, and re-ran the full
make verify-phase6 gate end to end to confirm: both arenas rotated,
both headless clients observed both authoritative goals, clean
teardown.
2026-09-01 13:38:07 +01:00
Josh Creek fd18cf6ac0 feat(multiplayer): propagate match ID to an already-allocated pod via annotations
Investigated the Fleet-manifest wiring task flagged last commit and
found a deeper, previously-undesigned gap: Kubernetes env vars are
fixed at pod creation, but Agones allocates a match to an already-
running Ready pod well after it starts -- so there was no channel at
all for match-specific data (match ID) to reach that pod's processes.

Close it using the Agones GameServerAllocation API's documented
spec.metadata.annotations field, which Agones applies to the allocated
GameServer's own object_meta on success: server/agones.Client.Allocate
now requests cosmic-clash.io/match-id and cosmic-clash.io/allocation-id
annotations, and the supervisor reads them back from the same
/gameserver SDK call it already makes for the assigned port/address
(GameServer.ObjectMeta.Annotations), falling back to them for its own
control-plane registration only when MatchID isn't explicitly
configured -- an explicit value always wins, and a match ID resolvable
from neither source fails Start() closed before any HTTP call.

The exact object_meta vs objectMeta JSON key from a live Agones SDK
sidecar is not independently verified from this sandbox; documented
inline, and the fallback degrades safely (empty annotations map, same
as before this change) if it turns out to be wrong.

Covered by two new tests: the annotation actually flowing through to
the registration body, and fail-closed with neither config nor
annotation supplying a match ID (registerCalled stays false, not just
that Start() errors).
2026-09-01 13:34:08 +01:00
Josh Creek 4278c04d60 docs(multiplayer): record supervisor control-plane registration in task 8.28
Also records the concrete gap this surfaced: the Fleet manifest never
actually invokes game-server-supervisor today, so the new capability
has no deployment wiring yet -- and names exactly what's needed
(entrypoint/sidecar decision, token volume, Downward API env vars)
rather than leaving it as an unspecified 'remains'.
2026-09-01 13:28:00 +01:00
Josh Creek 0bad9e07db feat(multiplayer): report process-ready to the control plane from the supervisor
Add opt-in control-plane registration to server/supervisor: once Agones
Ready succeeds, POST /v1/servers/{id}/register (assignment_ready=false)
using a workload token read fresh from disk each call -- matching how a
Kubernetes projected service account token is rotated in place by
kubelet, unlike a cached/env-var secret. ControlPlaneURL empty (the
default) is a total no-op, so direct/Compose mode and allocated-without-
control-plane mode are both byte-for-byte unaffected; New() rejects a
half-configured registration (URL set without token path/server/match/
digest) rather than silently skipping it.

ServerID/MatchID/ImageDigest are read from env vars named by CLI flags
(--server-id-env, --match-id-env, --image-digest-env), matching the
existing --drain-token-env convention in this same binary, rather than
parsed out of the Agones SDK's own GameServer JSON -- that shape isn't
independently verifiable from here, whereas the Kubernetes Downward API
(fieldRef: metadata.name) populating an env var is a standard, safe
pattern already used elsewhere in this codebase for exactly this class
of secret.

A registration failure now kills the child (matching the existing
waitReady failure path) rather than leaving Agones-Ready-but-
control-plane-unregistered process running -- a real gap the second new
test (TestControlPlaneRegistrationFailureKillsChildRatherThanRunningUnregistered)
had to be corrected to actually exercise: its first draft omitted
ReadyURL and was failing at waitReady, before ever reaching the code
path it claimed to test.
2026-09-01 13:27:43 +01:00
Josh Creek 8b76f80b5c docs(multiplayer): record the concurrent queue-heartbeat race test in 8.14/8.46 2026-09-01 13:22:18 +01:00
Josh Creek 270ab00c52 test(multiplayer): add real concurrent queue-heartbeat revision race test
Races 5 concurrent HeartbeatQueueTicket calls, all at the same expected
revision, against a real PostgreSQL instance -- a genuinely plausible
client scenario (slow-response retry, duplicate tab/process), and one
the existing sequential stale-revision test can't exercise since it
only calls the second heartbeat after the first has already
committed. Asserts exactly one wins, the durable revision ends at
exactly 1 (not higher, which a stale winner slipping through would
produce), and every loser fails cleanly rather than hanging or
returning a raw serialization error. Stable across 6 runs with -race,
plus the full integration and unit suites.
2026-09-01 13:21:59 +01:00
Josh Creek d9e806ed27 docs(multiplayer): record real-Redis integration coverage in 8.14/8.46 2026-09-01 13:20:39 +01:00
Josh Creek 17bd7768eb test(multiplayer): add real-Redis integration coverage for the candidate index
Every existing RedisCandidateIndex test runs against miniredis -- a
from-scratch Go reimplementation of the Redis command set, not real
Redis's own float64 score encoding, TTL/expiry, or RESP behavior.
Add an opt-in integration suite (mirroring postgres_integration_test.go's
pattern: //go:build integration, COSMIC_CLASH_REDIS_ADDR-gated) plus
scripts/run_redis_integration.sh against a disposable redis:7-alpine
container, covering:

  - upsert/snapshot/remove against a real server
  - a real TTL actually waited out (not miniredis's manual
    FastForward), proving expiry really happens on the wire
  - the documented 'Redis restart or lost keyspace' repair path
    exercised against an actual FLUSHALL, not a simulated empty map,
    including that the repair actually persists back to Redis (a
    second snapshot reads it without a second durable-source call)

Verified stable across 3 runs with -race against a real container.
2026-09-01 13:20:09 +01:00
Josh Creek bf64cce947 docs(multiplayer): record the concurrent result-submission test in 8.21/8.25 2026-09-01 13:18:12 +01:00
Josh Creek caece00e7f test(multiplayer): add real concurrent result-submission rating test
Races 5 concurrent identical CompleteResultWithResult calls for the
same RESULT_PENDING match against a real PostgreSQL instance -- the
scenario behind 8.25's 'identical duplicates idempotent' claim, which
every existing result test only exercised sequentially. All five must
succeed (idempotent replay, not conflict), and the rating update must
apply exactly once: asserted by computing the expected post-match
rating independently via the same domain.CasualOpponents/UpdateRating
functions and requiring an exact match, since a doubled application
would compound the rating further away from baseline rather than
merely producing 'some' change that a looser inequality check would
miss.

First draft asserted ranked_games == 1, which doesn't hold for a
casual result (rankedIncrement is unconditionally 0 for casual by
design) -- caught by actually running it, not by inspection. Verified
clean across 6 runs with -race, plus the full integration and unit
suites.
2026-09-01 13:17:58 +01:00
Josh Creek dbdfaa5d9e docs(multiplayer): record the concurrent allocation-claim test in 8.30 2026-09-01 13:14:56 +01:00
Josh Creek 42ac34ca70 test(multiplayer): add real concurrent allocation-claim integration test
Fires more concurrent ClaimAllocation calls than there is Ready
capacity at a real PostgreSQL instance and asserts: exactly as many
win as there was capacity, every winner gets a distinct server (no
double-booking), every loser gets ErrNoCapacity rather than a raw
serialization error or a hang, and the durable game_servers.state
count matches. This is the cross-allocator-replica race 8.30 calls
out as untested -- the existing capacity test in this file claims
strictly one request at a time. Verified clean across 6 runs with
-race, plus the full integration and unit suites.
2026-09-01 13:14:46 +01:00
Josh Creek ea6939e18d docs(multiplayer): record the concurrent proposal-claim test in 8.18/8.46 2026-09-01 13:13:32 +01:00
Josh Creek 63eb43d50a test(multiplayer): add real concurrent proposal-claim integration test
Every existing Postgres integration test runs strictly one transaction
at a time, so none of them exercise the SERIALIZABLE retry-and-fence
path CreateProposal actually depends on for correctness under real
matcher-replica contention -- only concurrent goroutines against a
real connection can. Add a test that races two goroutines each
proposing a formation that shares one contested ticket (a realistic
scenario: nothing stops two matcher replicas reading the same QUEUED
ticket in the same poll window), and asserts exactly one proposal
commits, the loser's proposal and participant rows are fully rolled
back, the contested ticket ends up claimed by the winner, and -- the
part a single-threaded test can't show -- the loser's OWN uncontested
ticket also rolls back to QUEUED rather than being left stranded as
PROPOSED with no surviving proposal.

Adversarial review of my own first draft: it initially failed
deterministically (5/5 runs), but the failure was in the test itself
-- the winner/loser branch picking the loser's uncontested ticket had
the two branches swapped, so it was checking the WINNER's ticket
against the QUEUED expectation. Fixed and re-verified clean across 8
runs with -race, plus the full integration suite.
2026-09-01 13:13:16 +01:00
Josh Creek e9d9f59a6a docs(multiplayer): record queue/proposal event logging in task 8.44 2026-09-01 13:10:23 +01:00
Josh Creek 4eaa3304c3 feat(multiplayer): extend event logging to queue and proposal mutations
Wire the same Service.Log hook added for the server register/result
routes into queue create/heartbeat/cancel and proposal accept/decline:
log the resulting state on success (queue_create, queue_heartbeat,
queue_cancel, proposal_response) or 'rejected' on a domain error,
using only the ticket/proposal ID and outcome -- never the domain
error text itself, which isn't documented as credential-free.

Read-only routes (queue GET, proposal GET, assignment fetch) and the
early availability/not-found rejections that return before reaching
the domain call are deliberately not logged in this pass.

Covered by a new end-to-end test driving real create/heartbeat/cancel
and an accept followed by a stale-revision accept (fenced for real by
the domain layer behind proposalBackendSpy, unlike the dumb queue
spy), asserting the exact sequence of events logged.
2026-09-01 13:10:08 +01:00
Josh Creek 1490ff7fcf docs(multiplayer): record observability wiring in task 8.44 2026-09-01 13:07:35 +01:00
Josh Creek 3817df2a12 feat(multiplayer): wire structured event logging into server routes
server/observability existed fully unit-tested but was imported by
nothing outside its own package -- no HTTP handler ever called it, so
its credential redaction protected zero real log output. Wire it into
Service via an optional Log field (nil-safe, so every existing Service
literal keeps compiling unchanged) and call it from the two
workload-authenticated server routes -- register and result -- at
every outcome: unauthorized, rejected, conflict and success. Wire
cmd/control-plane to actually emit those events as JSON lines on
stderr.

Add a secret canary test that drives both routes end to end with
realistic bearer-token and result-nonce values and asserts neither
literal secret appears anywhere in what Service.Log actually received
-- a stronger claim than the existing observability unit test, which
only proves redact() strips a synthetic value under a denylisted key
name. redact() is still key-name-based, not content-based: a future
call site that logs a secret under an unlisted key name would not be
caught by this test or by redact() itself, only by the same discipline
applied here of never putting raw request/token bytes into Fields.

Queue, proposal and assignment mutation routes are not wired yet.
2026-09-01 13:07:23 +01:00
Josh Creek 06a4ea0a02 docs(multiplayer): record live Postgres verification and the bugs it found
Tasks 8.5, 8.14, 8.18 and 8.23 all claimed opt-in PostgreSQL execution
already covered their durable paths. It existed, but per this session's
run had apparently never actually been exercised clean: it surfaced
three real bugs (queue ticket insert param-count mismatch, an
unconditional proposal-participant timeout, a missing seasons row in
one integration test) that a passing unit-test suite could not have
caught, since the unit tests mock the driver. Record what was found,
fixed and re-verified live, and that the new migration rollback runner
is now in place.
2026-09-01 12:45:27 +01:00
Josh Creek 66d114bfe3 test(server): seed a seasons row for the ranked rollover integration test
ranked_season_rollovers.season_id has a foreign key into seasons, but
the integration test never inserted a seasons row for 'season-1' --
ApplyRankedSeasonRollover failed on the FK constraint before the
rollover logic itself ran at all. Insert a matching seasons row,
mirroring how a real 12-week season would already exist when
maintenance's rollover sweep runs. Verified against a real
PostgreSQL instance.
2026-09-01 12:44:48 +01:00
Josh Creek 6d3490da14 fix(server): gate proposal participant timeout on actual expiry
ProposalParticipantExpireSQL marked every PENDING participant on a
proposal TIMED_OUT unconditionally -- it took a proposal_id and 'now'
but never actually compared 'now' against the proposal's expires_at,
unlike its sibling ProposalExpireSQL (which does gate on
'expires_at <= $2'). Both GetProposal and RespondToProposal run this
statement on every call as a recovery step, so the very first
RespondToProposal for any proposal timed out every participant
(including the one about to respond) before checking their response,
then rejected the real accept/decline with ErrConflict. Add the same
expiry gate via an EXISTS against proposals.expires_at, matching
ProposalExpireSQL's own condition, and update the SQL-fragment test to
assert the gate is present. Verified end to end against a real
PostgreSQL instance: TestPostgreSQLProposalClaimAndResponseAreAtomic
now passes a two-participant accept/accept sequence that previously
failed on the first response.
2026-09-01 12:44:43 +01:00
Josh Creek e23243ff56 fix(server): drop extra unused argument in queue ticket insert
CreateQueueTicket passed 9 arguments to QueueTicketInsertSQL, which
only has 8 placeholders (state is a hardcoded 'QUEUED' literal in the
SQL, not $4) -- every real queue-ticket creation against PostgreSQL
failed with 'mismatched param and argument count'. Found by actually
running the opt-in Postgres integration suite (previously never
exercised locally, per its own gating) rather than trusting the unit
tests, which mock the driver and can't catch a placeholder-count
mismatch. Verified fixed against a real postgres:17-alpine container.
2026-09-01 12:44:36 +01:00
Josh Creek 67609d71c0 feat(multiplayer): add down migrations and a rollback runner
Add migrations.Rollback(ctx, db, dir, steps): reverses the N most
recently applied migrations, newest first, each in its own committed
transaction under the same advisory lock Apply uses. Down SQL lives in
migrations/down/<version>.sql (a subdirectory, so Apply's *.sql glob
over the main directory is untouched); a missing down file for a
migration being rolled back is a hard error rather than a silent
partial reversal. Wire it into cmd/migrate as --rollback=N.

Add down files for all six existing migrations, each dropping objects
in FK-safe reverse dependency order.

Adversarial review: could not run the new integration test
(TestPostgreSQLMigrationsRollBackAndReapplyCleanly, gated behind
COSMIC_CLASH_POSTGRES_DSN / scripts/run_postgres_integration.sh)
against a real database in this sandbox - Docker Desktop's own
overlayfs ran out of space pulling postgres:17-alpine, unrelated to
this change. Verified instead by hand-tracing every DROP against its
forward migration's FK graph, confirming Apply's directory glob does
not pick up the down/ subdirectory, and a clean go build/vet/test
-tags integration. Worth an explicit real run before this is trusted
in CI.
2026-09-01 12:41:30 +01:00
Josh Creek 7e5cfdeceb style(server): gofmt allocation_match_sql_test.go 2026-09-01 12:41:18 +01:00
Josh Creek 99df7e20e0 docs(multiplayer): record server registration API in task 8.28 2026-09-01 12:36:04 +01:00
Josh Creek d937cb153c feat(multiplayer): add server process/assignment-ready registration API
Add POST /v1/servers/{id}/register (and its /api/v1 contract alias),
authenticated by the same workload binding as the result route. A
game server reports its protocol version and image digest and asks
to advance ALLOCATING -> PROCESS_READY -> ASSIGNMENT_READY; the store
boundary (AdvanceServerRegistration) does this as one idempotent
SERIALIZABLE transaction that also advances every participant's queue
ticket, and gates the final transition on every participant having a
live, unexpired assignment.

Adversarial review of the surrounding routing turned up a pre-existing
bug: contractServerMutation rejected any path containing '/', so the
already-documented /api/v1/servers/{id}/result route (and this new
/register route) 404'd for every real caller despite being declared
in the OpenAPI contract. Fix it to delegate shape validation to
serverMutation, matching how contractQueueMutation handles its own
two-segment paths, and add a regression test covering both contract
routes end to end.
2026-09-01 12:35:30 +01:00
Josh Creek 4fb7ddfecf docs(multiplayer): consolidate tracking into one document
multiplayer-todo.md and multiplayer-next.md tracked overlapping
information in two places. Fold everything into multiplayer-next.md
(architecture decisions, wire format, task breakdown with checkboxes,
gotchas list, testing notes) and delete multiplayer-todo.md. Section
numbers are unchanged, so existing code comments citing them by
section/task number still resolve; update every such reference to
point at the new filename.
2026-09-01 12:32:43 +01:00
Josh Creek 9dc1cc2d6f feat(multiplayer): refresh allocator ready servers 2026-09-01 10:44:43 +01:00
Josh Creek 013eb0778b fix(multiplayer): advance tickets on allocation bind 2026-09-01 10:42:10 +01:00
Josh Creek 25fdc2c2c8 fix(multiplayer): recover recorded allocations 2026-09-01 10:40:10 +01:00
Josh Creek 55c46f56ec feat(multiplayer): run leased allocator worker 2026-09-01 10:38:45 +01:00
Josh Creek 6f7d61eafb feat(multiplayer): lease allocating match claims 2026-09-01 10:36:13 +01:00
Josh Creek 03ff8e485e feat: promote accepted proposals from API 2026-09-01 10:29:50 +01:00
Josh Creek e0ba6c6ead fix: enforce ranked match promotion size 2026-09-01 10:22:26 +01:00
Josh Creek 7807b9706b feat: promote accepted proposals into matches 2026-09-01 10:21:41 +01:00
Josh Creek 11599889fa feat: gate allocation on accepted proposals 2026-09-01 10:18:22 +01:00
Josh Creek 2d750cbcab feat: enable guarded ranked matcher role 2026-09-01 10:14:22 +01:00
Josh Creek d882469c79 feat: repair matcher candidates through redis projection 2026-09-01 10:11:54 +01:00
Josh Creek 7a3d520608 fix: bind rated result to durable receipt 2026-09-01 10:09:40 +01:00
Josh Creek dd80b52a11 feat: apply certified ratings during result completion 2026-09-01 10:08:11 +01:00
Josh Creek 388300c553 fix: validate durable result submissions 2026-09-01 10:02:29 +01:00
Josh Creek eebab1bc19 feat: add workload-authenticated result API 2026-09-01 10:01:04 +01:00
Josh Creek a70a0ebc74 feat: add projected workload JWT adapter 2026-09-01 09:57:33 +01:00
Josh Creek febc69bdef feat: gate allocator roster publication 2026-09-01 09:55:09 +01:00
Josh Creek 8b5b5333c6 fix: verify signed assignment rosters 2026-09-01 09:53:45 +01:00
Josh Creek 55e07648cf test: cover provider allocation reconciliation SQL 2026-09-01 09:52:00 +01:00
Josh Creek 0023bdab6e feat: reconcile Agones allocations durably 2026-09-01 09:51:52 +01:00
Josh Creek 931e51a647 feat: add Agones allocation client 2026-09-01 09:49:09 +01:00
Josh Creek 4bbaf0976f feat: add ranked season maintenance role 2026-09-01 09:46:57 +01:00
Josh Creek e729570010 test: cover allocator PostgreSQL claims 2026-09-01 09:45:02 +01:00
Josh Creek b1966a3423 feat: add durable allocator claim boundary 2026-09-01 09:43:33 +01:00
Josh Creek 7803e1ec7c feat: wire control plane probe recorder 2026-09-01 09:40:35 +01:00
Josh Creek def60169a8 feat: persist authenticated queue probe RTT 2026-09-01 09:40:25 +01:00
Josh Creek 25cc182793 feat: persist queue probe metadata 2026-09-01 09:37:47 +01:00
Josh Creek e170bcf0ef fix: bind matcher source to playlist 2026-09-01 09:35:00 +01:00
Josh Creek d0952adaf9 feat: add runnable casual matcher role 2026-09-01 09:32:22 +01:00
Josh Creek bdc89303b4 feat: add durable matcher worker orchestration 2026-09-01 09:30:28 +01:00
Josh Creek 18538e833b feat: wire API queue projection to Redis 2026-09-01 09:28:49 +01:00
Josh Creek fe9f6f3cb5 feat: add runnable control-plane API role 2026-09-01 09:24:05 +01:00
Josh Creek 18888ed520 feat: add PostgreSQL migration runner 2026-09-01 09:21:26 +01:00
Josh Creek 4d83ec1525 feat: add signal-bound server supervisor command 2026-09-01 09:19:25 +01:00
Josh Creek 58508bd87c feat: bound supervisor drain termination 2026-09-01 09:18:19 +01:00
Josh Creek e7c835af52 feat: add Godot Agones REST bridge 2026-09-01 09:16:41 +01:00
Josh Creek 6caf719158 feat: add allocated server readiness control 2026-09-01 09:12:10 +01:00
Josh Creek 5b80c97337 test: cover PostgreSQL season rollover 2026-09-01 09:06:10 +01:00
Josh Creek bd26aa3dc4 test: cover PostgreSQL result and outbox flow 2026-09-01 09:05:15 +01:00
Josh Creek 9d210d254a test: cover PostgreSQL proposal transactions 2026-09-01 09:04:16 +01:00
Josh Creek c8a542a3af feat: repair Redis candidates from durable source 2026-09-01 09:02:55 +01:00
Josh Creek eadaa7b54e feat: add rebuildable Redis candidate index 2026-09-01 09:01:32 +01:00
Josh Creek 414df530f0 test: expand PostgreSQL adapter coverage 2026-09-01 08:59:39 +01:00
Josh Creek 5234390931 test: add PostgreSQL integration harness 2026-09-01 08:58:28 +01:00
Josh Creek eb8eecf080 docs: record backend vet verification 2026-09-01 08:53:32 +01:00
Josh Creek 3aad68a6e6 feat: fence expired allocated reconnects 2026-09-01 08:52:12 +01:00
Josh Creek e25d61d80e feat: verify allocated join authorisations with hmac 2026-09-01 08:48:48 +01:00
Josh Creek 66a1ee8007 docs: record backend fuzz coverage 2026-09-01 08:43:06 +01:00
Josh Creek 172775c141 docs: record backend race suite 2026-09-01 08:42:13 +01:00
Josh Creek 4b01b7fc88 fix: prevent concurrent join token reuse 2026-09-01 08:41:38 +01:00
Josh Creek 68d832f7bc feat: enforce allocated join roster admission 2026-09-01 08:39:56 +01:00
Josh Creek d8ea2f4ac7 feat: connect clients from validated assignments 2026-09-01 08:37:00 +01:00
Josh Creek 82bb9baec6 docs: record packet-loss prediction verification 2026-09-01 08:34:35 +01:00
Josh Creek 9848f4b92d docs: record impaired-link prediction verification 2026-09-01 08:33:57 +01:00
Josh Creek aeb37a4c6e fix: ignore pre-history prediction acknowledgements 2026-09-01 08:32:44 +01:00
Josh Creek afcb01d155 fix: guard match simulation after transport shutdown 2026-09-01 08:27:56 +01:00
Josh Creek c5678ce877 fix: pass Godot 4.7 multiplayer test suite 2026-09-01 08:24:33 +01:00
Josh Creek 76aad61191 fix: update Godot websocket handshake API 2026-09-01 08:21:05 +01:00
Josh Creek 467c25b20c feat: expose validated assignment endpoints 2026-09-01 08:17:39 +01:00
Josh Creek 0cdb60c0d9 fix: preserve assignment event revisions 2026-09-01 08:13:35 +01:00
Josh Creek 23134796ee feat: add durable outbox dispatcher 2026-09-01 08:12:33 +01:00
Josh Creek fec4f91672 feat: bind signed rosters to assignments 2026-09-01 08:10:05 +01:00
Josh Creek 5b40bf9066 fix: fail closed for unsupported allocated transport 2026-09-01 08:08:43 +01:00
Josh Creek 63f4f11aa8 feat: publish assignment rosters atomically 2026-09-01 08:08:00 +01:00
Josh Creek f520584368 fix: expire proposals on response boundary 2026-09-01 08:06:17 +01:00
Josh Creek eef7cf28da feat: make proposal responses durable 2026-09-01 07:52:52 +01:00
Josh Creek 30b4560bd5 feat: persist participant-scoped proposal recovery 2026-09-01 07:50:11 +01:00
Josh Creek 1eb6e8f9f4 feat: wire durable assignments into API 2026-08-31 23:20:25 +01:00
Josh Creek 3ae2daec88 feat: persist player-scoped assignments 2026-08-31 23:19:23 +01:00
Josh Creek 7f7516d9a0 feat: add bounded control plane rate limiting 2026-08-31 23:17:02 +01:00
Josh Creek 3533e8ae6c feat: consume assignment matchmaking events 2026-08-31 23:15:42 +01:00
Josh Creek fe246bf54e feat: add replayable outbox adapter 2026-08-31 23:14:33 +01:00
Josh Creek 4b82347d43 docs: align transport architecture with control plane 2026-08-31 23:12:46 +01:00
Josh Creek 60fe2caf8f feat: publish matchmaking state events 2026-08-31 23:12:20 +01:00
Josh Creek 161d2cdceb fix: validate matchmaking event vocabulary 2026-08-31 23:10:31 +01:00
Josh Creek a4bc8cdac8 fix: close slow event subscribers safely 2026-08-31 23:09:16 +01:00
Josh Creek 0be51ab902 fix: reconnect matchmaking event stream 2026-08-31 23:08:24 +01:00
Josh Creek a16db39884 feat: connect Godot matchmaking event stream 2026-08-31 23:06:44 +01:00
Josh Creek d258f17852 feat: add authenticated matchmaking event stream 2026-08-31 23:05:04 +01:00
Josh Creek d77563147c test: expand offline multiplayer failure matrix 2026-08-31 23:01:34 +01:00
Josh Creek fcc5d82763 feat: expose documented control plane routes 2026-08-31 23:00:22 +01:00
Josh Creek 6b3db98327 fix: bind assignments to authenticated player 2026-08-31 22:55:22 +01:00
Josh Creek 69f1ef6be1 feat: add player-scoped assignment recovery 2026-08-31 22:54:16 +01:00
Josh Creek 99680dbf6f fix: bind queue idempotency to compatibility 2026-08-31 22:51:00 +01:00
Josh Creek 585056ccc3 feat: add Godot Steam session login 2026-08-31 22:49:05 +01:00
Josh Creek e1807d2492 fix: handle matchmaking session expiry 2026-08-31 22:47:31 +01:00
Josh Creek 3e94960f0a fix: retry queue creation idempotently 2026-08-31 22:46:45 +01:00
Josh Creek 222bbb5b84 feat: classify matchmaking recovery failures 2026-08-31 22:45:20 +01:00
Josh Creek fddbebb33b feat: display backend ranked profile 2026-08-31 22:44:21 +01:00
Josh Creek 62c1478913 feat: persist matchmaking recovery state 2026-08-31 22:42:43 +01:00
Josh Creek 66a67c931d feat: add participant-scoped proposal recovery 2026-08-31 22:41:26 +01:00
Josh Creek 550d73f1d7 fix: preserve active matchmaking on transient errors 2026-08-31 22:39:42 +01:00
Josh Creek 47550aefae feat: add matchmaking queue UI 2026-08-31 22:39:29 +01:00
Josh Creek 5106ac64da feat: add authenticated matchmaking control client 2026-08-31 22:36:05 +01:00
Josh Creek 39ebfce1bb feat: add revisioned matchmaking client state 2026-08-31 22:33:33 +01:00
Josh Creek 2379c154a5 docs: track Steam browser dependency 2026-08-31 22:30:42 +01:00
Josh Creek 5265b1738b docs: record transport feature-gate verification 2026-08-31 22:29:24 +01:00
Josh Creek 4d3a8cc217 feat: add ban policy to ticket verification 2026-08-31 22:28:45 +01:00
Josh Creek 8253d772cb feat: add verified Steam session endpoint 2026-08-31 22:26:27 +01:00
Josh Creek a2a7107dd7 feat: wire durable session authentication into API 2026-08-31 22:24:51 +01:00
Josh Creek b3284d4bd6 feat: persist authenticated sessions 2026-08-31 22:23:59 +01:00
Josh Creek ae164e625a fix: expire abandoned auth attempts 2026-08-31 22:22:33 +01:00
Josh Creek 9fe6c57b5d feat: model asynchronous Steam auth sessions 2026-08-31 22:21:31 +01:00
Josh Creek 1a43a342ea test: verify persistent queue API delegation 2026-08-31 22:18:59 +01:00
Josh Creek 59cf29949f feat: wire persistent queue backend into API 2026-08-31 22:17:32 +01:00
Josh Creek b2d68d93cf fix: make SQL queue recovery expire authoritatively 2026-08-31 22:14:30 +01:00
Josh Creek 068b66b234 fix: bind proposal claims to playlist 2026-08-31 22:13:37 +01:00
Josh Creek e37a519ef8 fix: bind proposal claims to players 2026-08-31 22:12:47 +01:00
Josh Creek a45d2ddbb7 fix: rebuild candidate cache from queue authority 2026-08-31 22:12:03 +01:00
Josh Creek 4c131db2ca docs: track durable queue adapters 2026-08-31 22:11:06 +01:00
Josh Creek 948d603c0e feat: persist queue heartbeat and cancel mutations 2026-08-31 22:10:36 +01:00
Josh Creek 9263133e64 feat: add durable queue ticket repository 2026-08-31 22:08:45 +01:00
Josh Creek 3b208ae860 fix: bind queue candidates to their owner 2026-08-31 22:05:44 +01:00
Josh Creek b47c7dc3fa fix: enforce matchmaking compatibility boundaries 2026-08-31 22:04:57 +01:00
Josh Creek b1314074a8 docs: reflect multiplayer foundation status 2026-08-31 22:03:00 +01:00
Josh Creek 52a96de8d6 feat: protect game fleet during voluntary disruption 2026-08-31 22:01:18 +01:00
Josh Creek 72d4a604c2 feat: spread game fleet across on-demand zones 2026-08-31 21:59:51 +01:00
Josh Creek 90126a4be7 feat: add fleet autoscaling baseline 2026-08-31 21:58:42 +01:00
Josh Creek b2ee9ec92d feat: validate queue compatibility metadata 2026-08-31 21:57:40 +01:00
Josh Creek 0551fb0b1f feat: add regional Agones fleet overlays 2026-08-31 21:51:37 +01:00
Josh Creek 6253b620a9 fix: restrict supervisor drain to loopback 2026-08-31 21:49:22 +01:00
Josh Creek faede927fc fix: validate Agones assigned endpoints 2026-08-31 21:48:00 +01:00
Josh Creek 307828ff7f feat: atomically complete match results 2026-08-31 21:46:32 +01:00
Josh Creek 7b6e22292a feat: sign reconnect authorisations 2026-08-31 21:44:27 +01:00
Josh Creek 4b5e40bff7 feat: persist ranked season rollovers 2026-08-31 21:43:07 +01:00
Josh Creek bf4da9fd39 feat: atomically create matchmaking proposals 2026-08-31 21:40:21 +01:00
Josh Creek 229ded8613 feat: gate proposals on formed match policy 2026-08-31 21:38:47 +01:00
Josh Creek 4dcf98cbb0 feat: form matches from queue projections 2026-08-31 21:36:00 +01:00
Josh Creek 02a11704ce feat: add authenticated probe evidence boundary 2026-08-31 21:34:27 +01:00
Josh Creek 91e536425d feat: enforce supply chain policy 2026-08-31 21:32:03 +01:00
Josh Creek 0f1cc17af6 feat: add authenticated queue recovery 2026-08-31 21:29:33 +01:00
Josh Creek 236cca30ba feat: expose authoritative ranked profile 2026-08-31 21:27:21 +01:00
Josh Creek 846663e320 feat: derive authoritative ranked tiers 2026-08-31 21:25:53 +01:00
Josh Creek 726fe1ce2e feat: gate assignment publication on allocation 2026-08-31 21:24:19 +01:00
Josh Creek 88b5ffedb2 feat: add Kubernetes multiplayer security baseline 2026-08-31 21:21:55 +01:00
Josh Creek 79e66c7a95 feat: validate workload-bound result credentials 2026-08-31 21:20:12 +01:00
Josh Creek 8d1b407bb0 feat: add authenticated proposal API 2026-08-31 21:17:15 +01:00
Josh Creek 77c01dc531 fix: reject ambiguous queue JSON bodies 2026-08-31 21:13:47 +01:00
Josh Creek cd30098eca feat: add authenticated queue HTTP API 2026-08-31 21:13:10 +01:00
Josh Creek caa875f15c fix: fence concurrent queue mutations 2026-08-31 21:09:58 +01:00
Josh Creek 58e8a5c523 fix: calculate conservative SLO percentiles 2026-08-31 21:08:49 +01:00
Josh Creek bc7136b2cb feat: add ranked season window policy 2026-08-31 21:08:10 +01:00
Josh Creek e13a64756f feat: add authoritative rating outcome scoring 2026-08-31 21:07:04 +01:00
Josh Creek 63332435d2 feat: classify match integrity separately from delivery 2026-08-31 21:05:54 +01:00
Josh Creek 4e66c5758c docs: reflect current multiplayer implementation status 2026-08-31 21:04:58 +01:00
Josh Creek 723f8aea5d test: verify offline matchmaking pipeline 2026-08-31 21:04:22 +01:00
Josh Creek c0d1c33f54 feat: add executable multiplayer SLO checks 2026-08-31 21:02:29 +01:00
Josh Creek 3dde0ffb79 feat: add credential-safe multiplayer observability 2026-08-31 21:01:30 +01:00
Josh Creek 0364d3f172 test: add offline Steam and allocator fakes 2026-08-31 21:00:31 +01:00
Josh Creek 1902084523 test: add multiplayer control-plane fuzz targets 2026-08-31 20:59:29 +01:00
Josh Creek bbabd259b6 docs: complete multiplayer threat model 2026-08-31 20:58:11 +01:00
Josh Creek 217ae263cd feat: add rebuildable candidate cache 2026-08-31 20:56:13 +01:00
Josh Creek 3b5f50023b feat: enforce ranked admission policy 2026-08-31 20:55:11 +01:00
Josh Creek 518df3a73a fix: bind reconnects to verified Steam identity 2026-08-31 20:54:16 +01:00
Josh Creek 893db17c03 feat: add authenticated supervisor drain 2026-08-31 20:52:37 +01:00
Josh Creek 7ce28559d2 feat: add revisioned resync reducer 2026-08-31 20:51:46 +01:00
Josh Creek b1b4608dd8 docs: synchronize multiplayer progress checklist 2026-08-31 20:50:24 +01:00
Josh Creek e702661388 feat: add ticket and session policy 2026-08-31 20:49:45 +01:00
Josh Creek dfe8d46d99 feat: add casual bot backfill policy 2026-08-31 20:48:10 +01:00
Josh Creek 9c6d48ae2c feat: add initial connect no-show policy 2026-08-31 20:46:52 +01:00
Josh Creek 81e68bb5fa feat: add assignment readiness gate 2026-08-31 20:45:29 +01:00
Josh Creek 2b8bce5e4b feat: add deterministic allocation policy 2026-08-31 20:43:56 +01:00
Josh Creek 9810ee543f fix: propagate allocated transport ports 2026-08-31 20:42:19 +01:00
Josh Creek a0195987bd feat: add Agones readiness supervisor core 2026-08-31 20:40:51 +01:00
Josh Creek 698413cd91 feat: validate allocated assignment manifest 2026-08-31 20:38:56 +01:00
Josh Creek ecc78b7a2a feat: add result transaction SQL boundary 2026-08-31 20:37:49 +01:00
Josh Creek a616b7637e feat: add serializable matchmaking store boundary 2026-08-31 20:36:43 +01:00
Josh Creek 7c4b64b50a feat: add durable matchmaking metadata schema 2026-08-31 20:35:34 +01:00
Josh Creek 637b522486 test: harden result annotation reconciliation 2026-08-31 20:34:50 +01:00
Josh Creek 864e4e8aaf feat: add durable result policy core 2026-08-31 20:33:16 +01:00
Josh Creek b04f3318b9 feat: add ranked reconnect policy 2026-08-31 20:31:16 +01:00
Josh Creek cc2cd80a01 feat: add ranked season rollover policy 2026-08-31 20:29:11 +01:00
Josh Creek 1793eb7621 feat: add canonical matchmaking rating engine 2026-08-31 20:25:07 +01:00
Josh Creek 7643dbc439 feat: add matchmaking proposal policy 2026-08-31 20:23:17 +01:00
Josh Creek cf212d94f9 feat: validate matchmaking latency evidence 2026-08-31 20:21:55 +01:00
Josh Creek 997175c753 docs: track queue domain progress 2026-08-31 20:20:59 +01:00
Josh Creek 6c0163c3ec feat: add retry-safe matchmaking queue domain 2026-08-31 20:20:42 +01:00
Josh Creek b79d358db9 feat: add deterministic matchmaking team partitioning 2026-08-31 20:18:43 +01:00
Josh Creek 07fe144b2f feat: add deterministic matchmaking candidate selection 2026-08-31 20:17:53 +01:00
Josh Creek f5d9c08468 feat: add matchmaking domain state core 2026-08-31 20:15:52 +01:00
Josh Creek e3119bf77c docs: mark matchmaking contracts complete 2026-08-31 20:14:04 +01:00
Josh Creek 4264a2bbd3 feat: validate allocated server compatibility 2026-08-31 20:13:48 +01:00
Josh Creek d864ce2475 feat: add allocated server compatibility config 2026-08-31 20:13:22 +01:00
Josh Creek 15fdd989e2 feat: add matchmaking durable schema migration 2026-08-31 20:12:19 +01:00
Josh Creek 5b8638e15e feat: define matchmaking state transitions 2026-08-31 20:10:51 +01:00
Josh Creek f3e7538fb7 feat: publish matchmaking v1 contracts 2026-08-31 20:09:50 +01:00
Josh Creek af8592082e docs: define matchmaking launch SLOs 2026-08-31 20:07:41 +01:00
Josh Creek 62ee3f2777 docs: lock matchmaking platform architecture 2026-08-31 20:06:45 +01:00
Josh Creek 835233672f fix multiplayer snapshot disconnect race 2026-08-31 20:05:40 +01:00
Josh Creek 8d4a0640e2 docs: finalize scalable matchmaking plan 2026-08-31 19:57:49 +01:00
Josh Creek bcc12aad19 docs(multiplayer-todo): add Phase 8 task breakdown for matchmaking and autoscaling
multiplayer-next.md carried the Phase 8 checklist but not the numbered
tasks with acceptance criteria that work actually gets picked up from.
That format lives in multiplayer-todo.md section 7, which already hosts
Phase 7 as in-progress, so Phase 8 goes there too.

Tasks 8.1-8.20 across four groups: backend service (identity, rating
store, Glicko-2, queue), server orchestration and autoscaling, playlists
and client UI, and keeping Docker/CI green. Section 0's short list gains
an index entry, and the status header now says Phase 8 is a 1.0 launch
blocker and the first phase to add a component outside the Godot
project.

Three entries are measured findings rather than plans, each of which
would break a naive implementation: stdout block-buffering making a
log-grep readiness probe hang forever, the hardcoded 7777/udp port
preventing more than one match per host, and compose.phase6-smoke.yml's
dependence on the exact behaviour allocation work would change.

Also fixes a now-false cross-reference: a Phase 4 note read 'not
Phase 8' meaning 'not a later phase', written when no Phase 8 existed.
CLAUDE.md's 'never add new work to multiplayer-todo.md' rule gains the
new-phase exception it always had in practice - Phase 7 was already
there.
2026-08-31 18:49:59 +01:00
Josh Creek 4ffa1543cc docs: design per-match server autoscaling, with measured boot time
Casual/ranked queues need servers allocated per match and shut down
afterwards, so cost is incurred only while a match runs - while the
existing Docker and CI gates keep passing unchanged.

Measured against the repo's own cosmicclash-server image rather than
estimated: the runtime image is ~148 MB of content, and boot to the
server_started line is ~870 ms on the container's own clock. That was
taken under x86_64 emulation on an arm64 host, so it is a pessimistic
bound and is recorded as one - it needs re-measuring on native Linux
before it sets any timeout.

Two findings that would each break a naive implementation, both hit
while taking that measurement:

- Godot's stdout is block-buffered off a TTY. A detached container logs
  nothing at all - server_started does not appear even after 35s - so an
  orchestrator readiness probe that greps the log hangs forever. Probe
  the UDP socket or flush explicitly.
- --port defaults to 7777 and the Dockerfile hardcodes EXPOSE 7777/udp,
  so several matches cannot share a host without a port range or an
  address per match. Being UDP, L7 ingress routing does not apply.

Also records the honest tension in 'only pay during a match': a server
must listen before players connect, and image pull plus scheduling can
dwarf 870 ms, so the recommendation is match-level scale-to-zero over a
small warm node pool rather than node-level scale-to-zero.

The rule for keeping verify-phase6 and verify-enet-integration green:
every allocation feature is opt-in via a ServerConfig flag defaulting to
current behaviour, with a second Compose file rather than mutating
compose.phase6-smoke.yml.
2026-08-31 18:45:05 +01:00
Josh Creek 3aa0f5b9c2 docs: scope casual and ranked matchmaking as a 1.0 launch blocker
Queued matchmaking had never been considered anywhere in the planning
docs - not as planned work, and not even on the explicitly-deferred
list. It is a launch requirement, so record the design before code.

Add docs/MATCHMAKING.md covering the model change (community-server ->
per-match allocation), the decision to use Steam for identity and a
project-owned backend for queue/rating/allocation, what the existing
server already provides (--max-matches=1 is the allocation primitive,
ServerConfig, the roster, MatchState), the casual/ranked ruleset split,
and the open questions - rating algorithm, team-to-individual rating,
and the server cost that allocated matches reintroduce.

Ranked is hard-blocked on Phase 7 Steam auth tickets: slot reclaim is
keyed by display name today, and a rating on a spoofable identity is
worse than no rating.

Add Phase 8 to multiplayer-next.md, and correct README/CLAUDE.md/
TECH_STACK.md, which asserted no backend exists or is planned - true
before this was scoped, wrong now.
2026-08-31 18:33:36 +01:00
Josh Creek 964094f65a docs: correct stale multiplayer/C#-backend claims, add TECH_STACK doc
CLAUDE.md and README.md described the pre-multiplayer state (local-only
MVP, planned C# backend) even though server-authoritative multiplayer,
the dedicated server, Docker/CI verification, and Steam transport have
since shipped (Phases 1-6). Update both to reflect reality and add a
docs index in CLAUDE.md pointing at multiplayer-next.md as the current
checklist.

- Add docs/TECH_STACK.md, linked from README, explaining the stack and
  why it's a single GDScript project with no separate backend.
- Add one TODO item for the video settings menu (missing presets/vsync/
  resolution scaling), blocked on the same profiling gate as the
  multiplayer 0.17 tasks.
- Pick up editor-generated .gd.uid sidecars and minor project.godot
  formatting noise from opening the project in Godot 4.7.
2026-08-31 18:20:52 +01:00
CosmicClash Training Bot c51d5ee369 chore(training): generation 5 progress after 20260829-1649-gen5-s6-league 2026-08-31 07:24:53 +01:00
CosmicClash Training Bot 6d837b2bf3 chore(training): Add 20260829-1649-gen5-s6-league checkpoints, logs, and exported policy 2026-08-31 07:19:18 +01:00
Josh Creek 4f13b4eca9 chore(training): close Stage 5 by human override, re-derive its air-touch gate
productive_air_touch_episode_fraction's 0.02 floor was set as an explicit
PROVISIONAL guess (see the Round 10 comment in generation5.py) with
instructions to re-derive it from attempt 1's measured tail. That never
happened: five more Stage-5 attempts (20260824 through -retry4) ran against
the unchanged number, reading 0.00004/0.00006/0.00002/0.00018/0.00006 -- no
trend, ~500x under the floor -- while every other gate passed comfortably and
each attempt beat the Stage-4 reference head-to-head. Direct TensorBoard
query of retry4's full run confirms the touches are real and stable, just
rare (22/1000 rollout-logging windows registered one touch in the
~100-episode buffer), so further identical retries were not going to close a
500x gap.

Lowered the floor to 0.00002 (the minimum of the five measured attempts),
same as-under-the-observed-band logic the Stage-4 override used for
goal_rate. Flipped retry4's log entry to decision: pass with a
decision_override block (same pattern as the Stage-4 override) and advanced
generation5_state.json to Stage 6 attempt 0. Documented in TRAINING.md and
flagged Stage 6's own 0.015 floor for the same metric as equally unvalidated.
2026-08-29 16:45:09 +01:00
CosmicClash Training Bot b946f78d1f chore(training): generation 5 progress after 20260828-0214-gen5-s5-intercepts-retry4 2026-08-29 00:16:31 +01:00
CosmicClash Training Bot ca17265bf1 chore(training): Add 20260828-0214-gen5-s5-intercepts-retry4 checkpoints, logs, and exported policy 2026-08-29 00:14:04 +01:00
CosmicClash Training Bot d235342889 chore(training): generation 5 progress after 20260827-0426-gen5-s5-intercepts-retry3 2026-08-28 02:14:11 +01:00
CosmicClash Training Bot 706ac9bd2c chore(training): Add 20260827-0426-gen5-s5-intercepts-retry3 checkpoints, logs, and exported policy 2026-08-28 02:11:26 +01:00
CosmicClash Training Bot 5de72b0636 chore(training): generation 5 progress after 20260826-0631-gen5-s5-intercepts-retry2 2026-08-27 04:26:36 +01:00
CosmicClash Training Bot 295be3d26a chore(training): Add 20260826-0631-gen5-s5-intercepts-retry2 checkpoints, logs, and exported policy 2026-08-27 04:24:16 +01:00
CosmicClash Training Bot 3af7ed077c chore(training): generation 5 progress after 20260825-0835-gen5-s5-intercepts-retry1 2026-08-26 06:31:14 +01:00
CosmicClash Training Bot e364a7dd06 chore(training): Add 20260825-0835-gen5-s5-intercepts-retry1 checkpoints, logs, and exported policy 2026-08-26 06:28:51 +01:00
CosmicClash Training Bot d06a67ade6 chore(training): generation 5 progress after 20260824-1052-gen5-s5-intercepts 2026-08-25 08:35:28 +01:00
CosmicClash Training Bot 6d94366693 chore(training): Add 20260824-1052-gen5-s5-intercepts checkpoints, logs, and exported policy 2026-08-25 08:32:51 +01:00
Josh Creek cb06300685 feat(training): reopen stage 5 with a gate that can see the behaviour
Stage 5 blocked after nine attempts and ~540M steps, every one on
productive_air_touch_fraction. Instrumenting the environment rather than
retuning the reward again found three separate causes, none of which was the
policy's competence.

The gate could not register the behaviour. productive_air_touch_fraction
divides by TOTAL touches in the episode, so a strong ground game dilutes it for
identical aerial play. Stage 4's entire purpose is improving that ground game
(it took forward_motion_fraction 0.24 -> 0.48), so Stage 4's success drove
Stage 5's gate toward zero and the two stages were working against each other.
It also explains why every non-zero reading in the whole lineage came from
degenerate episodes whose single touch happened to be aerial: per-episode 1.0,
which is exactly 0.0100 once meaned over SB3's 100-episode buffer, and 0.0100
was every run's observed maximum. Replaced with
productive_air_touch_episode_fraction, which asks whether the episode contained
a productive aerial at all and cannot be diluted by ground play.

The bar was never derived from anything. AIR_TOUCH_HEIGHT was 5.0 and four
rounds of aerial mechanisms were built on top of it without anyone measuring
where the ball goes. New ball-altitude telemetry over normal match play: the
ball averages ~1.6m, the average episode's peak is ~2.4m, and it clears 5m for
~5% of ticks. Lowered to 3.0, this project's existing airborne threshold, with
_place_air_intercept's band retuned 8-14m -> 6-10m. Simulated against real
physics the pair strictly dominates the old one: 67.8% reach (was 53.2%), 57.3%
above-bar touches (was 41.2%), 5.2m of climb instead of 8.2m. The band could
not be lowered alone -- at a 5m bar, 8-14m was optimal and 5-8m collapses
above-bar touches to 4.3%. This reverses Round 9's explicit "AIR_TOUCH_HEIGHT
stays 5.0"; that objection was about comparability, and a metric that read 0.0
for nine attempts has no history to protect. Pre-2026-08-24 air-touch figures
are not comparable with later ones.

Note AIR_TOUCH_HEIGHT also gates air_touch_bonus_weight's payout, so unlike
Round 9 this DOES change the reward function and the usual "don't resume a
policy shaped by a different reward balance" rule is engaged rather than exempt.
Resuming retry2 anyway is justified on narrower grounds: the changed term has
never once fired (productive_air_touch_fraction exactly 0.0 across nine
attempts, air_touch_fraction at ~0.0003 noise), so no learned value estimate is
attached to it, while the ground handling and scoring retry2 does know are
untouched. The flip side is that at a 3m bar a fully-aligned aerial touch now
pays 0.7 + 0.5 = 1.2 against a ground touch's 0.7, which is the intended
incentive but is a live reward change -- if attempts show touch farming near 3m
rather than genuine intercepts, cut air_touch_bonus_weight rather than raising
the threshold back.

The policy could not climb, and the entropy controller could not see it. Its
target is a sum over heads, which read 21% of h_max -- on target -- while
thrust_y alone sat at 14% of its own ceiling. The measured consequence was a
policy commanding ~0.03 mean vertical thrust when hovering needs 0.408
(120/5 = 24 m/s^2 against 9.8 gravity), leaving it in free fall ~84% of every
episode. Added --min-head-entropy-frac so one starved head raises ent_coef
regardless of the aggregate, and --ent-coef-max because a probe pinned the old
0.05 ceiling for its entire duration with the head still starved.

A 200k-step probe from retry2 with all three in place moved air_touch_fraction
from 0/74 rollouts non-zero to 5/98, ent_coef 0.0102 -> 0.0416 and
vertical_thrust_mean 0.031 -> 0.089, with goal_rate, upright_fraction and
forward_motion_fraction all holding. The gate metric was still 0.0 at that
scale, so its 0.02 floor is marked provisional in generation5.py and should be
re-derived from attempt 1's tail rather than trusted.

Stage 5 expands to 90M timesteps and MAX_RETRIES 4, its goal_rate floor drops
0.75 -> 0.72 (every attempt landed 0.7217-0.7369 and was failed by ~2-4% while
winning its paired evaluations 54-25, 63-23 and 47-32), and state resumes from
20260823-1734-gen5-s5-intercepts-retry2 via resume_override.

Verified: generation5.py --dry-run resolves the resume to retry2 with the new
flags, 123 unit tests pass, probe artifacts removed.
2026-08-24 10:49:05 +01:00
Josh Creek 08eb9f5842 docs(training): the stage-5 side imbalance was seed variance, not an asymmetry
The Hard-tier promotion noted a 17% physical side imbalance (physical teams
0-1 = 29-46) and flagged it as worth investigating, possibly in the arena or in
ship_observations.gd's team-1 mirroring. Testing it directly shows that was
wrong.

Ran hard.json against itself — self-play, so any team_0/team_1 split is purely
positional and cannot be a strength difference — over 10 independent seeds at
30 episodes each. Pooled: 113-125 across 300 episodes, 4.0% imbalance, sign
test p = 0.48, team 1 ahead in only 3 of 10 seeds. Per-seed imbalance ranged
0.0% to 43.3%, so swings larger than the original observation happen by chance
at this episode count.

The underlying mistake is worth recording, and is now in TRAINING.md:
evaluate.py --seed defaults to 1, so the two measurements that appeared to
agree were the same paired starting-state sequence rather than independent
samples, and seed 1 happens to favour team 1. Same reason the
physical_side_imbalance_ceiling gate in generation5.py is a single-seed
catastrophe check, not evidence about side balance.
2026-08-24 08:54:26 +01:00
Josh Creek e1f512c94e feat(bots): promote gen5 stage-5 policy to the Hard tier
Hard has been a label-only duplicate of medium.json since medium was promoted
on 2026-08-17. Promote 20260823-1734-gen5-s5-intercepts-retry2 into
hard.json so the tier is a genuinely distinct policy, and so the strongest bot
the curriculum has produced survives the next round's checkpoint pruning —
promoted files are never touched by training scripts.

Stage 5 blocked after three attempts, so like medium.json this comes from a run
recorded as decision: "fail". Both failing floors are covered in TRAINING.md:
goal_rate 0.7369 vs 0.75 is marginal, and productive_air_touch_fraction 0.0001
vs 0.005 is a bar no policy in the lineage has approached, against a metric
quantised at 0.01 per ~100-episode window. On every other axis it is the best
yet: upright_fraction 0.757 against a 0.40 floor that the pre-Round-6 lineage
never pushed past 0.331, and forward_motion_fraction 0.479 against 0.20.

Chosen over attempt 2 (retry1) on a tiebreak, not a margin. retry1 posts a much
wider indirect result against medium.json (63-23-14 vs 47-32-21), but a direct
100-episode head-to-head between the two finished 36-39 with 25 draws, so that
gap does not reflect a real strength difference. Attempt 3 is the later
checkpoint (it resumed from attempt 2) and edges every telemetry metric.

Verified: hard.json is byte-identical to its source export, matches easy/medium
on input_size 83, 3 layers and action space, and beats medium.json 19-7-4 in a
fresh 30-episode paired run. Tiers stay monotonic: hard > medium > easy.

That head-to-head also showed a 17% physical side imbalance (physical teams
0-1 = 29-46), reproduced at 13% in the 30-episode check. Inside the 20% bar
used elsewhere and equal across both models, but noted in TRAINING.md as worth
investigating rather than assuming variance.
2026-08-24 08:46:06 +01:00
Josh Creek 6320b982a8 fix(project): keep comments out of project.godot and guard the settings
Godot's ConfigFile writer does not round-trip comments in project.godot. An
observed rewrite deleted both `;` blocks outright and spliced the three-line
`#` block above run/main_scene.dedicated_server onto the setting's own line,
leaving it commented out — which would send dedicated builds to the
interactive main menu instead of server_boot.tscn, with nothing failing until
someone noticed a server process rendering a menu.

Move the explanations into the code that owns the settings (server_boot.gd for
the dedicated-server override, video_settings.gd for stretch mode and vsync)
so they cannot be destroyed by a rewrite, and leave project.godot holding only
assignments plus Godot's own regenerated header.

Add tests/cases/test_project_settings.gd as the backstop: the feature-override
assertions read project.godot as text and reject a line that has been folded
into a comment, since ProjectSettings resolves `key.<feature>` overrides at
load time and never exposes the suffixed key. Verified by reproducing the
exact corruption, which fails the test, and it also covers the Jolt physics
engine, the required autoloads, and that no test-hook autoload is ever shipped
registered.
2026-08-24 08:40:16 +01:00
Josh Creek 46fe696a58 fix(tests): measure cumulative travel, not displacement, in the ENet host check
run_ci_host_check asserted input reached the server by comparing each bot
ship's position against one recorded before the check forced a goal. But a
goal's kickoff teleports every ship back to spawn (_begin_kickoff ->
reset_ships), so that comparison measured only the distance covered since the
last reset — a window whose length depends on when the sample lands relative
to the kickoff rather than on whether input was flowing at all.

It failed on master with peers at 0.51m and 0.23m against a 0.5m threshold:
one passed by a centimetre, the other failed, with both connected, neither
stalled, and every other assertion in the run green. The commit it failed on
touches only training JSON, and the push two minutes earlier passed on
identical game code.

Accumulate per-tick path length in _await_recording_score instead, discarding
any single-frame step over 2.0m as a teleport — Ship.max_speed (35 m/s) is
hard-clamped each tick in _integrate_forces, so 60Hz caps legitimate travel at
~0.58m. Same 0.5m threshold now reads 28-75m across runs, and it is strictly
stronger than before: it asserts input kept arriving for the whole wait rather
than that the ship merely ended up somewhere else.
2026-08-24 08:40:06 +01:00
CosmicClash Training Bot dffc2812e1 chore(training): generation 5 progress after 20260823-1734-gen5-s5-intercepts-retry2 2026-08-24 08:07:11 +01:00
CosmicClash Training Bot 614ec9cda9 chore(training): Add 20260823-1734-gen5-s5-intercepts-retry2 checkpoints, logs, and exported policy 2026-08-24 08:04:54 +01:00
CosmicClash Training Bot 17f588b95b chore(training): generation 5 progress after 20260823-0258-gen5-s5-intercepts-retry1 2026-08-23 17:34:58 +01:00
CosmicClash Training Bot 7c949d8679 chore(training): Add 20260823-0258-gen5-s5-intercepts-retry1 checkpoints, logs, and exported policy 2026-08-23 17:32:48 +01:00
CosmicClash Training Bot ba1887fe93 chore(training): generation 5 progress after 20260822-1242-gen5-s5-intercepts 2026-08-23 02:58:22 +01:00
CosmicClash Training Bot b83e030a44 chore(training): Add 20260822-1242-gen5-s5-intercepts checkpoints, logs, and exported policy 2026-08-23 02:55:57 +01:00
CosmicClash Training Bot 5fcdb256b3 chore(training): restore resume_override for stage-5 retry2 after crashed push 2026-08-22 12:42:13 +01:00
CosmicClash Training Bot b69291a7d3 chore(training): Add 20260821-1516-gen5-s5-intercepts checkpoints, logs, and exported policy 2026-08-22 11:50:40 +01:00
Josh Creek f01b1c3cbb Merge pull request #13 from jcreek/multiplayer-phase1-transport
Add multiplayer functionality
2026-08-21 20:50:24 +01:00
Josh Creek b99f63afb7 ci: ignore Blender authoring sources during import 2026-08-21 20:41:28 +01:00
Josh Creek 04865abb39 fix(ci): complete Godot imports before testing 2026-08-21 20:27:50 +01:00
Josh Creek d551ff9cce fix(ci): force Godot asset cache regeneration 2026-08-21 20:21:04 +01:00
Josh Creek 24d6a547d6 fix(ci): isolate imported client test image 2026-08-21 20:16:01 +01:00
Josh Creek 3649620726 fix(godot): regenerate asset import metadata 2026-08-21 20:06:31 +01:00
Josh Creek 23c1c3d231 ci: add ENet integration coverage 2026-08-21 19:57:59 +01:00
Josh Creek 72944a03e9 ci: modernize dedicated server smoke workflow 2026-08-21 19:35:25 +01:00
Josh Creek dab647e514 fix(server): use headless-safe arena simulation 2026-08-21 19:26:47 +01:00
Josh Creek 9e4609d5b3 docs(multiplayer): add concise next-work checklist 2026-08-21 18:56:02 +01:00
Josh Creek 6bafdc7794 feat(multiplayer): add Steam transport foundation 2026-08-21 18:52:07 +01:00
Josh Creek f2b72394de feat(server): complete phase 6 local verification 2026-08-21 18:38:30 +01:00
Josh Creek ec896b27ac feat(server): task 6.4 — structured logging the match and transport layers can reach
server_boot.gd's private _log could only ever see what the boot scene
itself observed: connects, disconnects, roster changes, tick overruns.
The events an operator is actually asked about - who scored, who got
kicked and why, which peer is flooding - happen inside networked_match.gd
and match_sim.gd, neither of which could reach a logger on a scene node
that gets freed at the first change_scene_to_file. scripts/server_log.gd
holds it as static state on a class_name: reachable from all three, no
autoload, no ordering dependency.

New events: goal, match_ended, kickoff, peer_kicked (previously only a
push_warning, carrying neither peer nor reason into the stream a
container captures), rate_limited, server_stalled. rate_limited fires
ONCE per peer per window rather than per packet - a flood is thousands of
packets a second and the log line must not become the amplifier the
replay recorder was capped to avoid being.

Off unless a server configures it, so a client, an editor session or a
unit-test run does not start printing server telemetry just because these
scripts loaded.

Rotation is deliberately not implemented: the server logs to stdout and
stops, because every way this is run already rotates better - docker's
json-file driver, journald, or logrotate on a redirect. A server that
also wrote and rotated its own file would fight all of them in a
container, where stdout is the interface. SERVER.md (6.6) documents the
three configurations.

Five tests on the one piece with real logic - the one-line contract.
Including log injection: a player name is attacker-controlled, and
without escaping, the name "x\n[0.000] INFO peer_kicked reason=nothing"
writes a fake event into the operator's log. Newlines are escaped rather
than dropped so the attempt stays visible.

End-to-end verification of the new events comes with 6.5, which is what
first makes a server run a match at all.
2026-08-21 17:13:11 +01:00
Josh Creek 06881f05ca feat(server): task 6.1/6.3 — dedicated server export preset and a real CLI surface
6.1: "Linux Dedicated Server" preset (dedicated_server=true,
custom_features="dedicated_server") mirroring the existing training
preset, plus run/main_scene.dedicated_server so the server binary reaches
its own entry point with no flag. Builds: an 85MB Linux x86_64 binary,
gitignored like the training one.

6.3: scripts/server_config.gd declares every server flag once - name,
type, default, section, help - and one parser turns that into parsing,
type checking, range validation, config-file backing and --help. The
flags had grown to ~30 across server_boot.gd and networked_match.gd, each
parsed inline with begins_with, none documented, and an unrecognised flag
was SILENTLY IGNORED: --max-clientss=8 ran a server on the default cap
and said nothing. Unknown flags, missing values, wrong types, duplicates
and out-of-range values are now hard errors, reported all at once.

Precedence is command line > config file > default. server_boot.gd parses
strictly because it owns the whole command line; networked_match.gd reads
the same declaration leniently because it is one consumer of an argv the
smoke harnesses also fill with --role= and --drive-seconds=. Nothing is
lost - every server flag is declared, so the strict pass already caught
any typo before the match scene re-reads its own.

13 unit tests covering the precedence order, the typo rejection that
motivated this, --no-<bool> not double-listing in --help, and --help
documenting every flag asserted against the declaration rather than a
hand-kept list. Verified end to end: --help prints, a typo'd flag refuses
to start, and the plain/replay-log/late-joiner smoke scenarios still pass.
2026-08-21 17:03:08 +01:00
Josh Creek 624d1c6b78 docs(multiplayer): add a single index of outstanding work, and record the identity defect
The document had no one place that answered "what is left". Outstanding
items were spread across two phase-gate lines, two phase tables, §11, and
prose buried in the phase notes - and the name-keyed slot-reservation
hijack, which an adversarial review demonstrated with a real three-process
run, was not written down anywhere at all. It existed only in a
conversation.

New §0 indexes everything not done, in four groups: verification a
machine cannot do (the Phase 4 playtest, the Phase 5 3v3 gate), known
defects left unfixed with their severity, the one open architectural
question, and the two unstarted phases. Each row points at the detailed
write-up rather than duplicating it, and the phase gates now point back.

§11 gains the identity defect in full: reservations match on
slot.player_name and nothing else, with no uniqueness constraint on names
anywhere, so a peer joining during the 30s window with a departed
player's name is handed their slot, ship and team. A bespoke token would
be half of task 7.4 thrown away, so it stays deferred - with the
consequence stated plainly rather than implied, and listed as a
precondition of Phase 6's internet-facing gate.

Also refreshes the stale status paragraph and task 5.10 for the replay
log's reject recording, write-failure handling, close(), and dump tool.
2026-08-21 16:51:52 +01:00
Josh Creek ff725e1ffa feat(multiplayer): §6.3 late joiners take a vacated slot at the next kickoff
"Spectate now, take the slot at the next kickoff" was a print statement.
The server logged it and never acted; on the client, _is_spectator was
assigned once in _on_match_config_received and never revisited - and that
handler returns early whenever _slots is non-empty, so no rebroadcast
could promote an in-match spectator. The reconnect path only worked
because a returning player is a fresh process.

Server: late joiners are queued in arrival order and the queue is drained
from _begin_kickoff, before the reset transforms are read, so a promoted
player's ship is placed by that same kickoff and the controller swap
lands on an already-frozen body. A slot is available only once its player
has gone AND their 30s reservation has lapsed - §6.4 outranks §6.3, since
taking a reserved slot would quietly break the reconnect promise.
_abort_if_abandoned now counts a waiting spectator as somebody present,
or the one person queued for the slot that just opened is dumped to the
lobby at the moment they were about to get it.

Client: new broadcast slot_assigned (reliable, channel 0). Broadcast
because every client holds its own slot list and one naming the wrong
peer keeps flying somebody else's ship as a remote body; reliable because
no per-snapshot field would re-converge a client that missed it. The
promoted client undoes what made the body remote - fresh interpolator,
physics interpolation back on, offsets cleared - and deliberately does
not unfreeze, clearing _local_prediction_ready so the next snapshot
teleports it to a real authoritative pose first. The controller-attach
block moved to _take_local_ownership rather than being copied.

New --role=host-latejoin/--role=client-latejoin and
--slot-reservation-seconds=. Verified 4/4 both sides: queued, NOT
promoted merely because the reservation lapsed, takes the slot at the
kickoff, same ship instance, and both peers independently measure ~45.7m
under its input. Control with a 90s reservation: kickoff fires, nothing
is promoted, the slot still reads the departed player's name.
2026-08-21 16:47:35 +01:00
Josh Creek 5714829c13 test(multiplayer): grade §6.4's reconnect from the returning player's side
The disconnect scenario only ever asserted the server's bookkeeping, and
the client's half was failing every run. run_disconnect_host_check ticked
60 physics frames past the reclaim and then shut the server down, so the
reconnecting client - whose wiring check waits a 2.0s settle before it
looks at anything - had its peer torn out from under it and reported
"current_scene is not NetworkedMatch after 2.0s". The host printed PASS
throughout, and the host was the side anyone read.

The hold is now a real window (8s), and the host also asserts that the
reconnected player's input reaches the server and moves the ship the
server owns - every other assertion there is slot bookkeeping that would
hold identically for a client whose input pipeline came back dead. Both
position and connection state are sampled while the peer is still
connected: the client leaves on its own schedule, and an end-of-hold
sample reported still_connected=false for a good run.

New --role=client-reconnect asserts the returning player is not a
spectator, owns a slot with its own peer_id, has a real ship, rejoined a
live match with the clock already known (§6.2 step 2's bootstrap), and
can still drive. That set is chosen because a stale _last_match_config
once made a reconnecting player a spectator, and that bug was visible in
this scenario's own logs while it reported PASS.

Verified 3/3 both sides. Control: rejoining while the slot is still
occupied fails on is_player=false - and since the first control run
reported it as the generic "lost its ship mid-drive", the spectator case
is now diagnosed before the drive rather than after.
2026-08-21 16:25:25 +01:00
Josh Creek 866efa0d9b fix(multiplayer): server no longer rate-limits a backlog it caused itself
Closes task 5.10's three recording gaps, and the gap-closing found a real
input-loss bug.

Replay log: a failed write now ends the log permanently instead of
desyncing every later record's framing; close() is called from _exit_tree
with a summary, since the RefCounted destructor closes it implicitly but
never says whether the log is complete; rejected packets are recorded
with their reason in the kind byte (framing unchanged, FORMAT_VERSION 2
so "no rejects" differs from "this build never recorded them"). Recording
is capped at 8 per peer per window - uncapped, the diagnostic is a remote
disk-fill amplifier, since the attacker picks the packet rate. Uncapped
totals live on MatchSim and survive the peer's disconnect.

The bug: a 2s host stall has the client sending at 60Hz throughout, and
ENet delivers that whole backlog in the first window after resume - 70 of
an honest client's packets rejected as "rate limit exceeded". Redundancy
does not cover it, because the dropped packets are contiguous: 0 of 70
rescued, and 82 of 923 sequences (8.88%, ~1.4s of input) never reached
the server, against 0.00% with no stall. Every prediction gate passed.

Fixed by granting each already-tracked peer a capped, two-window packet
grace when the server detects its own wall-clock stall. Rate-limit
rejects 70 -> 0, sequences missing 8.88% -> 0.00%, seq-guard rejects
9 -> 0. Controls on the unfixed build lost 4.34/7.52/7.86%. All three
abuse roles still disconnect and no flood induced a stall, so the grace
cannot be farmed.

Also corrects an earlier wrong conclusion: the reviewer's free-flight
p95 0.688 is real and reproduces on two processes with 0.0% snapshot
loss. The plain --role=client drive fails the 0.5 free-flight bound in
3 of 8 runs because that drive is mostly a contact test - the harness
comment already said so - leaving a cohort as small as 12 samples.
Near-surface error is genuinely several times open-air error, so the
calibrated bound now belongs to --exercise-free-flight alone and the
plain role asserts the always-well-sampled all-cohort percentiles at
1.2/2.0, printing the free-flight numbers as reported-not-asserted.
6/6 plain runs pass where 3/7 failed; tightening to 0.3 still fails.

tools/replay_dump.gd reads a log back: counts by kind, plus how much of
the input sequence stream reached the server once redundancy is counted.
2026-08-21 16:10:43 +01:00
Josh Creek e51dc765a2 test(multiplayer): report transport health on prediction-quality failures
A percentile alone cannot tell "the predictor regressed" from "the client
never received the data". The client gate now prints snapshot_loss /
snapshot_age / rtt on every run, and on a quality failure with >20% loss
says explicitly that the run was transport-starved. It deliberately does
not convert the failure into a pass: a client that cannot receive
snapshots is still a failed run, just a differently-diagnosed one.

Both directions of the new branch verified non-vacuously (forced true so
it fires and formats; restored so it stays quiet on a healthy run while
the INFO line still prints).

Records the investigation behind it in multiplayer-todo.md: the reviewer's
3-process p95 0.688 did not reproduce. An idle third process costs nothing
(p99 0.094), a spectator costs a small but real amount (p99 0.094-0.146),
and snapshot loss held at 0.0% even under 2x CPU oversubscription - all an
order of magnitude inside the 0.5/2.0 gates. Also notes that a previously
working class_name can silently drop out of the .godot class cache, which
surfaces as a bogus parse error with nothing in git status to explain it.
2026-08-21 15:24:58 +01:00
Josh Creek 818f8e89cd fix(training): make the stage-5 air-intercept drill physically solvable
productive_air_touch_fraction sat at exactly 0.0 across nine Stage-5
attempts and 540M timesteps. Two rounds of reward shaping were aimed at
it (air_approach_weight, then air_touch_bonus_weight); both worked --
airborne_fraction 0.223->0.258, mean_altitude 2.59->3.25,
vertical_thrust_mean 0.004->0.063 -- and the ship now visibly plays the
ball in the air. The metric could not see it because it counts only
touches with the ball above AIR_TOUCH_HEIGHT (5m), and
_place_air_intercept never produced a reachable one.

Simulating the spawn distribution against the ship's flight envelope
(vertical_thrust 120 / mass 5 = 24 m/s^2 less gravity, drag capping
climb near 12 m/s): a ball spawned 6-12m up at 6-11 m/s is above 5m for
a median of 0.80s, while the ship spawned 7-13m behind, 3-10m below, and
at a dead stop. An ideal interceptor -- point mass, instant attitude, no
righting torque, zero reaction delay -- makes that touch in 0.00% of
episodes and reaches the ball at all in 0.5%.

Retune the drill instead of the reward: ball higher (8-14m) and slower
(4-8 m/s), ship closer (4-9m behind), narrower lateral spread, and a
6-14 m/s planar run-up rather than a standing start -- the dead stop was
the largest single factor. Ideal interceptor now reaches the ball in
~98% of episodes and above 5m in ~37%, so the 0.005 floor has headroom.
AIR_TOUCH_HEIGHT stays 5.0 so the metric remains comparable with earlier
generations.

Resume from retry2 rather than restarting from Stage 4: that rule guards
against a changed reward function invalidating the value function, and
the reward function is untouched here -- only the state distribution
moved, so the policy that already learned to fly is what should be
pointed at a reachable target. Adds a one-shot resume_override to
generation5_state.json, consumed on first use.
2026-08-21 15:14:36 +01:00
CosmicClash Training Bot 23e3dd18f9 chore(training): generation 5 progress after 20260821-0056-gen5-s5-intercepts-retry2 2026-08-21 13:49:28 +01:00
CosmicClash Training Bot 0699b14d4e chore(training): Add 20260821-0056-gen5-s5-intercepts-retry2 checkpoints, logs, and exported policy 2026-08-21 13:48:12 +01:00
Josh Creek 7a1668c902 fix(multiplayer): second adversarial review - Esc, stranded clients, clock
A second adversarial review (this one able to RUN things, unlike the
first) reproduced five defects. Fixing the critical and high ones.

CRITICAL - Esc no longer left a networked match, and a client whose
server vanished was stranded forever. Two independent bugs composing:
_unhandled_input (added for spectator target cycling) overrode
GameMode._unhandled_input and returned early for every non-spectator
without ever calling super(), silently killing ui_cancel -> main menu;
and NetworkedMatch never connected NetworkManager.disconnected_from_
server the way lobby.gd does. Measured: a client whose host exited
emitted 7,235 engine errors in ~18s and only left because a test timer
fired. Now 1 benign teardown error, and it returns to the main menu.

HIGH - the match clock lost up to 3 seconds of regulation per goal.
_on_goal_registered extended end_tick by the celebration only
(resume_tick - goal_tick) and never by the 180-tick kickoff countdown
that follows it, while _update_clock derived remaining time from the
current tick regardless of _clock_running - so regulation drained during
every stoppage. Measured 660 PLAYING ticks for a 14s match against 840
expected: exactly one WARMUP lost. The HUD also opened at 0:17 for a 14s
match because the initial arm folded WARMUP into end_tick.

Replaced the per-goal arithmetic with bank-and-rebase: entering any
non-live state banks the remaining ticks, leaving it rebases end_tick
off the banked value. That covers celebration and countdown together and
cannot drift, since nothing has to predict how long a stoppage will be.
clock_state and match_bootstrap now carry remaining_ticks, which is
authoritative whenever the clock is stopped. Verified with the
reviewer's own metric: 840 PLAYING ticks for a 14s match, exactly.

MEDIUM - clients never froze at FULL_TIME/RESULTS. The freeze handling
sat inside `if multiplayer.is_server()`, so a local player flew around
for the whole 8s results screen while every other peer saw their ship
parked.

Not fixed, and now demonstrated rather than merely suspected:

- The 30s slot reservation is keyed on display NAME, so a stranger can
  take a departed player's ship and the real player is then locked out
  (reproduced). Worse than first thought: MatchNet.local_player_name
  defaults to "Player" and uniqueness is never enforced, so collisions
  are the common case, not an attack setup. Needs a real identity token;
  §6.2 step 1 reserves auth_ticket for Phase 7.
- §6.3's "late joiner takes the slot at the next kickoff" is
  unimplemented - _is_spectator is assigned once and never revisited -
  while the server logs that it happened.
- Replay log still ignores store_* return values, never records
  malformed/rejected inputs, and close() has no caller.
- --role=host-disconnect grades the reconnecting client on ~1s of life
  before the host quits, and never asserts the client owns _my_slot.

Regression: 87 unit tests; free-flight LAN; transition gate 0.00%; goal
cycle; spectator; disconnect and reconnect; full match to RESULTS.
2026-08-21 12:17:06 +01:00
Josh Creek b5e9dff33c fix(multiplayer): Phase 5 adversarial review fixes - reconnect, spectators
An adversarial review found five real defects in the Phase 5 lifecycle
work. Two were critical and both were verified against controls.

CRITICAL - a reconnecting client silently became a spectator.
_try_reclaim_slot() swapped slot.peer_id, but MatchSim caches the last
match_config and replays THAT to whoever asks. A reconnecting client in
a fresh process requested config, received the pre-disconnect peer-id
array, could not find itself, left _my_slot null and fell through to the
spectator path - no ship, no input, for the rest of the match. The
evidence was already in my own disconnect-test logs ("no slot for this
peer - spectating", my_slot_ok=false) and I dismissed it: the host-side
check only asserted the SERVER reclaimed the slot, never that the
returning client owned it. Config is now rebroadcast on reclaim.
Verified: my_slot_ok=false -> true.

CRITICAL - spectators received no snapshots at all. §6.3 says a
spectator "receives identical snapshots (the snapshot is already a
broadcast - zero extra server work)". That was only ever true of the
body SEGMENT: _broadcast_snapshot unicasts one packet per SLOT, so a
peer without a slot got nothing - no poses, no reset_gen, no
match_state byte. Spectating was entirely non-functional. The segment is
still shared, so this is one extra send per spectator. Verified against
a control: 0 snapshots and state stuck at LOADING before, 361 snapshots
and PLAYING after.

HIGH - cycling the spectator camera to the ball was a type error.
ShipCameraRig.target is declared `var target: Ship` and the rig reaches
into ship-only API, so it would have fired the moment anyone cycled past
the last ship. Cycling is ships-only; the rig already has its own
ball-cam mode for watching the ball.

MEDIUM - clients never received match_ended or overtime_started. Both
emitted only inside server-side logic, so a client froze and returned to
the lobby without a result and its timer never switched to overtime.
Derived from replicated state instead of adding two more RPCs: the
client already has the authoritative score, and the transition is the
event.

MEDIUM - the goal cinematic ignored its authoritative window. goal_tick
and resume_tick arrived and were unused; the client started a fresh
fixed-length timer on RPC receipt, so a reliable retransmit could run
the celebration past the server's window and into the next kickoff.
_goal_pause_seconds() now returns the time actually remaining, clamped
so an elapsed window cannot produce a non-positive timer.

Also added: a match_bootstrap RPC carrying state, score, clock and
reset_gen to one peer. match_config alone carries arena and roster only,
so a late joiner or reconnecting player had no score or clock until the
next goal happened to fire. It is sent on join AND on every
request_match_config retry - the join-time send has exactly the same
race match_config already had (the server sends it before the peer has
loaded the match scene and connected its listeners), which the control
run exposed: state was reaching PLAYING via the snapshot byte, not the
bootstrap.

New test: --role=client-spectator asserts a slotless peer receives the
snapshot stream, follows the lifecycle, agrees with the wire byte, and
can cycle targets without ever handing the camera a non-Ship. Verified
non-vacuous. The ball-contact steering now closes all the way to 1.2m
instead of coasting from 3m, which was missing the ball outright in
roughly 1 run in 4.

Not fixed, and still open: the 30s slot reservation is keyed on the
player's display name, so any peer can claim a departed player's ship by
choosing their name. §6.2 step 1 reserves auth_ticket for Phase 7; this
needs a real identity token, not a name.

Regression: 87 unit tests; free-flight LAN; transition gate 0.00%; ball
contact 4/4; goal cycle; full match to RESULTS/LOBBY; disconnect and
reconnect; spectator; two-bot CI.
2026-08-21 11:34:48 +01:00
Josh Creek a5cbc977b5 feat(multiplayer): Phase 5 tasks 5.6-5.10 - disconnects, spectators, replay log
Completes Phase 5's implementation. Every task is verified at 1v1; the
3v3 phase gate itself has not been run and remains outstanding.

5.6/5.7 disconnects: a ship is never despawned. The slot keeps it and
swaps the controller (--fill-bots gives it a bot, the default leaves it
inert per §1.4), sets `stalled` immediately so the nameplate greys out
rather than waiting ~500ms for the abandoned jitter buffer to starve,
and reserves the slot for 30s keyed by player name so a reconnect gets
the same ship back.

5.7 was a real bug, found by the test rather than by review:
SlotInfo.controller was declared RLShipController, but the takeover
swaps in an AIShipController or the base controller - the narrower type
makes that assignment fail its type check, leaving the field pointing at
the controller set_controller() just queue_free()d. It surfaced as
controller_valid=false on the first run. The per-tick action write is
now also gated on `is RLShipController`, since a disconnected slot's bot
drives itself and overwriting it from a starving buffer would pin it to
the departed player's last input.

§6.4's two rules conflict: reserve for 30s, but abort when the last
human leaves. Applied naively the abort wins instantly in a 1v1 and the
reservation can never be redeemed, making reconnect unreachable exactly
when it matters. Abort now waits for no connections AND no outstanding
reservations.

5.8 spectators: a slotless peer spawns no ship and receives the same
snapshot broadcast. HUDController.spectator_mode keeps the clock, score
and goal celebration and hides only the ship instrument cluster - it
previously push_error'd and bailed, leaving a spectator with a dead HUD.
Camera cycles ships in slot order then the ball. --max-spectators caps
it, counted from the live peer list so a dropped spectator cannot leak a
unit of the cap.

5.9 escape respawn: new GameMode._on_bodies_respawned() virtual;
NetworkedMatch bumps reset_gen through Phase 2's deferred path so the
bump and the respawned pose land in the same broadcast. Single-player
modes are unaffected - the base is a no-op.

5.10 replay log: scripts/replay_log.gd, --replay-log=<path>, storing the
wire bytes verbatim in both directions rather than re-serialising - a
re-encode would launder away precisely the malformed payload being
chased. A live 6s match recorded 1115 records (557 inputs / 558
snapshots) and a stored snapshot decodes back to server_tick=100
match_state=WARMUP bodies=2.

Note for future work: --check-only --script is the only thing that
catches a parse error in networked_match.gd, because the unit runner
never loads it. Two separate breakages passed the full unit suite while
breaking every two-process run. A new class_name also needs --import
before it resolves.

Test surface: --role=host-disconnect (three-process 5.6/5.7 scenario),
--match-length=<s>, --replay-log, --fill-bots/--no-fill-bots,
--max-spectators. The ball-contact scenario now steers at the ball with
closed-loop real input instead of a hand-tuned fixed heading, which 5.3
broke by adding KICKOFF_YAW_JITTER; thrusting while turning took it from
2/3 to 5/5.

Regression: 87 unit tests; free-flight LAN p99 0.094m with 0 hard snaps;
transition gate 0.00%; ball contact 5/5; lifecycle goal cycle and full
match to RESULTS/LOBBY; disconnect+reconnect; two-bot CI.
2026-08-21 10:25:15 +01:00
Josh Creek 3d6906b981 feat(multiplayer): Phase 5 tasks 5.2-5.5 - clock, kickoff, goals, full time
Implements the rest of the §6.2 lifecycle on top of 5.1's state machine.

5.3 kickoff: the server resets every body and broadcasts the RESULTING
transforms, never a seed - §1's locked decision, because shared-seed
determinism needs both sides to consume the RNG stream in identical
order forever and the first randf() added to the reset path desyncs
silently. Countdown is derived from server_tick on both peers, and a
kickoff that lands after its own resume tick applies immediately and
skips the countdown rather than scheduling into the past.

5.4 goals: goal_scored(scoring_team, score, goal_tick, resume_tick).
Score is authoritative at sensor time, before any presentation. The
reset moved OUT of the sensor path and into the kickoff at resume_tick,
which is what stops the server resetting while clients are still
mid-celebration. Engine.time_scale is never touched.

5.2 clock: tick-derived, no Timer and no _process polling. The goal
pause shifts the absolute end_tick by (resume_tick - goal_tick) rather
than pausing anything, so no float drift accumulates across goals.

5.5 full time: clock expiry -> FULL_TIME -> sudden death on a draw or
RESULTS, golden goal in overtime, then LOBBY on both peers - clients
return to the lobby, not the main menu. get_tree().paused is never used.

Four bugs found and fixed while building this, each by a failing run
rather than by inspection:

- Tick order was load-bearing: _update_kickoff_countdown() clears the
  same _kickoff_resume_tick that _update_match_state() reads to leave
  WARMUP, so running the countdown first wiped the transition condition
  and the match sat frozen in WARMUP forever.
- _apply_match_state resets _state_deadline_tick on every transition, so
  a GOAL_PAUSE deadline assigned before _set_match_state was wiped and
  the match never resumed. Deadlines are now owned by _apply_match_state.
- Freezing "all bodies" is wrong on a client. Remote ships and the ball
  are permanently FREEZE_MODE_KINEMATIC and transform-driven; freezing
  them all unfroze the remote ones on the way back out, so they fell
  under gravity while the interpolator fought them - 210 hard snaps and
  an infinite p99. A client now freezes only the one body it simulates.
- A frozen body never runs _integrate_forces, so the queued kickoff
  teleport was stranded by an immediate set_deferred("freeze", true).
  Freeze now happens on a strictly later tick, the same pattern Phase 2
  used for _pending_reset_gen_bump_tick.

Prediction and reconciliation are suspended while the match is not live:
during a countdown or goal pause the local ship is frozen on both peers,
and running delta transport over those frozen states produced a p95
position error of 2.4e10 m. Input keeps flowing so the server's jitter
buffer does not starve into `stalled`.

Also fixed: a kickoff can arrive before match_config, and body order is
slot order - applying it early placed the BALL at positions[0], on top
of the first ship, which the ball-cam reported as "target vector can't
be zero" 95 times. It is now held until the roster exists.

Test changes: the ball-contact scenario steered by a hand-tuned fixed
heading, which 5.3 broke because kickoff applies KICKOFF_YAW_JITTER - it
flew past the ball in 3/3 runs. It now closes the loop on the actual
bearing using real input actions. Assertions that read a frozen ship
(freeze, thrust) are gated on the match being live, and the hooks now
survive the scene teardown at RESULTS instead of hanging on freed
objects for the full timeout.

Regression: 81 unit tests; free-flight LAN p99 0.143m and 80±20ms, both
0 hard snaps; transition gate 0.00%; ball contact 3/3; two-bot CI.
2026-08-21 10:01:39 +01:00
Josh Creek 9f28c02488 feat(multiplayer): Phase 5 task 5.1 - match lifecycle state machine
Adds the §6.1 state machine, its broadcast, and the client side that
follows it. Physics, freezing and input are deliberately NOT gated on
state yet - 5.3 and 5.4 own freeze/unfreeze at kickoff and goal, and
doing it here would change the conditions every Phase 4 prediction gate
was measured under.

scripts/match_state.gd holds the enum and transition table as pure data
with no scene or RPC dependency, so the table is checked exhaustively
rather than by example: every state reachable, every state has an exit,
no self-transitions, abort-to-LOBBY from anywhere per §6.4, illegal
shortcuts rejected, unknown values refused rather than coerced. The enum
values are the wire format - match_state has been a u8 in the snapshot
header since §2.4 - so a test pins them; only append, never renumber.

The server validates every transition and push_errors an illegal one
rather than following it. Clients deliberately do NOT enforce the table:
authoritative state must be accepted, and a late joiner legitimately
jumps straight to PLAYING.

Two channels carry the state. state_change (reliable, channel 0) is
prompt and carries an absolute at_tick, never a duration. The snapshot's
match_state byte is the catch-up path for a client not yet sent a
transition - a late joiner, or the window between scene load and the
first RPC.

The byte needs a tick guard, and this was found the hard way. Snapshots
are unreliable_ordered on channel 2 and ordering holds only within a
channel, so a state_change for tick N routinely arrives before an
in-flight snapshot from tick N-2. Without the guard the client applies
the new state then gets dragged back by the older byte, oscillating on
every transition - observed directly as LOADING -> WARMUP -> LOBBY ->
PLAYING -> LOBBY while running a deliberately-broken-byte control. Only
a byte at least as new as match_state_since_tick is accepted.

WARMUP_TICKS/GOAL_PAUSE_TICKS are honest placeholders so 5.1 drives real
transitions to verify against; 5.3 and 5.4 replace them. The server also
leaves LOADING immediately rather than waiting for scene_ready, which
does not exist yet.

New smoke flag --exercise-match-state, passed to both roles: the host
forces a goal to drive a GOAL_PAUSE cycle, the client records the
sequence and asserts every consecutive pair is legal, that ticks are
monotonic, and that the wire byte agrees with its own state. Observed
LOADING -> WARMUP -> PLAYING -> GOAL_PAUSE -> WARMUP with tick deltas
matching the configured durations exactly.

Verified against a control: hardcoding the snapshot byte back to 0 fails
both the byte assertion and the transition-legality assertion. The byte
is asserted separately from the RPC precisely because everything else in
the check is RPC-driven and would pass with a dead byte - the same gap
that hid the Phase 4 label bug (gotcha 47).

Regression: 81 unit tests; 60s free-flight LAN (p99 0.148m, 0 hard
snaps, marker 0/3364); transition gate 0.00%; ball contact; two-bot CI.
2026-08-21 09:31:22 +01:00
Josh Creek 75f485667b feat(multiplayer): Phase 4 prediction correctness + two input-death fixes
Closes Phase 4's outstanding action-sequence-correctness invariant, then
fixes two server-side bugs an adversarial review of that work uncovered.
Server simulation, bot observations, collision resources and tick rate are
unchanged: the server_physics_parity trace is byte-for-byte identical to
HEAD across 360 ticks including both ships' full observation vectors.

4.11 - prediction history filed under the ISSUING sequence

_send_local_input filed each post-step predicted state under the timeline's
estimate of the sequence the server would consume this tick, trailing
issuance by input_lead. The body had integrated the intent issued under
_input_seq, so predicted[S] held "state after the intent from now" while
the server's authority for S is "state after action(S)". They agree only
while the stick is still. Filing under _input_seq costs nothing: which
action the ship uses is decided in LocalNetShipController.get_action() and
is untouched.

Every prior Phase 4 gate held its input steady, and a steady input cannot
falsify a sequence label - the 60s runs honestly reported marker=0/3784.
New --exercise-input-transitions role toggles thrust every 6 ticks; it is
the only gate that can catch a label regression. Verified non-vacuous: the
old label fails it at 50%.

4.12 - issued-but-unsimulated sequences, and the release path

An attack (delta > 1) issues and sends several sequences for one local
physics step. Those gap sequences had no recorded prediction, so a server
ack of one reported missing_not_recorded - indistinguishable from ring
loss, costing a teleport and resync suppression several times a minute.
They are now recorded stateless via record_unsimulated() and answered with
a new "skip" decision mode. Free-flight hard snaps: 25/8/4 -> 0/0/0.

A release (delta == 0) re-recorded at the unchanged _input_seq, filing the
current intent under a sequence that went out carrying a different action;
LocalInputTimeline deliberately refuses to mutate an issued sequence, so
the ring contradicted the wire. Recording is now skipped on release ticks.

4.13 - two Phase 3 bugs silently killing player input

(a) InputJitterBuffer.consume() advanced last_applied_seq on every tick
including a starve. Since ingest() discards seq <= last_applied_seq, one
starve on a sequence the client had not sent yet stranded the stream one
ahead of arrivals permanently - both sides advancing in lockstep, every
honest packet discarded on arrival. The client's own input_lead release is
enough to trigger it, so input died for ~30 ticks roughly every 6.5s on a
clean LAN. Now only gives up on a sequence once strictly newer data proves
it lost. Silent-client stall and ring-overflow resync are unchanged.

(b) The seq-range guard bounded incoming seq against highest_ingested_seq,
which only advances inside ingest(), which that guard gates. After a ~2s
host hitch every packet was rejected forever with no diagnostic (600+
consecutive rejections reproduced via SIGSTOP). Third iteration of this
guard; each previous version bounded against a value only the accepted
path could advance. Adds an escape after 10 consecutive rejections, which
grants an attacker nothing the rate limiter does not already bound.

(c) The transitions gate reported PASS at 3.76% while input was completely
dead, because suppression stops _record_metrics - a worse outage yields
fewer samples and a LOWER rate. Now scales the required sample count with
run length and asserts the wire's server_stalled bit. Reverting both fixes
makes it fail at samples 292/600, server_stalled=true, input_lead=12.

Fixing (a) also explained a residual the review had already traced: 151 of
151 action-marker mismatches were the server repeating a stale action on a
starve, not a prediction defect. Marker is now 0.00% in all three
conditions (was 1.7-2.5%), and free-flight p99 improved to
0.141/0.168/0.154m from 0.170/0.176/0.184m.

Two pre-existing test defects fixed alongside: the ball gate asserted
RTT-masking on a link with no RTT (flaked 2 in 5; now asserted only at
rtt >= 20ms, 5/5 under latency), and the two-bot CI compared scores across
a 3-5s window (now polls the scores the server actually held; note
score_changed is emitted only on the client path).

QA: 72 unit tests; 60s free-flight at LAN/80+-20ms/5% loss; transition
gate in all three; 2.0s and 3.5s host-freeze recovery; ball contact x5;
two-bot CI x3; all three abuse roles; net/match_net/clock/lobby smokes.

Phase 4 sign-off still pending a human playtest at ~100ms RTT - the
milestone asks how it feels, which no gate here answers.
2026-08-21 09:17:19 +01:00
CosmicClash Training Bot 9708bfafa3 chore(training): generation 5 progress after 20260820-1157-gen5-s5-intercepts-retry1 2026-08-21 00:56:33 +01:00
CosmicClash Training Bot 12bc4d7e8a chore(training): Add 20260820-1157-gen5-s5-intercepts-retry1 checkpoints, logs, and exported policy 2026-08-21 00:55:09 +01:00
Josh Creek 3d3024ae8a feat(multiplayer): Phase 4 tasks 4.1/4.2 - local prediction history ring
Adds LocalPredictionHistory, a client-owned seq-tagged ring recording
predicted ship state per input sequence, plus wiring in
NetworkedMatch to record predictions on send and compare them against
authoritative snapshots on arrival. Ships stay frozen/interpolated
until 4.3 lands actual correction logic; this round only builds the
comparison machinery and its data.

Includes fixes from two review rounds: resync_required now
self-clears once acknowledgements catch back up (mirrors
InputJitterBuffer's stalled flag), NetBodyState gained a copy()
method to stop diagnostic accessors aliasing ring-owned state, and
corrected comments that had described the local ship as being
force-simulated pre-4.3 when it is still driven by interpolated
transform writes.
2026-08-20 19:29:13 +01:00
Josh Creek cf73074e27 fix(multiplayer): resolve composition regression from second adversarial review
A second adversarial review of the previous fix commit found two of its
nine fixes silently defeated each other: the seq-range guard (fix for a
MEDIUM epoch-mismatch finding) capped the exact variable the ring-overflow
resync (fix for the original CRITICAL finding) depends on, making the
resync unreachable in production and recreating permanent input death at
a lower failure threshold, reachable via ordinary server tick loss alone.

- CRITICAL: rebind the seq-range guard to InputJitterBuffer's own
  highest_ingested_seq (now public) instead of the consumer-side
  last_applied_seq, so it tracks the client's send epoch rather than a
  value that can lag arbitrarily far behind during a stall.
- HIGH: InputLeadController's release logic still ANDed the old
  `lead > LEAD_MIN` gate onto the new depth-driven condition, so a
  backlog the controller never caused still couldn't drain. Split into
  two independent decisions: the seq-duplicate action follows real
  depth alone; lead's own bookkeeping separately never drops below its
  floor.
- MEDIUM: widen the CI driver's movement/stalled sampling margin
  (run_seconds - 2.0, was - 0.5) and assert the peer is still in
  multiplayer.get_peers() at sample time, since the old margin let the
  check pass on residual starvation grace after a bot had already
  disconnected.
- LOW: measure horizontal-only displacement in the human smoke test's
  movement check — the old 3D-distance bar was beatable by pure
  gravity settling with fully dead input.
- LOW: fix a real "clean stderr" violation (match_net.gd broadcasting
  a departure notice to a peer whose ENet channels are already torn
  down, including a second peer disconnecting in the same poll batch)
  by deferring the notification to the next idle frame.
- Wire the server's per-slot stalled bit into the client debug overlay
  for real — a prior commit message claimed this already reached the
  overlay when only the CI gate actually read it.

Re-verified end-to-end against the real production RPC path (not just
unit tests in isolation, which is how the composition bug got past the
first round): a 2-bot CI match with a 1.5s host SIGSTOP freeze injected
mid-run, well past the 0.6s threshold the review reproduced the bug at,
now recovers cleanly on repeated runs with zero stderr noise.
2026-08-20 18:26:12 +01:00
Josh Creek 2325313ad2 fix(multiplayer): adversarial review fixes for Phase 3
An Opus subagent's adversarial review of Phase 3 found a critical, silent,
permanent bug plus eight smaller real issues, all empirically verified
with real two- and three-process runs:

CRITICAL: InputJitterBuffer's 32-entry ring permanently bricked a
player's input once the un-consumed backlog exceeded the ring's
capacity - a fresh arrival would land in the exact slot consume() was
still waiting on, and since both counters only ever advance, the gap
never closed. Reproduced with a real SIGSTOP/SIGCONT host freeze:
client movement dropped from ~26m to 0.00m at ~0.7s, worse under real
loss (a lossy link lowered the fatal threshold to ~400ms), and
reachable via ordinary clock drift with no external trigger at all.
Fixed by tracking the highest seq ever ingested and having consume()
jump directly to what the ring can still provide once the gap exceeds
capacity, instead of starving through an unrecoverable span. Re-verified
with a 3s freeze (well past the original threshold): full recovery.

HIGH: InputLeadController's release logic was gated on its own past
attacks (lead > LEAD_MIN) rather than the real server-reported depth, so
a backlog it didn't itself cause was never drained. Fixed to gate on
actual depth vs target.

MEDIUM-HIGH: the rate limiter's "N consecutive over-budget seconds"
streak hard-reset to 0 on any clean window, letting a duty-cycled flood
(burst, one clean window, repeat) sustain ~33x budget indefinitely with
zero warnings. Replaced with a leaky-bucket accumulator immune to the
same evasion by construction.

MEDIUM: the seq > server_tick + 20 guard compared two unrelated clock
epochs (server process uptime vs. client's own from-zero seq numbering),
so it never actually protected anything on a long-running server and
could silently drop an honest client's input forever. Bound against the
buffer's own last_applied_seq instead.

MEDIUM: InputJitterBuffer.stalled was computed but never reached the
wire - the one signal that would have made the ring-overflow bug visible
anywhere. Now wired through _ship_to_net_body_state.

MEDIUM: task 3.6's CI driver's assertions didn't depend on client input
reaching the server at all, so it kept passing with the ring-overflow
bug actively triggered. Added real ship-movement and non-stalled checks,
sampled while bots are still connected (an initial attempt sampled after
their own legitimate disconnect, which starves identically to the bug).

LOW-MEDIUM: a lead change silently mislabelled _input_history's older
entries, since the wire format has no per-entry seq field. Fixed by
handling each delta case (ordinary/release/attack) on its own terms.

LOW: bandwidth and snapshot-loss overlay metrics froze at their last
value during a total outage instead of decaying - exactly when they
matter most. Both now report honest post-outage values.

LOW: a guard comment on NetworkManager._ping misdescribed the actual
disconnect_peer() arguments in use. Corrected.

New permanent regression tests: test_ring_overflow_resyncs_to_fresh_data
_instead_of_starving_forever, test_release_drains_a_backlog_it_never_
caused_itself, and client-abuse-flood-dutycycle (reproduces the exact
duty-cycle evasion). Full regression suite, including the net-sim-latency
milestone gate, all abuse roles, and the CI driver, re-run clean after
every fix.
2026-08-20 15:28:44 +01:00
Josh Creek 10040f7339 docs(multiplayer): close out Phase 3 in multiplayer-todo.md
Documents all seven Phase 3 tasks (3.1-3.7) with DONE status and
verification evidence, updates the top-level status summary, and records
the phase gate as met - re-verified today under the gate's own exact
condition (--net-sim-latency 80 --net-sim-loss 0.05) on both the human
smoke test and the two-bot CI driver, not just the looser conditions
used during individual task development.

Adds one new gotcha (#38): GDScript lambdas capture enclosing locals by
value, not by reference, which silently broke two separate Phase 3 test
scripts' own disconnect-detection assertions this session (the
production disconnect logic was correct both times; only the test's own
flag-capture pattern was wrong).

Also records a deliberate scope decision for task 3.4: server-side
input_lead enforcement from arrival times was scoped down to
observability rather than built as active enforcement, since the
concrete security requirements (rate limiting, malformed-packet
counting, seq-range rejection, disconnect policy) already close the
load-bearing gaps and the doc's own text calls the remaining edge
"small" - flagged to revisit once Phase 4's prediction work exists to
judge against.
2026-08-20 13:43:49 +01:00
Josh Creek caa9f44ab6 feat(multiplayer): Phase 3 task 3.6 - --test-bot client mode + CI driver
networked_match.gd's client can now swap its input sampler for a real
AIShipController (--test-bot, optionally --test-bot-model=<path>,
defaulting to bots/promoted/medium.json) instead of PlayerShipController.
Unlike the human sampler, AIShipController needs real scene context
(get_parent() as Ship, plus ball/teammate/opponent discovery via groups),
so it's parented onto the client's own ship via Ship.set_controller()
rather than left floating - and the field's static type widened from
PlayerShipController to the shared ShipController base to allow either.

Known, documented limitation: this client's ships are all
FREEZE_MODE_KINEMATIC and driven purely by transform writes, so nothing
ever writes linear_velocity/angular_velocity onto them - the bot's
observations always see every ship as stationary. It still produces
well-formed, bounded actions from that degraded input (the policy
network's output layer is bounded regardless of input quality), which is
sufficient for this task's actual job: generating realistic sustained
network traffic for CI, not winning matches.

New CI driver (tests/networked_match_ci.gd/.tscn): a headless server plus
two headless --test-bot clients playing a real match. task 3.6's original
acceptance text also named "p95/p99 prediction error" and "snap count" -
both Phase 4 concepts that don't exist until client-side prediction and
its hard-snap threshold are built, so asserting on them now would be
fabricated. What's checked instead: snapshot throughput (500+ received
over an 8s run, comfortably above a 60Hz-scaled floor), and genuine
cross-peer score agreement - forced via a deterministic server-side goal
(bot-vs-bot scoring isn't reliable enough within a short run to gate on),
with each client independently writing its own final score to a peer-id-
keyed file for the host to compare against the other bot's, not just
trusting the server's own view. "Clean stderr" is left as the external
invocation's job, same as every other smoke test in this project.

Verified with real 3-process runs (host + two bots): both clients
independently confirmed identical scores after a forced goal, both saw
500+ snapshots, and all three processes exited 0 with clean stderr on a
representative run (one run separately hit the same known, already-
documented single-benign-error disconnect-timing race task 3.4's own
abuse tests hit - not a new issue). Full regression suite, including the
net-sim-latency milestone gate and the abuse-detection tests, re-run
clean.
2026-08-20 13:40:48 +01:00
Josh Creek 9d8a8080ba feat(multiplayer): Phase 3 task 3.7 - debug net overlay extension
Extends net_debug_overlay.gd (Phase 1's RTT/offset display) with the
rest of task 3.7's list: jitter (new RFC3550-style EWMA in
NetworkManager, computed from raw per-sample RTT before Phase 1's own
min-filtering, since that filter is deliberately jitter-insensitive by
design), input buffer depth and input_lead (both already tracked
client-side for task 3.3), snapshot loss (a new EWMA in networked_match.gd
over each received snapshot's own server_tick gap - snapshots go out at a
steady one-tick cadence, so a gap is direct evidence of a drop or
reorder), snapshot age (computed on demand from the same bias-corrected
tick estimate the interpolator itself uses), and bandwidth (new rolling
per-second byte counters in MatchSim, on the two 60Hz hot-path channels
only). Prediction error is deliberately omitted with a comment explaining
why: there's no client-side prediction to measure until Phase 4.

Verified values are live and plausible, not just present, by calling
get_net_debug_stats() directly in a real two-process test and checking
the numbers make sense: bandwidth matched the wire format's own byte
math almost exactly (measured ~2400 B/s sent against a computed 40B x
60Hz, ~3540 B/s received against 59B x 60Hz), and buffer depth/lead/loss
all moved in the correct direction between a clean LAN run and one under
simulated 60ms latency + 10% loss. Full regression suite re-run clean.
2026-08-20 13:32:16 +01:00
Josh Creek b290f49143 feat(multiplayer): Phase 3 task 3.4 - input validation, rate limiting, disconnect policy
MatchSim._recv_input now validates before decoding (§3.1 steps 2-3):
per-peer rolling-1s rate limiting (packet count AND byte budget, dropping
over-budget packets and disconnecting after 3 consecutive over-budget
seconds), and framing validation (redundancy count and payload size
checked against NetCodec's own layout before unpack_input ever runs,
disconnecting after 20 malformed packets). Framing has to be validated
explicitly rather than relying on decode failure: StreamPeerBuffer
silently zero-fills past EOF instead of erroring, a finding from Phase
2's adversarial review.

networked_match.gd's _on_input_received now rejects any seq claiming to
be more than 20 ticks ahead of the current server tick (§3.1 step 4) and
counts (rather than silently ignoring) input from a peer with no slot,
for observability.

Verified with two new permanent regression tests (networked_match_smoke.gd
--role=client-abuse-malformed / client-abuse-flood) that call
MatchSim._recv_input directly with garbage bytes and a legitimate-but-
too-frequent flood, respectively, bypassing the honest client encoder
entirely - the same thing a hostile custom client sending raw ENet
packets would look like. Both confirm real disconnection, not just that
the server tolerates the abuse.

Two bugs surfaced by getting these tests to actually pass cleanly: a
GDScript lambda-capture-by-value mistake in the tests themselves (a
plain `var disconnected := false` mutated inside a signal-handler lambda
never became visible to the enclosing function - fixed by capturing a
single-element Array instead, which is captured by reference); and a
narrow real race where NetworkManager's own ping/pong reply could target
a peer that a concurrent abuse-triggered disconnect had just removed
from the same poll() batch, now guarded. (Passing disconnect_peer's
`force` parameter as an attempted fix for a related one-off benign error
was tried and reverted - it made Godot's own peer-list bookkeeping
inconsistent, producing hundreds of errors instead of one; verified
empirically rather than assumed.)

Full regression suite, including the net-sim-latency milestone gate,
re-run clean.
2026-08-20 13:27:03 +01:00
Josh Creek 5bbb319161 feat(multiplayer): Phase 3 task 3.3 - client-owned input_lead control loop
New InputLeadController (scripts/input_lead_controller.gd, standalone and
unit-tested like input_jitter_buffer.gd): fast attack (+3 immediately,
debounced to once per 30 ticks) on any server-reported starve, slow
release (-1 per 60 ticks, gated behind a one-time 2s clean-surplus bar)
otherwise, clamped [1, 12]. Deliberately the only thing that adapts
buffer depth - the server (InputJitterBuffer) stays a pure reporter, per
§3.3's explicit warning that multiple control loops acting on one plant
(buffer occupancy) oscillate and present as unattributable sticky
controls.

Wired into the client's per-tick input send: a lead change is realized as
extra distance between the client's outgoing sequence numbers and what
the server has consumed - an attack skips extra sequence numbers, a
release duplicates the current one (sent again, unincremented). The
server's ring buffer needs no special handling for either: a skipped seq
is an ordinary drop, a duplicated one is a same-seq resend already
discarded by the existing "already consumed" check.

Verified with real two-process runs: on a clean LAN, one early attack
(a momentary hiccup during connection setup) recovers via two releases
within the test's own ~4s window, settling back near minimum. Under
sustained 30% simulated loss, lead climbs to 7 via repeated attacks and
never releases while genuine loss continues - confirming the debounce,
attack, and release gates all fire on real conditions, not just in
isolated unit tests. Full regression suite, including the net-sim-latency
milestone gate, re-run clean.
2026-08-20 13:14:40 +01:00
Josh Creek 86a597f0f5 feat(multiplayer): Phase 3 tasks 3.1/3.2/3.5 - input redundancy + server jitter buffer
Client now sends the last 4 ticks' actions per packet (newest-first,
already-supported by net_codec's wire format from Phase 1) instead of a
single action with no redundancy. Server gains a real per-slot ring
buffer (new InputJitterBuffer class, scripts/input_jitter_buffer.gd) that
consumes exactly one sequence number per physics tick: repeats the last
action on a starve, zeroes only after a sustained 500ms stall, and
reports real input_buffer_depth/last_input_seq/echo_client_send_ms in
every snapshot instead of the hardcoded zeros Phase 2 shipped with.

InputJitterBuffer is a standalone, scene-free RefCounted (same pattern as
net_codec.gd/net_interpolator.gd) specifically so it's unit-testable
against scripted arrival traces (tests/cases/test_input_jitter_buffer.gd):
sequential consumption, redundancy surviving a 3-packet burst loss (3.1's
own acceptance criterion), starvation repeat-then-zero timing, stale/
reordered packet handling, buffered-depth reporting, and ring-wraparound
slot-tagging safety.

One real bug found wiring this into a live match: the server's ring
buffer started counting its own "expected sequence" from 0 the instant a
player's slot was created - well before that player's first real packet
could possibly have arrived (connection handshake, arena/ship spawn all
take real time first). Since both sides only ever advance monotonically
with no resync mechanism, that gap between the server's arbitrary local
counter and the client's actual from-1 sequence numbers never closed,
so the ship simply never received the client's input (0m movement in a
two-process test). Fixed by seeding the buffer's expected-sequence
counter from the client's own numbering on first real ingest, rather
than assuming a shared from-zero baseline.

Verified with real two-process runs: clean baseline movement restored,
zero starvation observed under 25% random simulated input loss (well
above what redundancy-4 needs to fully absorb), and correct starve-then-
stall behaviour confirmed under 100% loss as a sanity check that the
mechanism isn't a silent no-op. Full regression suite, including the
net-sim-latency milestone gate, re-run clean.
2026-08-20 13:07:33 +01:00
Josh Creek 14698d4ccb fix(multiplayer): adversarial review fixes for Phase 2
An Opus subagent's adversarial review of Phase 2 found real bugs the
smoke tests couldn't catch, since constant-velocity dead reckoning still
moves a ship far enough to pass a "moved > 1.0" check:

- The interpolator never actually interpolated. NetInterpolator.to_tick()
  assumes physics_frame * TICK_MS == Time.get_ticks_msec() on the server,
  which is off by a steady ~45-55ms in practice (real startup work before
  the first physics step, widened by any dropped tick). Every sample_at()
  call took the extrapolation branch, 100% of the time, defeating the
  interpolation buffer entirely. Fixed with a shared, min-filtered rolling
  bias estimate in networked_match.gd, applied before every to_tick() call.

- Goals caused a ~27m visual slide: _reset_gen was bumped before the
  queued teleport actually landed, so the client's buffer-clear kept
  exactly the stale in-goal sample and lerped a slide to the next, real
  one. Fixed by tracking the tick the goal was detected on and only
  bumping the generation once strictly later ticks confirm the teleport
  has landed - a naive "next _physics_process" boolean flag doesn't
  work, since a goal Area's body_entered fires before that same tick's
  _physics_process runs, not on the next one.

- _local_input_sampler (a Node, never added to the tree) was never freed
  - this was the unexplained "3 resources still in use at exit" warning
  on every Phase 2 test run.

- Ball angular velocity decoded 8x too small (rescale_avel was never
  called); get_server_time_estimate_ms() was used before the clock had
  synced; net_sim.gd's delayed-send timer stopped ticking while the tree
  was paused and didn't check connection status before firing;
  _broadcast_snapshot's ball index could silently break if a ship were
  ever despawned; declared-but-unemitted HUD lifecycle signals showed a
  permanently frozen timer widget.

Also confirmed, empirically, several things the review checked and found
fine: a hostile client sending malformed input cannot crash the server,
skipping GameMode's super() drops nothing load-bearing, deterministic
slot assignment is correct with 2 real simultaneous clients, and RPC
authority enforcement genuinely rejects a forging client.

All fixes verified with real two-process runs (including forcing an
actual goal and reading the server's own broadcast stream) and temporary
instrumentation, removed once each fix was confirmed. Full Phase 1 +
Phase 2 regression suite, including the net-sim-latency milestone gate,
re-run clean after every fix.
2026-08-20 12:43:33 +01:00
Josh Creek 7b150ef72e feat(multiplayer): task 2.8 net_sim.gd, close out Phase 2
New NetSim autoload: seeded, CLI-driven (--net-sim-latency/-jitter/-loss/-dup)
latency/jitter/loss/duplicate decorator, a true no-op passthrough unless a
flag is set. Wraps MatchSim.send_input/send_snapshot per the design doc's
scope, plus NetworkManager's ping/pong so the already-tested RTT/clock
measurement becomes the acceptance signal for "raises observed RTT" without
waiting on Phase 3's per-peer snapshot echo.

Two real bugs found while building and verifying this against Phase 2's own
milestone gate (a real match under --net-sim-latency 80 --net-sim-jitter
20, not just LAN): a timestamp captured inside a delayed RPC closure
silently ate that side's own added delay out of the round-trip
measurement instead of adding to it; and a delayed send whose target
disconnected (or whose own process had already shut down) during the hold
threw RPC errors, since the existing get_peers() filtering only checked
validity at schedule time. Fixed by capturing timestamps before handing
off to NetSim, and by having NetSim re-validate the target at fire time.

Phase 2's milestone gate now passes for real: a full 1v1 under simulated
80ms latency / 20ms jitter still shows clean server-authoritative
movement and zero RPC errors. Full Phase 1 + Phase 2 regression suite
re-verified clean with NetSim present but inactive.
2026-08-20 08:50:47 +01:00
Josh Creek 39a41c016c feat(multiplayer): Phase 2 server-authoritative simulation, dumb client
Implements tasks 2.1-2.7: NetworkedMatch spawns a deterministic slot
layout from the lobby roster, the server drives each connected peer's
ship via RLShipController fed by decoded client input and broadcasts
60Hz snapshots, and the client renders everything (including its own
ship) from a per-body NetInterpolator with no local prediction yet.
Dual-time remote entities split collider updates (present-time, for
correct contacts) from $Visual updates (interp-delayed, for smoothness).
Camera/HUD wiring and remote engine-flame VFX fell out of the existing
Ship API for free once snapshots were flowing.

Three real bugs found and fixed while getting a two-process test
green: an RPC method named _input collided with Node's built-in
_input virtual and broke the whole MatchSim autoload from loading;
networked_match.gd never called NetworkManager.poll(), so nothing
sent via RPC in this scene reached the wire despite Phase 1's manual
polling being wired up everywhere else; and a match_config
request/response fallback (added to close a startup race) could
double-deliver once polling was fixed, requiring an idempotency guard.

Verified with tests/networked_match_smoke: a real headless two-process
host+client run shows the client rendering 31m of server-authoritative
movement from a held forward-thrust input, with thrust_z=1.0 confirmed
on the interpolated snapshot mid-drive and camera/HUD both wired.
Full Phase 1 regression suite re-run clean alongside it.

Task 2.8 (net_sim.gd latency/jitter/loss decorator) is not yet done;
Phase 2's own gate needs it before it's fully met.
2026-08-20 08:42:13 +01:00
Josh Creek 4533da34e0 feat(multiplayer): Phase 1 transport, connection, and lobby
Lands tasks 1.0-1.8 of multiplayer-todo.md: the pure-function test runner,
net_codec (wire format quantizers/pack-unpack), NetworkManager (ENet
transport, manual polling, min-RTT clock sync), MatchNet (handshake,
protocol/tick-rate gating, roster with team+ready state), lobby.tscn (team
columns, switch team, ready toggle), server_boot.tscn (headless dedicated
server with structured logging and an overrun watchdog), and main_menu.gd's
Host/Join-by-IP UI (connecting overlay, cancel, bounded failure path).

Followed by an adversarial review (Opus subagent) that found and fixed two
real bugs - an unvalidated player_name broadcast that let one client's
oversized name head-of-line-block the reliable channel for everyone, and a
server-side roster leak across a host/re-host cycle - plus three gaps in
the test suite itself where a claim of "verified" wasn't actually backed
by what the test checked. All five two-process smoke tests plus the
pure-function suite are green with the strengthened assertions in place.
2026-08-20 08:18:59 +01:00
Josh Creek e83bb4fa0c fix(multiplayer): revert stray match.tscn team_size, record 0.15b real-hardware results
match.tscn had picked up team_size=3 from an earlier diagnostic dry run,
which would have made every normal Match spawn 3v3 instead of 1v1 -
reverted to the scene's intended default.

multiplayer-todo.md: task 0.15b's real blocker turned out to be measuring
on a Mac (Apple Silicon's tile-based GPU architecture gave a misleading,
undifferentiated cost profile). Re-ran the same 6-ship-match profiling
harness on reference hardware (RTX 3090) via a real GPU-bound X session -
results in §5.5.2 show the game comfortably clears 500+fps with every
effect on, and SDFGI/SSIL dominate the (now tiny) effects budget as
originally expected. This closes 0.28 (physics threading) as unnecessary
- there's no frame-time variance problem on reference hardware to fix -
and reframes 0.26 (bake GI) as a real but smaller win than assumed, worth
revisiting on lower-end hardware. Also corrected two stale/inaccurate
task rows (0.13, 0.17) found while reconciling the doc against what
actually landed.
2026-08-19 23:16:21 +01:00
Josh Creek 04691aaa48 chore(multiplayer): Phase 0 refactors + graphics/perf settings groundwork
Lands the non-networked Phase 0 tasks from multiplayer-todo.md (ship/camera/
arena refactors, sim constants, background FPS handling) plus a first pass
at exposing graphics/performance settings (presets, resolution scaling,
vsync, FPS cap, perf overlay) and a GPU profiling harness for the
real-hardware follow-up in task 0.15b.
2026-08-19 22:37:17 +01:00
567 changed files with 60318 additions and 632 deletions
+23
View File
@@ -0,0 +1,23 @@
name: Agones Integration
on:
workflow_dispatch:
pull_request:
paths:
- Dockerfile
- Makefile
- deploy/k8s/**
- scripts/verify_kind_agones.sh
- .github/workflows/agones-integration.yml
permissions:
contents: read
jobs:
kind-agones:
runs-on: ubuntu-latest
timeout-minutes: 30
steps:
- uses: actions/checkout@v4
- name: Verify disposable kind/Agones lifecycle
run: make verify-kind-agones
+27
View File
@@ -0,0 +1,27 @@
name: Allocated Compose Smoke
on:
workflow_dispatch:
pull_request:
paths:
- Dockerfile
- Makefile
- compose.allocated-smoke.yml
- server/api/**
- server/store/**
- server/workload/**
- server/migrations/**
- scripts/verify_allocated_compose.sh
- .github/workflows/allocated-compose.yml
permissions:
contents: read
jobs:
allocated-compose:
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v4
- name: Verify independent allocated Compose flow
run: make verify-allocated-compose
@@ -0,0 +1,14 @@
name: Dedicated Server Smoke Test
on:
push:
pull_request:
jobs:
dedicated-server-smoke:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v7
- name: Build and verify exported dedicated server
run: make verify-phase6
+16
View File
@@ -0,0 +1,16 @@
name: ENet Integration Tests
on:
push:
pull_request:
jobs:
enet-integration:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@v7
- name: Build the pinned Godot test image
run: docker build --target enet-test -t cosmic-clash-enet-tests .
- name: Run multi-process ENet smoke tests
run: docker run --rm cosmic-clash-enet-tests bash scripts/verify_enet_integration.sh
+26
View File
@@ -0,0 +1,26 @@
name: Multiplayer Chaos Recovery
on:
workflow_dispatch:
pull_request:
paths:
- Dockerfile
- Makefile
- compose.chaos-smoke.yml
- server/cmd/maintenance/**
- server/store/**
- server/migrations/**
- scripts/verify_chaos_recovery.sh
- .github/workflows/multiplayer-chaos.yml
permissions:
contents: read
jobs:
api-restart-recovery:
runs-on: ubuntu-latest
timeout-minutes: 15
steps:
- uses: actions/checkout@v4
- name: Verify API restart and stalled-allocation recovery
run: make verify-chaos-recovery
+23
View File
@@ -0,0 +1,23 @@
name: Multiplayer API Load
on:
workflow_dispatch:
pull_request:
paths:
- server/api/**
- server/domain/**
- server/matcher/**
- Makefile
- .github/workflows/multiplayer-load.yml
permissions:
contents: read
jobs:
api-load:
runs-on: ubuntu-latest
timeout-minutes: 10
steps:
- uses: actions/checkout@v4
- name: Verify 10,000-client API load boundary
run: make verify-multiplayer-load
+47
View File
@@ -0,0 +1,47 @@
# The Go control plane is ~24k lines, and until this workflow existed the only
# Go tests CI ever ran were the two load tests in multiplayer-load.yml. Nothing
# else — domain policy, the wire/store boundaries, the allocator, the Steam
# adapter — gated a change. The Godot unit suite is covered (verify-phase6 runs
# test_runner.tscn as its first step); this closes the equivalent gap on the
# Go side.
#
# Deliberately Docker-free and cluster-free so it stays fast enough to gate
# every push. Tests that need a real PostgreSQL or Redis are behind the
# `integration` build tag and stay with their own scripts; `go vet` is still
# run over that tag so those files cannot rot uncompiled.
name: Server Unit Tests
on:
push:
pull_request:
permissions:
contents: read
jobs:
go-tests:
runs-on: ubuntu-latest
defaults:
run:
working-directory: server
steps:
- uses: actions/checkout@v4
- uses: actions/setup-go@v5
with:
go-version-file: server/go.mod
cache-dependency-path: server/go.sum
- name: Build
run: go build ./...
- name: Vet
run: go vet ./...
# Integration-tagged files are excluded from the default build, so
# without this a signature change could leave them broken until someone
# ran the integration scripts by hand.
- name: Vet integration-tagged tests
run: go vet -tags integration ./...
- name: Test
run: go test ./...
# The control plane is concurrent by design: outbox dispatchers, the
# event hub, the matcher worker and the allocator all run in parallel.
- name: Test with race detector
run: go test -race ./...
+18
View File
@@ -0,0 +1,18 @@
name: Supply Chain Policy
on:
push:
pull_request:
permissions:
contents: read
jobs:
repository-policy:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Verify immutable image references and secret hygiene
run: make verify-supply-chain
- name: Verify release process is documented
run: test -s docs/SUPPLY-CHAIN.md
+9
View File
@@ -17,5 +17,14 @@ training/checkpoints/*/ppo_*_steps.zip
# export_linux.sh / run_training.sh), not a training result.
training/build/
# Exported dedicated server binary (task 6.1): same reasoning — an 85MB
# regenerable artifact, rebuilt by `godot --headless --path Game
# --export-release "Linux Dedicated Server"`.
server/build/
# Steam exports and local App ID configuration are developer-machine inputs.
steam/build/
steam_appid.txt
# Texture generator scripts: throwaway env, not the scripts themselves.
tools/textures/.venv/
+141
View File
@@ -0,0 +1,141 @@
# Investigate and fix the failing Agones Integration CI gate
## Task
`make verify-kind-agones` (workflow `.github/workflows/agones-integration.yml`,
script `scripts/verify_kind_agones.sh`) fails. Find the root cause and fix it so
the gate passes on CI. Repo: `jcreek/CosmicClash`, branch `feat/multiplayer`,
PR #30.
## What is already known — do not re-derive this
**The failure.** `helm upgrade --install agones ... --wait --timeout 5m` fails
with `Error: context deadline exceeded`. Immediately before, Helm reports:
```
resource Deployment/agones-system/agones-controller not ready. status: InProgress, message: Available: 0/1
resource Deployment/agones-system/agones-extensions not ready. status: InProgress, message: Available: 0/1
resource Deployment/agones-system/agones-allocator not ready. status: InProgress, message: Available: 0/1
```
So the cluster is created, the game-server image loads, and the Agones chart
installs — but none of its Deployments become Available inside 5 minutes. The
script never reaches the parts that exercise this repo's own manifests.
**It is pre-existing.** It fails identically at `089c127c`, the branch head
before recent work. It is not caused by the branch's changes. Do not assume a
recent commit broke it.
**It is not architecture-specific.** It fails the same way on GitHub's
`ubuntu-24.04` amd64 runners and on an arm64 macOS developer machine. Agones
1.49.0 publishes both amd64 and arm64 images.
**It is not a Helm kubeVersion rejection.** Agones charts 1.49.0, 1.50.0 and
1.51.0 declare no `kubeVersion` constraint, so Helm is not refusing the
Kubernetes version — the pods are being created and are not becoming ready.
**Ruled out as a red herring:** reproducing locally on a machine with heavy
Docker usage produced `FailedCreatePodSandBox: containerd connection reset`,
which is local resource pressure, not the CI cause. If you see that locally,
clear Docker state and retry rather than chasing it.
**There may be two distinct failures, not one.** After `docker system prune`,
a local run got *past* the Agones install cleanly (controller and allocator
both reached "condition met") and failed later, at:
```
scripts/verify_kind_agones.sh:146
kubectl wait --for=jsonpath='{.status.ready}'=2 fleet/cosmic-clash-game -n cosmic-clash --timeout=5m
error: timed out waiting for the condition on fleets/cosmic-clash-game
```
So locally the Agones install is fine and the **Fleet's game-server pods never
become Ready**; on CI the run never gets that far because the Agones install
itself times out. Treat these as potentially separate problems: fixing the CI
Agones timeout may simply expose the Fleet one underneath. Both need to pass.
The Fleet failure is the more suspicious of the two for recent work, because
`deploy/k8s/base/fleet.yaml` changed: the join-signing key material moved from
a single raw-bytes secret key (`join-signing-key`) to a JSON map
(`join-signing-keys.json`), and the mount's `items[].key` moved with it. The
script's `kubectl create secret` was updated to match and does succeed
(`secret/cosmic-clash-game-server created`), so the obvious mismatch is not
present -- but verify the pod actually mounts and starts rather than assuming.
Note the script's `sed` also strips `--allocated-mode` and the roster path and
blanks `--control-plane-url`, so the game server runs in a reduced mode here;
check whether it is failing for a reason unrelated to the key at all.
## Pinned versions (all in `scripts/verify_kind_agones.sh`)
| Thing | Value | Override |
|---|---|---|
| Agones chart | `1.49.0` | `AGONES_VERSION` |
| kind node image | `kindest/node:v1.33.1` (Kubernetes 1.33) | `KIND_NODE_IMAGE` |
| Cluster | single node, `--wait 120s` | `KIND_CLUSTER_NAME` |
| Runner | `ubuntu-latest` (ubuntu-24.04), 30 min timeout | — |
The chart is installed with `--set agones.controller.replicas=1`,
`agones.extensions.replicas=1`, `agones.allocator.replicas=1`, and
`agones.extensions.resources.{requests,limits}.ephemeral-storage` lowered to
128Mi/512Mi. That ephemeral-storage override already exists because Agones 1.49
otherwise requests 10,100 MiB and will not schedule on a default kind node —
there is a comment saying so. **A similar resource-fit problem for the other
Deployments is a strong hypothesis worth checking first.**
## Diagnostics are already in place
The script now dumps, on any failure and before the cluster is deleted: node
capacity and conditions, pods in `agones-system` and `cosmic-clash`, recent
events per namespace, and describe + current/previous logs for every not-ready
pod. Set `KIND_KEEP_ON_FAILURE=1` to retain the cluster for interactive
inspection instead of deleting it.
Its first run revealed a bug in the diagnostics themselves: a
`kubectl cluster-info` reachability guard suppressed the entire dump. That
guard has been removed, so the dump now always runs on failure.
**Start by reading that output**, either from a CI run or a local run. The most
likely candidates it will distinguish between:
1. **Resource pressure** — `FailedScheduling ... Insufficient cpu/memory/
ephemeral-storage`. Fix by lowering requests for the other Deployments the
way extensions already is, or by giving the kind cluster more capacity.
2. **Version incompatibility** — Agones 1.49 against Kubernetes 1.33. Check
Agones' release notes for its supported Kubernetes range; if 1.33 is outside
it, either raise `agones_version` or lower `kind_node_image`. Confirm the
pairing is one Agones actually tests.
3. **Probe/readiness failure** — pods Running but never Ready. The pod logs and
describe output will show the failing probe.
4. **Image pull** — `ImagePullBackOff` on an Agones image.
## Constraints
- **Do not weaken the gate to make it pass.** Removing `--wait`, extending the
timeout to hide a real failure, or `|| true` around the install are all wrong.
If the cause is genuinely a timeout on slow-but-working startup, raising it
is acceptable *only* with evidence that the pods do become Available, and the
new value should be justified in a comment.
- Keep it a disposable, isolated cluster: it must not touch an existing cluster,
and the EXIT trap must still remove the one it created.
- If you change a pinned version, pin the new one explicitly and say why in the
commit message. Do not float to `latest`.
- `CLAUDE.md` applies: never create co-authored commits, never mention Claude.
## Verification
- `make verify-kind-agones` passes locally (needs Docker, kind, kubectl, Helm).
- The `Agones Integration` workflow passes on PR #30. It is `pull_request`
triggered with path filters on `Dockerfile`, `Makefile`, `deploy/k8s/**`,
`scripts/verify_kind_agones.sh`, and its own workflow file — so a change to
the script will trigger it.
- Do not regress the other seven workflows. `Allocated Compose Smoke` was also
failing and has just been fixed; confirm it stays green.
## Useful context
- `multiplayer-next.md` §7 task 8.49 describes what this gate is meant to prove.
- `deploy/k8s/base/fleet.yaml` is the Fleet the script applies after Agones is
up, with a `sed` that swaps the release digest placeholder for the locally
built image and strips `--allocated-mode` and the roster path (there is no
control plane in this disposable cluster).
- The gate is a prerequisite for issue #17 (standing up a real cluster).
+234 -18
View File
@@ -2,14 +2,30 @@
This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
Important rule: never create co-authored commits. Never mention Claude in commits.
Important rule: never create co-authored commits. Never mention Claude in commits.
## Project overview
Cosmic Clash is an open-source, physics-based "vehicle soccer" game (a spiritual successor to Rocket League) built in Godot 4.7, using space ships instead of cars. The project is GDScript/Godot only right now — the "C# backend" mentioned in README.md is planned but not yet started. There is no server-side code; the MVP is local-only play against bots.
Cosmic Clash is an open-source, physics-based "vehicle soccer" game (a spiritual successor to Rocket League) built in Godot 4.7, using space ships instead of cars. The game and the dedicated server are GDScript/Godot only — the "C# backend" an early README described was never started, and the dedicated server is an export of this same Godot project. There is one component outside the Godot project: a **Go matchmaking control plane** in `server/` for casual/ranked queues, ranked ratings and Agones-based server allocation. It is a 1.0 launch blocker — see `docs/MATCHMAKING.md` for the design, `multiplayer-next.md` §0 and §7 for what remains (the allocation-to-connect pipeline is now wired end to end; what is left is external — a Steamworks App ID, custom GodotSteam builds, a registry to publish images to, and a live Agones cluster; `TODO.md` orders them), and `docs/TECH_STACK.md` for why the control plane is Go rather than C#, Rust or C++. README.md's "MVP is local-only against bots" section is historical: server-authoritative online multiplayer, a headless dedicated server, Docker/CI verification, and an optional Steam transport are all implemented (Phases 16). See `multiplayer-next.md` for what actually remains.
Because the gameplay concept (vehicle soccer) can't be copyrighted but specific expression can, all code/art/assets must be original — this is why the project uses Godot instead of Unreal/Unity and ships instead of cars. Keep this in mind when writing code or pulling in assets: don't port or closely mirror Rocket League's actual implementation.
### Where the documentation lives
The prose docs carry far more design rationale than the code comments, and several are load-bearing:
- `multiplayer-next.md`**the multiplayer task-tracking document**: outstanding work (§0), a numbered "gotchas" list (§9), and the current task breakdown with checkboxes (§7), all in one file. Start at §0 for "what's left". Day-to-day work is Phase 7 (Steam) and Phase 8 (matchmaking), whose numbered task breakdown and acceptance criteria live in §7, because that is the format tasks are picked up from. Phases 06 are done and archival — their evidence lives in git history, not the current doc.
- `MULTIPLAYER_SPEC.md` — the architecture decisions, wire format, server-side input handling, prediction/reconciliation, latency/frame-rate budget and match lifecycle state machine, as sections 16. Code comments across `Game/scripts/` cite it constantly by section number (`§2.4`, `§4.1`); many still say `multiplayer-next.md §N` for `N` 16 from before this doc was split out — when a comment does, the content is now here, not there. `multiplayer-next.md`'s own §7+ cites `§N` the same way and disambiguates by number (16 → this doc, 7+ → itself).
- `TRAINING.md` — the full RL workflow (training, curriculum generations, export, eval, difficulty tiers).
- `SERVER.md` — dedicated-server build, config, systemd deploy, sizing.
- `STEAM.md` — optional GodotSteam custom-build setup and the transport contract.
- `FLIGHT_MANUAL.md` — the player-facing flight model.
- `docs/MATCHMAKING.md` — casual/ranked queue design, and the locked constraints (Go/PostgreSQL/Redis/Agones) the `server/` module implements. Partially implemented; a 1.0 launch blocker, and the reason a backend service outside the Godot project exists at all.
- `docs/TECH_STACK.md` — what the project is built with and why, including the Go-vs-C#/Rust/C++ rationale for the matchmaking control plane.
- `TODO.md` — deferred non-multiplayer work, **and** the ordered human-actionable backlog: which GitHub issue to do first, what each one unblocks, and which items are waiting on nobody. Start there when asking "what next". Audio is no longer absent — a procedural `AudioManager` covers UI, countdown, impact, goal and engine/turbo cues; what remains is authored assets.
- `docs/THREAT-MODEL.md`, `docs/SUPPLY-CHAIN.md`, `docs/OBSERVABILITY.md`, `docs/MATCHMAKING-SLOs.md`, `docs/ADR-001-matchmaking-platform.md` — the control plane's security, release, telemetry and SLO contracts. `server/security/*.py` asserts several of them against the checked-in manifests, so changing a manifest often means changing one of these.
- `docs/REVIEW-2026-09-feat-multiplayer.md` — a point-in-time adversarial review of this branch. Every finding in it is fixed; it is kept for the reasoning, not as a status report, and its header says so.
## Godot MCP server
This repo vendors [godot-mcp](https://github.com/tugcantopaloglu/godot-mcp) as a git submodule at `mcp/godot-mcp` and registers it in `.mcp.json`. **Prefer the godot-mcp tools over manual file edits or shell commands** when the task involves inspecting or modifying the Godot project — reading/editing scenes, nodes, scripts, running the project, or interacting with a live Godot editor/runtime instance. It understands Godot's scene tree and `.tscn`/`.gd` structures directly, which is more reliable than hand-parsing them.
@@ -53,34 +69,234 @@ Upstream ships telemetry, and there are **two independent switches** — turning
## Commands
There is no build step, linter, or automated test suite for the GDScript project itself — Godot projects run directly from source.
There is no build step or linter for the GDScript project itself — Godot projects run directly from source.
### Running the game
- **Open the project**: open `Game/` as a project in the Godot 4.7 editor, or run `godot --path Game` from the repo root.
- **Run the game**: press Play in the editor, or `godot --path Game res://scenes/main_menu.tscn`.
- **Headless smoke test** (RL/CI precondition — the game must run without rendering): `godot --headless --path Game res://scenes/free_play.tscn`.
- **Import resources first** on a fresh checkout or in a container: `godot --headless --path Game --import`. Do **not** add `--quit` — it ends the editor after one iteration and can leave `.godot/imported` half-generated (see the Dockerfile comment).
### Unit tests
`godot --headless --path Game res://tests/test_runner.tscn` — pure-function assertions, exits 0/1.
Add a test by dropping a `*.gd` file under `Game/tests/cases/` that extends `res://tests/test_case.gd` (path-based `extends`, not the bare `class_name` — see that file for why) with any number of `test_*()` methods; the runner discovers it, no registration needed. The same path-vs-`class_name` caveat is why `net_codec.gd`, `sim_constants.gd` etc. are reached by `preload()` elsewhere in the codebase.
The runner has **no filter flag** — it always runs everything (it's fast). To isolate one case, temporarily move the others out of `tests/cases/`.
Two runner behaviours exist because of past silent-pass bugs, and new tests must respect them: a case file that fails to parse is a failure (`can_instantiate()` is the guard — `load()` does *not* return null on a broken script), and **a test that completes having made zero assertions is itself a failure**, because GDScript has no exceptions and a crash before the first `assert_*` would otherwise read as a pass.
### Networking smoke tests (multi-process)
These need two or three real `godot --headless` processes for a live ENet handshake, so they are **not** part of `test_runner.tscn`. Each prints `SMOKE PASS/FAIL: ...` and exits 0/1. Run them all through the wrapper:
```bash
make verify-enet-integration # host+client pairs for every case, then the 3-process match
VERIFY_ENET_CASES=net,clock make verify-enet-integration # subset, for local debugging
GODOT_BIN=/path/to/godot make verify-enet-integration # non-default Godot binary
```
`scripts/verify_enet_integration.sh` starts each role, waits, and fails on any `SCRIPT ERROR`/`ERROR:`/`SMOKE FAIL` in the logs — a clean exit code alone is not the bar. It prints its temp log directory and dumps the logs on failure. The individual scenes, if you need to drive one by hand with `-- --role=<role>`:
| Scene | Roles | What it proves |
| --- | --- | --- |
| `tests/net_smoke.tscn` | `host`, `client` | Raw connect/disconnect; the host observes `client_disconnected`, not just clean self-exit. |
| `tests/match_net_smoke.tscn` | `host`, `client`, `client-badversion`, `client-longname`, `host_recycle` | Handshake gating (protocol version, oversized name rejection) and that a host→leave→re-host cycle actually empties the roster (run a plain `client` against `host_recycle`). |
| `tests/clock_smoke.tscn` | `host`, `client` | Clock convergence, cross-checked against independent OS-wall-clock ground truth rather than self-consistency. |
| `tests/lobby_smoke.tscn` | `host`, `client` | **Both** roles load `lobby.tscn` for real via `change_scene_to_file`, exercising the server's read-only view as well as the client's interactive one. |
| `tests/networked_match_ci.tscn` | `host`, `client-bot --test-bot` (×2) | A full server + two AI-driven clients playing a real match: snapshot throughput and cross-peer score agreement, via a deterministic server-forced goal. |
| `tests/networked_match_smoke.tscn` | see its header | Shorter attended variant of the above. |
| `tests/net_sim_smoke.tscn` | see its header | The `--net-sim-*` latency/loss decorator actually changes observed behaviour. |
See `network_manager.gd`'s header comment and `multiplayer-next.md` §9 gotchas 2530 for the non-obvious Godot/ENet failure modes these caught (`OfflineMultiplayerPeer` sentinel, premature peer teardown, `change_scene_to_file` off the real `current_scene`, unbounded `connection_failed`, the `is_client`-before-actually-connected race, `load()` not returning null on a broken script).
**`main_menu.tscn`'s Host/Join flow** is verified the same way but needs a temporary autoload since it's the real main scene, not a wrapper: add `MainMenuTestHooks="*res://tests/main_menu_test_hooks.gd"` to `project.godot [autoload]`, run `godot --headless --path Game res://scenes/main_menu.tscn -- --role=<host|join_ok|join_refused|join_cancel>` (host first, sleep ~1s, then the join role), then remove the autoload line again — it must never ship registered.
`tests/server_physics_parity.gd` is a standalone `SceneTree` script (no `.tscn`, no wired runner) that traces the real Ship scene through fixed inputs and dumps every physics step's pose/velocity plus the observation vector. It exists to be diffed against the same file run from a `git archive HEAD` tree, proving a client-side change didn't perturb shared physics.
### Dedicated server (Docker)
```bash
make verify-phase6 # the whole exported-server gate; also the entire Phase 6 CI workflow
```
This builds the stripped `Linux Dedicated Server` export, runs it in one container, joins two independent headless clients from two others, forces a server-owned goal in each of two matches, and asserts both clients saw both scores **and that the arena actually rotated between matches**. It needs several GB of free Docker space (the pinned `barichello/godot-ci:4.7.1` image is ~2.4 GB) and always tears down its Compose containers, printing its log directory either way.
The Dockerfile's targets are worth knowing: `project-imported` (base, resources imported) → `enet-test` (source client, used by the ENet CI workflow) → `exporter` (rewrites `run/main_scene` and exports the server) → `server` (slim Ubuntu runtime) and `smoke-client` (test-only harness). **Godot dedicated exports refuse command-line scene overrides**, which is why the server scene is baked in by `sed` at export time rather than passed as an argument.
To run one by hand, and for every config flag, see `SERVER.md`. `--smoke-force-goal-after=<seconds>` is a verification-only switch and must never be used for a real match.
### Steam builds (optional)
`make verify-steam-templates` requires custom GodotSteam executables pinned in `steam-dependencies.lock.json` and pointed at by `COSMIC_CLASH_STEAM_CLIENT_GODOT` / `COSMIC_CLASH_STEAM_SERVER_GODOT`. It deliberately refuses a stock Godot binary. Nothing else in the repo needs Steam — the default build and every Docker check are ENet-only. See `STEAM.md`.
### CI
`.github/workflows/` has eight jobs, all but one running a Make target:
| Workflow | Runs | Needs |
|---|---|---|
| `server-unit-tests.yml` | `go build`/`vet`/`vet -tags integration`/`test`/`test -race` in `server/` | nothing (no Docker) |
| `dedicated-server-smoke.yml` | `make verify-phase6` | Docker, several GB |
| `enet-integration.yml` | `make verify-enet-integration` inside the `enet-test` image | Docker |
| `allocated-compose.yml` | `make verify-allocated-compose` | Docker Compose |
| `agones-integration.yml` | `make verify-kind-agones` | kind + Helm |
| `multiplayer-chaos.yml` | `make verify-chaos-recovery` | Docker |
| `multiplayer-load.yml` | `make verify-multiplayer-load` (two `-tags load` Go tests) | — |
| `supply-chain.yml` | `make verify-supply-chain` | — |
**The Godot unit suite runs via `verify-phase6`**, which invokes `test_runner.tscn` as its first step — there is no separate Godot workflow. The Go unit suite has its own workflow because until it existed the only Go tests CI ran were `multiplayer-load`'s two load tests, so ~24k lines of control plane gated nothing.
Note what is *not* in CI: `make verify-multiplayer-local` (the combined local gate, which also runs the Python manifest/contract suites) and the `integration`-tagged Go tests, which need a real PostgreSQL/Redis and live in `scripts/run_*_integration.sh`. Run those by hand before landing server changes.
### When a gate fails, suspect the assertion first
The most expensive failures in this repo have not been broken behaviour. They
have been **assertions that cannot distinguish the two states they implicitly
claim to**, each reporting its own ambiguity as a confident verdict about the
system under test. Five in one session, several costing multiple CI round trips:
| Assertion | What it actually conflated |
|---|---|
| `kubectl wait --for=jsonpath='{.status.ready}'` on an Agones Fleet | field does not exist vs. condition unmet — it could never pass |
| `compose ps --status running \| grep -qx game-server` | not started *yet* vs. exited |
| `remote_residual_position_p99 < 0.3` | real regression vs. host scheduling noise |
| a validator reading `status.gameServer` | Agones' real response vs. an invented one, with unit tests asserting the invention |
| `docker image inspect` guarding a build | image is current vs. image merely exists, so a rerun verified stale code |
Before theorising about the code, ask: **can this check tell "broken" from
"not ready yet", "absent" from "unset", or "regressed" from "slow"?** If not,
that is the bug, whatever else is also true.
Two habits follow from it, and both repeatedly beat reading code:
- **Make the script say what it saw before diagnosing why.** Most gates here are
`curl -fsS` and bare `[[ ]]` under `set -e`, which abort silently — several CI
runs produced nothing but `make: *** Error 1`. Report the failing line and
command, print the value that failed its comparison, and dump the surrounding
state *before* any cleanup trap destroys it. Every root cause found in that
session came from doing this; essentially every confident guess made without
it was wrong.
- **Verify the diagnostics fire.** Two separate dumps were added and neither ran:
one behind a `kubectl cluster-info` guard that misjudged reachability, one
because a bare `trap ... ERR` does not fire inside functions or subshells
without `set -E`. A diagnostic that has never been seen working is not
evidence.
And when a test and the code agree but reality disagrees, suspect they were
written together. A validator and its fixtures both encoded a response shape
Agones never sends; nothing caught it because the gate had never run far enough
to see a real one.
### Other
- The `mcp/godot-mcp` submodule is a separate Node/TypeScript project with its own `npm install` / `npm run build` (see above) — it is tooling, not part of the game itself.
- `Game/tools/` holds editor-run utilities (`bake_arena_boundary.gd`, `gpu_profile_harness.tscn`, `replay_dump.gd` for reading server replay logs); `tools/blender/` and `tools/textures/` hold the Python generators for the original ship/ball/nebula assets.
## Architecture
The structure was deliberately chosen so an RL-trained AI opponent and, later, multiplayer bolt on without rework (see `TODO.md` for the deferred work). The three load-bearing seams are the controller abstraction, the arena/game-mode split, and code-driven spawning.
The structure was deliberately chosen so an RL-trained AI opponent and, later, multiplayer bolt on without rework. The load-bearing seams are the controller abstraction, the arena/game-mode split, code-driven spawning, and (for networking) the pure-function codec/state modules that can be unit-tested without a live connection.
- **Scene flow**: `scenes/main_menu.tscn` (`main_menu.gd`, one handler per mode) → `scenes/free_play.tscn` (practice: no timer, R resets ball) or `scenes/match.tscn` (150s timer, per-team score, kickoff resets). Esc returns to the menu from either mode.
- **Controller seam (do not bypass)**: `Ship` (`scripts/ship.gd`, `RigidBody3D`) never reads `Input`. Each physics tick, `_integrate_forces` pulls one `ShipAction` (`scripts/ship_action.gd`: thrust `Vector3`, rotation `Vector3`, turbo `bool`, each axis -1..1) from its `ShipController` child (`scripts/ship_controller.gd`, base returns a zero action). `PlayerShipController` reads input actions; a future `AIShipController` (RL policy) or network-replication controller implements the same `get_action()` interface. A ship with no controller is inert but simulated. The ShipAction shape *is* the future RL action space — change it deliberately.
- **Arena vs game mode**: `scenes/arena_01.tscn` (`scripts/arena.gd`, group `"arena"`) is a stateless stadium — a setting (space-platform floor, starfield sky, lighting), an enclosing `Boundary` (instance of `objects/arena_boundary.tscn`: floor/walls/ceiling colliders), two `Goal` instances (team 0 and 1), `BallSpawn` and `SpawnsTeam0/1` Marker3Ds — queried via `get_ball_spawn()`/`get_ship_spawns(team)`/`get_goals()`. All arenas are a standard size: they instance the shared `arena_boundary.tscn`, and `scripts/arena_boundary.gd` (`ArenaBoundary`) holds the canonical play-volume constants (inner x ±12, z ±18, height 12, goal lines z ±17) that field-size logic must derive from instead of restating numbers. Game modes extend `GameMode` (`scripts/game_mode.gd`, group `"game"`): the mode's scene contains an Arena + HUD, and the mode spawns ball/ships/controllers/camera **in code** (`spawn_ship(team, index, controller)` etc.) so ship counts and controller mixes stay flexible. `free_play.gd` and `match_mode.gd` override `_start()` and `_on_goal_scored(conceding_team)`.
### Core game
- **Scene flow**: `scenes/main_menu.tscn` (`main_menu.gd`, one handler per mode) → `free_play.tscn` (practice: no timer, R resets ball), `match.tscn` (150s timer, per-team score, kickoff resets), `spectate.tscn` (bot vs bot exhibition), `settings.tscn`, or — for online — `lobby.tscn``networked_match.tscn`. Esc returns to the menu. Canonical paths live in `scripts/scene_paths.gd`; use those constants rather than string literals.
- **Controller seam (do not bypass)**: `Ship` (`scripts/ship.gd`, `RigidBody3D`) never reads `Input`. Each physics tick, `_integrate_forces` pulls one `ShipAction` (`scripts/ship_action.gd`: thrust `Vector3`, rotation `Vector3`, turbo `bool`, each axis -1..1) from its `ShipController` child (`scripts/ship_controller.gd`, base returns a zero action). `PlayerShipController` reads input actions; `AIShipController` runs an RL policy; `RLShipController` is driven by the training bridge; `LocalNetShipController` wraps another controller to record inputs into the network timeline. A ship with no controller is inert but simulated. The ShipAction shape *is* the RL action space and *is* what the wire format quantises — change it deliberately and everywhere at once.
- **Arena vs game mode**: an arena (`scripts/arena.gd`, group `"arena"`) is a stateless stadium — a setting, an enclosing `Boundary` (instance of `objects/arena_boundary.tscn`), two `Goal` instances, `BallSpawn` and `SpawnsTeam0/1` Marker3Ds — queried via `get_ball_spawn()`/`get_ship_spawns(team)`/`get_goals()`. All arenas are a standard size: they instance the shared `arena_boundary.tscn`, and `scripts/arena_boundary.gd` (`ArenaBoundary`) holds the canonical play-volume constants (`INNER_HALF_X` 18, `INNER_HALF_Z` 27, `INNER_HEIGHT` 18, `GOAL_LINE_Z` = `INNER_HALF_Z`) that field-size logic must derive from instead of restating numbers. Game modes extend `GameMode` (`scripts/game_mode.gd`, group `"game"`): the mode's scene contains an Arena + HUD, and the mode spawns ball/ships/controllers/camera **in code** (`spawn_ship(team, index, controller)` etc.) so ship counts and controller mixes stay flexible.
- **Arena registry**: `scripts/arena_registry.gd` is the single source of truth for the arena list — three settings × floor/elevated goal variants. `"random": true` gates which arenas Match/Spectate/the dedicated server may pick; **elevated-goal variants are Free-Play-only** until a checkpoint trained on `training_elevated.tscn` is promoted, because the current bots cannot score on an elevated goal. `path_for_match(match_index, mode)` is deliberately pure arithmetic so "the server cycles arenas" is unit-testable. **The Go control plane keeps its own copy of the ranked-eligible subset** (`server/domain/ranked.go`'s `rankedArenas`), because ranked arena selection is a server-authoritative decision made before any Godot process exists. That copy is not free to drift: `server/domain/arena_registry_sync_test.go` parses this file and fails if the two disagree in either direction, or if a ranked path has no scene behind it. Editing the arena list therefore means updating `ranked.go` too — the test says so when it fails. `arena_base.tscn` is the scenery-free physical layout the dedicated server loads (clients still render the variant `MatchSim` names).
- **Goals are dumb sensors**: `scripts/goal.gd` (`Area3D`, group `"goal"`, `@export team`) only emits `goal_scored(team)` when a body in group `"ball"` enters; `GameMode` debounces it (`_handle_goal_scored`) and modes decide consequences. Never put scoring/reset logic in the goal.
- **Ship physics**: all movement is force/torque-based (`_integrate_forces`), not kinematic — inputs become world-space forces/torques relative to ship orientation, with manual drag and speed clamps per tick. Physics formulas are commented inline; see `FLIGHT_MANUAL.md` for the player-facing flight model. Physics properties (mass, inertia, friction material) live in `objects/ship.tscn`, not in `_ready` overrides — keep the scene truthful; RL tuning depends on it.
- **Surface pull (wall/ceiling grav-plating)**: `ArenaBoundary.get_surface_pull()` is a wall+ceiling-only proximity force field (the floor stays plain default gravity) that `Ship` and `Ball` (`scripts/ball.gd`) each apply in their own `_integrate_forces` with independently-tuned strength/range, discovered via the `"arena_boundary"` group — enabling wall-rides and ceiling shots with no collision-shape changes. Because it runs inside `Ship`'s shared `_integrate_forces`, it reaches trained bots too; see `TRAINING.md` for the retrain this warrants.
- **Camera** (`scenes/ship_camera_rig.tscn`, `scripts/ship_camera.gd`, group `"ship_camera"`) is spawned by the game mode and given a `target` ship — ships have no camera/HUD dependency, so headless RL runs work (`godot --headless`).
- **HUD / telemetry pattern**: `Ship` emits flight data via signals only when values change past thresholds (`_last_*` fields, `*_THRESHOLD` constants). `HUDController` (`scripts/HUDController.gd` on `scenes/HUD.tscn`, instanced by each mode's scene) discovers the camera rig and game mode via groups (`"ship_camera"`, `"game"`) but receives its target ship directly from the game mode via `GameMode.spawn_camera_rig` (mirroring the camera rig's `target`, not group lookup — the `"ship"` group can have 2+ members), connects to signals, and only updates labels — no polling. Follow this discovery-by-group + signal-push pattern for new instruments or cross-node communication, not hardcoded `get_node` paths or per-frame polling.
- **Input actions** are defined in `Game/project.godot` under `[input]` (`move_forward`, `turn_left`, `turbo`, `reset_ball`, etc.) and read only by `PlayerShipController` (plus mode-level `_unhandled_input` for `reset_ball`/`ui_cancel`) — add new controls there rather than hardcoding key checks.
- Physics engine is Jolt (`Game/project.godot`, `[physics] 3d/physics_engine="Jolt Physics"`).
- **Ship physics**: all movement is force/torque-based (`_integrate_forces`), not kinematic — inputs become world-space forces/torques relative to ship orientation, with manual drag and speed clamps per tick. Physics properties (mass, inertia, friction material) live in `objects/ship.tscn`, not in `_ready` overrides — keep the scene truthful; RL tuning and the client/server parity trace depend on it.
- **Surface pull (wall/ceiling grav-plating)**: `ArenaBoundary.get_surface_pull()` is a wall+ceiling-only proximity force field (the floor stays plain default gravity) that `Ship` and `Ball` (`scripts/ball.gd`) each apply in their own `_integrate_forces` with independently-tuned strength/range, discovered via the `"arena_boundary"` group — enabling wall-rides and ceiling shots with no collision-shape changes.
- **Camera** (`scenes/ship_camera_rig.tscn`, `scripts/ship_camera.gd`, group `"ship_camera"`) is spawned by the game mode and given a `target` ship — ships have no camera/HUD dependency, so headless runs work.
- **HUD / telemetry pattern**: `Ship` emits flight data via signals only when values change past thresholds (`_last_*` fields, `*_THRESHOLD` constants). `HUDController` (`scripts/HUDController.gd`) discovers the camera rig and game mode via groups (`"ship_camera"`, `"game"`) but receives its target ship directly from the game mode via `GameMode.spawn_camera_rig`, connects to signals, and only updates labels — no polling. Follow this discovery-by-group + signal-push pattern for new instruments, not hardcoded `get_node` paths or per-frame polling. **`HUDController` duck-types on optional signals** (`timer_updated`, `match_ended`, `kickoff_countdown`, …) and hides the corresponding widget when a mode lacks one — so declaring a signal you never emit is worse than not declaring it (it shows a permanently frozen timer instead of hiding it).
- **`SimConstants.TICK_HZ`** is the single source of truth for the 60 Hz tick — every derived timing constant reads it rather than restating `60`. It is *not* wired to `project.godot`'s `physics/common/physics_ticks_per_second` (an engine setting), so those must be kept in sync by hand.
- **Input actions** are defined in `Game/project.godot` under `[input]` (`move_forward`, `turbo`, `reset_ball`, `toggle_perf_overlay` F3, `toggle_net_overlay` F4, …) and read only by `PlayerShipController` plus mode-level `_unhandled_input` — add new controls there rather than hardcoding key checks.
- Physics engine is Jolt (`[physics] 3d/physics_engine="Jolt Physics"`).
### `project.godot` hazard
Godot's `ConfigFile` writer does not round-trip comments, and a `#` block directly above a setting can be spliced into that setting's own line on rewrite, silently commenting it out. **Do not add comments to `Game/project.godot`.** This matters most for the feature overrides `run/main_scene.training` and `run/main_scene.dedicated_server`, which are how the training and server exports reach the right scene without a CLI flag; `tests/cases/test_project_settings.gd` fails loudly if they ever break.
### Networking (server-authoritative, with client prediction)
All hot-path RPCs live on **autoloads**, never scene nodes, so RPC NodePaths never depend on which scene is loaded. The autoload chain, in `project.godot` order:
- **`NetSim`** (`net_sim.gd`) — debug-only seeded latency/jitter/loss/duplicate decorator around outgoing dispatch. A pure passthrough unless `--net-sim-latency=` / `--net-sim-jitter=` / `--net-sim-loss=` / `--net-sim-dup=` / `--net-sim-seed=` are passed, so its mere existence changes nothing. Each process reads only its own flags, which is what makes asymmetric (e.g. lossy-upload-only) testing free.
- **`NetworkManager`** (`network_manager.gd`) — transport-neutral host/join/shutdown and connection signals. Sets `server_relay = false` the moment a peer exists (the default `true` would let any client RPC any other client through the server). Runs **manual multiplayer polling** (`set_multiplayer_poll_enabled(false)`), because SceneTree's automatic poll runs on the idle frame and would cost a frame in each direction for RPCs issued from `_physics_process` — anything driving a connection must call `NetworkManager.poll()` itself or nothing is ever sent or received.
- **`MatchNet`** (`match_net.gd`) — hello/welcome handshake, strict `protocol_version` and tick-rate gating, and the roster (name, team, ready) that survives the lobby→match transition. Slot assignment is *not* stored here; it's derived at spawn time.
- **`MatchSim`** (`match_sim.gd`) — the Phase 2+ simulation RPCs: `match_config`, `input` (client→server), `snapshot` (server→client), score/state/kickoff/goal/clock messages. Also owns protocol-level input validation (leaky-bucket packet and byte rate limits), because framing abuse is independent of any particular match's state. Emits `input_rejected` with the verbatim bytes so the replay log can explain "my input did nothing".
- **`NetDebugOverlay`** (F4) and **`PerfOverlay`** (F3) — headless-guarded read-only overlays.
Supporting modules, deliberately standalone (`RefCounted`/`class_name`, no scene or RPC dependency) so they unit-test head-on:
- `net_codec.gd`**the wire format**. `PROTOCOL_VERSION`, channel intents, quantisers, pack/unpack for the input and snapshot packets. Any change here is a protocol change.
- `match_state.gd` — the match lifecycle enum and its legal-transition table. **The integer values are the wire format** (`match_state` is a u8 in the snapshot header): never renumber an existing state, only append.
- `net_body_state.gd`, `net_interpolator.gd`, `net_ship_predictor.gd`, `local_prediction_history.gd`, `local_input_timeline.gd`, `input_jitter_buffer.gd`, `input_lead_controller.gd`, `adaptive_input_depth_controller.gd`, `ship_action_codec.gd`, `replay_log.gd`, `server_config.gd`, `server_log.gd` — each has a header comment explaining its role and the task it came from.
`networked_match.gd` (`NetworkedMatch extends GameMode`, ~2.4k lines) is where it all meets: the server simulates every slot and broadcasts 60 Hz snapshots; a client simulates **only its own unfrozen slot** with one real controller while every remote slot and the ball stay frozen and interpolated. Its scene has no Arena or HUD child — both are built in code once the arena is actually known (the server picks it, the client learns it from `match_config`), which is why it overrides `_ready()` entirely rather than using `GameMode`'s arena-required-synchronously flow.
Server process: `scenes/server_boot.tscn` (`server_boot.gd`) is the shell — strict CLI parsing via `ServerConfig` (unknown flag or bad value refuses to start), structured logging via `ServerLog`, physics-overrun watchdog. `ServerMatchLoop` (`server_match_loop.gd`) is the actual match loop: wait for `--min-players` **by roster, not raw peers**, count down, load the next arena from the rotation, run the match, return to the lobby, repeat or drain at `--max-matches`. It parents itself to the scene-tree **root**, never `current_scene`, because `change_scene_to_file` frees the live scene and an orchestrator freed by its own transition can't orchestrate the next one.
Known-insecure, and the reason public hosting is gated: **slot reclaim is keyed by display name**, so anyone who knows a disconnected player's name can take their reserved slot. Verified Steam identity (Phase 7) is the fix. Don't expose a server to strangers before then.
### Matchmaking control plane (`server/`, Go)
The only component outside the Godot project, and roughly a third of the
codebase. Layered so policy is testable without a database and persistence
without a network:
- `domain/` (~3.2k lines) — **pure policy, no I/O**: matcher formation and
rating tolerance, Glicko ratings and tiers, proposal/queue/match state
machines, casual lineup and backfill selection, probe validation, join
authorisations. Most behaviour worth asserting lives here and needs no
fixture. `ranked.go`'s arena list is checked against `arena_registry.gd` (see
Arena registry above).
- `store/` (~5.3k) — PostgreSQL boundaries. Every mutation goes through
`RunSerializable`; contention is expected rather than exceptional, so the
retry budget and jittered backoff there are load-bearing, not decoration.
- `api/` (~2.5k) — HTTP surface and the outbox dispatchers. `Service` is a
struct of optional providers, each nil-guarded into a 503, which is why a
binary can look healthy while a whole feature is unreachable — check what
`cmd/*/main.go` actually assigns before concluding a feature is broken.
- `allocator/`, `supervisor/`, `agones/` — allocation, the Go process that
wraps the exported Godot server in an Agones pod, and the Agones client.
- `matcher/`, `workload/`, `observability/`, `steam/`, `testkit/` — the matcher
worker loop, workload-token signing, metrics, the Steam Web API adapter, and
deterministic offline fakes.
`cmd/` holds seven binaries: `control-plane`, `matcher`, `allocator`,
`maintenance`, `game-server-supervisor`, `migrate`, and `testkit-api`.
**`testkit-api` is test-only** — it injects a fake Steam login that accepts any
ticket, and must never be deployed in place of `control-plane`.
Three things that are easy to get wrong:
- **Integration tests are behind `//go:build integration`** and need a real
PostgreSQL/Redis, so `go test ./...` silently skips them. Run them through
`scripts/run_*_integration.sh`, which start their own disposable containers.
`go vet -tags integration ./...` is worth running too, or those files rot
uncompiled.
- **Config is start-time.** Tier bands, the join-signing key set, Steam
credentials and the probe providers are all read once in `main()`. Changing
them is a rolling restart, not a hot reload — deliberate, and consistent with
how everything else in these binaries is supplied.
- **The wire contract is versioned.** `contracts/v1/openapi.json` and
`state-transitions.json` are asserted by `contracts/v1/test_contracts.py`;
changing a status code or operation ID without updating them breaks generated
clients silently.
### Steam transport
`net_transport.gd` (`NetTransport`) is a deliberately narrow boundary: a transport only *creates a peer*; `NetworkManager` keeps ownership of polling, RPC policy and lifecycle. `enet_transport.gd` and `steam_transport.gd` implement it. `NetworkManager.host()/join()` default to `"enet"`; passing `"steam"` **never falls back** — a missing custom build or failed init returns an error naming the missing prerequisite (`steam_bootstrap.gd` produces those messages). Discovery and server advertisement are intentionally unimplemented until a project-owned App ID exists; the local default is Valve's Spacewar App ID 480, which must never be used to advertise servers or ship.
## Reinforcement learning / AI bots
See `TRAINING.md` for the full workflow (training, exporting, evaluating, difficulty tiers). Architecture summary:
See `TRAINING.md` for the full workflow. Architecture summary:
- `scenes/training.tscn` (`scripts/training_mode.gd`, extends `GameMode`) is the headless self-play environment: two ships driven by `RLShipController`s, with `ShipAIController` (extends the vendored plugin's `AIController3D`) as the only class touching godot_rl types. The plugin is vendored (not a submodule) at `Game/addons/godot_rl_agents` — see its `VENDORED.md`; its C#/ONNX files are unused.
- `scripts/ship_observations.gd` is the shared observation builder used by both training and in-game inference — never fork or diverge these two paths. Team 1's observations are mirrored (180° about Y) so one policy plays both sides.
- In-game bots: `scripts/ai_ship_controller.gd` (a `ShipController`) runs the exported policy JSON via `scripts/policy_network.gd` (pure-GDScript MLP) — no .NET/ONNX/Python at runtime. Models live in `Game/bots/`; Match mode's `bot_model_path`/`bot_reaction_ticks`/`bot_action_noise` exports configure the opponent.
- Python side lives in `training/` (venv, not committed): `train.py` (SB3 PPO, launches parallel headless Godot instances from source), `export_policy.py` (checkpoint → JSON with parity check), `evaluate.py` (head-to-head eval, appends `training/eval_history.json`).
- `scenes/training.tscn` / `training_elevated.tscn` (`scripts/training_mode.gd`, extends `GameMode`) is the headless self-play environment: two ships driven by `RLShipController`s, with `ShipAIController` (extends the vendored plugin's `AIController3D`) as the only class touching godot_rl types. The plugin is vendored (not a submodule) at `Game/addons/godot_rl_agents` — see its `VENDORED.md`; its C#/ONNX files are unused.
- `scripts/ship_observations.gd` is the shared observation builder used by training, in-game inference, **and** the server — never fork or diverge these paths. Team 1's observations are mirrored (180° about Y) so one policy plays both sides.
- In-game bots: `scripts/ai_ship_controller.gd` (a `ShipController`) runs the exported policy JSON via `scripts/policy_network.gd` (pure-GDScript MLP) — no .NET/ONNX/Python at runtime. Models live in `Game/bots/` (promoted tiers in `Game/bots/promoted/`); Match mode's `bot_model_path`/`bot_reaction_ticks`/`bot_action_noise` exports configure the opponent, with the main menu's `GameSettings` autoload selections overriding them.
- Python side lives in `training/` (venv, not committed): `train.py` (SB3 PPO, launches parallel headless Godot instances from source), `export_policy.py` (checkpoint → JSON with parity check), `evaluate.py` (head-to-head eval, appends `training/eval_history.json`), plus the curriculum drivers (`curriculum.py`, `generation5.py`) and their JSON state files.
- The flattened action space is Box(7) in gymnasium's **sorted-key order**: rotation xyz, thrust xyz, turbo (>0 = on). The fields are `ShipAction`'s, but gymnasium alphabetizes Dict spaces, so the flat order is NOT ShipAction's thrust-first declaration order — `AIShipController._decide` consumes exported policies in sorted order; change the action space only deliberately and everywhere together.
+118
View File
@@ -0,0 +1,118 @@
# Local-only dedicated-server build and verification image. Pin the Godot
# release family used by project.godot; no image is pushed by this repository.
# barichello/godot-ci:4.7.1 (linux/amd64), resolved 2026-08-29.
FROM --platform=linux/amd64 barichello/godot-ci@sha256:622e5ca81b54cd8038ecf7de5d157b47efc800d7cf635af2eec18a6aee4bab7e AS project-imported
WORKDIR /workspace
# The pinned headless Godot image already runs imports without fontconfig.
# Do not refresh its old Ubuntu archive here: its historical keyring rejects
# current Noble signatures, while this source-only import stage needs no OS
# packages at all.
COPY Game /workspace/Game
# `--import` starts the editor, waits for resource import to finish, then
# exits. Do not combine it with `--quit`, which ends the editor after one
# iteration and can interrupt generation of `.godot/imported` resources.
RUN godot --headless --path Game --import \
&& test -f Game/.godot/imported/nebula_station.glb-fa9a6dd87ae3789d04205b52215e2e76.scn \
&& test -f Game/.godot/imported/nebula_debris.glb-39af77a17c0998b5b73172577d906cb9.scn \
&& test -f Game/.godot/imported/nebula_planet.glb-2431590907ff85cf1057e7d6ad614ed7.scn
# Test the source client from an untouched, fully imported project. The
# dedicated-server export below rewrites the main scene and must not be used
# to run client integration tests.
FROM project-imported AS enet-test
COPY scripts/verify_enet_integration.sh /workspace/scripts/verify_enet_integration.sh
# Godot dedicated exports disallow command-line scene overrides. Bake the
# server scene into this export (the interactive project's source stays
# unchanged), then generate the global-script/autoload metadata it needs.
FROM project-imported AS exporter
RUN sed -i 's|^run/main_scene=.*$|run/main_scene="res://scenes/server_boot.tscn"|' Game/project.godot \
&& mkdir -p /opt/cosmic-clash \
&& godot --headless --path Game --export-release "Linux Dedicated Server" /opt/cosmic-clash/CosmicClashServer.x86_64
# ubuntu:noble linux/amd64 manifest, resolved 2026-09-03. The prior pin
# carried an obsolete archive keyring and rejected current Noble signatures
# during apt-get update. This remains a digest pin; package verification is
# deliberately not bypassed.
FROM --platform=linux/amd64 ubuntu@sha256:1e0a86e57d247923571b75e0aaf48a1449cf8c543d51fb3e07a4a7d7bfa79316 AS server
RUN apt-get update && apt-get install -y --no-install-recommends libfontconfig1 libgl1 libstdc++6 && rm -rf /var/lib/apt/lists/*
COPY --from=exporter /opt/cosmic-clash/ /opt/cosmic-clash/
COPY deploy/cosmic-clash-server /opt/cosmic-clash/cosmic-clash-server
RUN chmod 0755 /opt/cosmic-clash/cosmic-clash-server
WORKDIR /opt/cosmic-clash
EXPOSE 7777/udp
ENTRYPOINT ["/opt/cosmic-clash/cosmic-clash-server"]
# Test-only target: runs the source client harness against the exported server.
FROM exporter AS smoke-client
WORKDIR /workspace
ENTRYPOINT ["godot", "--headless", "--path", "Game", "res://tests/export_server_smoke.tscn", "--"]
# Builds the process supervisor (server/supervisor, multiplayer-next.md task
# 8.27/8.28) that wraps the Agones-allocated dedicated server as PID 1.
# golang:1.23-alpine (matches server/go.mod's `go 1.23`), resolved 2026-09-01.
FROM --platform=linux/amd64 golang@sha256:383395b794dffa5b53012a212365d40c8e37109a626ca30d6151c8348d380b5f AS supervisor-build
WORKDIR /workspace/server
COPY server/go.mod server/go.sum ./
RUN go mod download
COPY server/ ./
RUN CGO_ENABLED=0 go build -o /opt/cosmic-clash/game-server-supervisor ./cmd/game-server-supervisor
RUN CGO_ENABLED=0 go build -o /opt/cosmic-clash/control-plane ./cmd/control-plane
RUN CGO_ENABLED=0 go build -o /opt/cosmic-clash/testkit-api ./cmd/testkit-api
RUN CGO_ENABLED=0 go build -o /opt/cosmic-clash/matcher ./cmd/matcher
RUN CGO_ENABLED=0 go build -o /opt/cosmic-clash/allocator ./cmd/allocator
RUN CGO_ENABLED=0 go build -o /opt/cosmic-clash/maintenance ./cmd/maintenance
# Agones-allocated fleet image: the same dedicated-server export as `server`
# (unchanged above; make verify-phase6 exercises that target exactly as
# before), wrapped by the Go supervisor as PID 1 instead of the direct
# launcher script -- required for process-ready/assignment-ready Agones SDK
# calls and control-plane registration (multiplayer-next.md §8.27/§8.28).
# deploy/k8s/base/fleet.yaml invokes this target with the deployment-specific
# supervisor flags and mounts the roster/signing material required by the
# allocated startup path. Workload credentials are delivered through the
# Agones allocation annotation; a projected token volume is not required.
FROM server AS game-server
COPY --from=supervisor-build /opt/cosmic-clash/game-server-supervisor /opt/cosmic-clash/game-server-supervisor
RUN chmod 0755 /opt/cosmic-clash/game-server-supervisor
ENTRYPOINT ["/opt/cosmic-clash/game-server-supervisor"]
# The production control-plane API. deploy/k8s/base/control-plane-deployment.yaml
# has always referenced this image, but nothing built it: cmd/control-plane was
# absent from the Go build stage and no target existed, so the checked-in
# Kubernetes base could not produce its own advertised topology.
#
# This must never be substituted with the testkit-api target below, which
# injects a fake login provider that accepts any ticket string.
FROM server AS control-plane
COPY --from=supervisor-build /opt/cosmic-clash/control-plane /opt/cosmic-clash/control-plane
COPY server/migrations /opt/cosmic-clash/migrations
RUN chmod 0755 /opt/cosmic-clash/control-plane
EXPOSE 8080
ENTRYPOINT ["/opt/cosmic-clash/control-plane"]
# TEST ONLY. Supplies a fake Steam login that accepts any ticket; never deploy
# this in place of the control-plane target above.
FROM server AS testkit-api
COPY --from=supervisor-build /opt/cosmic-clash/testkit-api /opt/cosmic-clash/testkit-api
COPY server/migrations /opt/cosmic-clash/migrations
RUN chmod 0755 /opt/cosmic-clash/testkit-api
ENTRYPOINT ["/opt/cosmic-clash/testkit-api"]
FROM server AS matcher
COPY --from=supervisor-build /opt/cosmic-clash/matcher /opt/cosmic-clash/matcher
COPY server/migrations /opt/cosmic-clash/migrations
RUN chmod 0755 /opt/cosmic-clash/matcher
ENTRYPOINT ["/opt/cosmic-clash/matcher"]
FROM server AS allocator
COPY --from=supervisor-build /opt/cosmic-clash/allocator /opt/cosmic-clash/allocator
COPY server/migrations /opt/cosmic-clash/migrations
RUN chmod 0755 /opt/cosmic-clash/allocator
ENTRYPOINT ["/opt/cosmic-clash/allocator"]
FROM server AS maintenance
COPY --from=supervisor-build /opt/cosmic-clash/maintenance /opt/cosmic-clash/maintenance
COPY server/migrations /opt/cosmic-clash/migrations
RUN chmod 0755 /opt/cosmic-clash/maintenance
ENTRYPOINT ["/opt/cosmic-clash/maintenance"]
+52 -12
View File
@@ -27,18 +27,58 @@ Welcome to space, pilot! This guide will teach you everything you need to know a
### Controller Controls
#### Translation
Button names are the Xbox layout; a PlayStation pad maps the same physical
positions (A = ✕, B = ○, X = □, Y = △).
- Left Stick - Strafe (Left/Right) + Thrust (Forward/Back)
- Right Trigger - Forward Thrust
- Left Trigger - Reverse Thrust
- Face Buttons - Up/Down Thrust
**The left stick points the nose, the right stick moves the hull.** Your ship has
six degrees of freedom and a pad has exactly six analog axes, so every one gets a
real axis rather than an on/off button.
#### Rotation
#### Rotation — left stick and shoulders
- Right Stick - Pitch/Yaw
- Shoulder Buttons - Roll
- `A Button` - Turbo Boost
- Left Stick (left/right) - Yaw
- Left Stick (up/down) - Pitch. Flight-sim polarity by default: **push the
stick forward and the nose goes down.** Flip it with "Invert pitch" in
Settings → Controls.
- `LB` - Roll Left (Bank Left)
- `RB` - Roll Right (Bank Right)
#### Translation — right stick and triggers
- `RT` - Forward Thrust (Main Engines)
- `LT` - Reverse Thrust (Retro Engines)
- Right Stick (left/right) - Strafe (Port/Starboard Thrusters)
- Right Stick (up/down) - Thrust Up/Down (Dorsal/Ventral Thrusters)
- `L3` (click the left stick) - Turbo Boost
`X` and `Y` are deliberately unused in flight, and `A`/`B` are menu-only, so a
reflexive face-button press never does anything mid-match.
#### Menus
- D-Pad or Left Stick - move the highlight
- `A` - select
- `B` - back
- `Start` - leave a match in progress (deliberately not `B`, which is too easy
to press by accident mid-game)
#### Other
- `R3` (click the right stick) - Toggle ball camera
- `D-Pad Up` - Reset the ball (Free Play only)
The triggers and sticks are **analog**: a half-pulled trigger gives half thrust,
and a gentle stick lean gives a gentle turn. Keyboard keys are all-or-nothing,
which is the main reason a pad is easier to fly precisely.
### Rebinding
Every control above — keyboard and controller alike — can be remapped in
**Settings → Controls**. Pick the device with the Keyboard/Controller toggle,
click the binding you want to change, and press the key or button to assign.
Binding an input that is already in use unbinds it from the action that had it,
and the screen tells you which. "Reset all bindings to defaults" restores this
table.
## 🛸 Basic Flight Principles
@@ -69,7 +109,7 @@ Your ship is a **realistic space vehicle** with the following characteristics:
#### Camera Control
- **Ball Cam**: Press `Enter` to toggle ball tracking camera
- **Ball Cam**: Press `Space` (or `R3` on a controller) to toggle ball tracking camera
- **Ship Cam**: Normal follow camera that looks where your ship points
### Intermediate Maneuvers
@@ -115,7 +155,7 @@ Your ship is a **realistic space vehicle** with the following characteristics:
## 🎮 Ball Cam vs Ship Cam
### Ball Cam Mode (`Enter` to toggle)
### Ball Cam Mode (`Space` / `R3` to toggle)
- **Camera**: Always looks toward the ball
- **Ship Control**: Based on ship orientation (NOT camera view)
@@ -133,7 +173,7 @@ Your ship is a **realistic space vehicle** with the following characteristics:
### Turbo System
- **Activation**: Hold `Shift` (keyboard) or `A` (controller) while thrusting forward
- **Activation**: Hold `Shift` (keyboard) or `L3` (controller) while thrusting forward
- **Effect**: 2.5x thrust multiplier on main engines only
- **Strategy**: Use for quick acceleration or emergency maneuvers
+3
View File
@@ -0,0 +1,3 @@
# Blender authoring sources live here, but the game consumes the exported
# runtime assets under res://assets/models. Keep Godot's project scanner from
# requiring Blender when importing or testing in headless environments.
@@ -1,63 +0,0 @@
[remap]
importer="scene"
importer_version=1
type="PackedScene"
uid="uid://ckohaa5ebxym2"
path="res://.godot/imported/ball.blend-22aebbee9e0a3f479241b5a042aee325.scn"
[deps]
source_file="res://assets/blender_models/ball.blend"
dest_files=["res://.godot/imported/ball.blend-22aebbee9e0a3f479241b5a042aee325.scn"]
[params]
nodes/root_type=""
nodes/root_name=""
nodes/root_script=null
mesh_library/use_node_names_as_mesh_names=false
array_mesh/deduplicate_surfaces=true
nodes/apply_root_scale=true
nodes/root_scale=1.0
nodes/import_as_skeleton_bones=false
nodes/use_name_suffixes=true
nodes/use_node_type_suffixes=true
meshes/ensure_tangents=true
meshes/generate_lods=true
meshes/create_shadow_meshes=true
meshes/light_baking=1
meshes/lightmap_texel_size=0.2
meshes/force_disable_compression=false
skins/use_named_skins=true
animation/import=true
animation/fps=30
animation/trimming=false
animation/remove_immutable_tracks=true
animation/import_rest_as_RESET=false
import_script/path=""
materials/extract=0
materials/extract_format=0
materials/extract_path=""
_subresources={}
blender/nodes/visible=0
blender/nodes/active_collection_only=false
blender/nodes/punctual_lights=true
blender/nodes/cameras=true
blender/nodes/custom_properties=true
blender/nodes/modifiers=1
blender/meshes/vertex_colors=1
blender/meshes/uvs=true
blender/meshes/normals=true
blender/meshes/export_geometry_nodes_instances=false
blender/meshes/gpu_instances=false
blender/meshes/tangents=true
blender/meshes/skins=2
blender/meshes/export_bones_deforming_mesh_only=false
blender/materials/unpack_enabled=true
blender/materials/export_materials=1
blender/animation/limit_playback=true
blender/animation/always_sample=true
blender/animation/group_tracks=true
gltf/naming_version=2
gltf/texture_map_mode=1
@@ -1,63 +0,0 @@
[remap]
importer="scene"
importer_version=1
type="PackedScene"
uid="uid://d2mrvrt1h305x"
path="res://.godot/imported/nebula_decoration.blend-2f6fe244eedad258eac5faa9b1684142.scn"
[deps]
source_file="res://assets/blender_models/nebula_decoration.blend"
dest_files=["res://.godot/imported/nebula_decoration.blend-2f6fe244eedad258eac5faa9b1684142.scn"]
[params]
nodes/root_type=""
nodes/root_name=""
nodes/root_script=null
mesh_library/use_node_names_as_mesh_names=false
array_mesh/deduplicate_surfaces=true
nodes/apply_root_scale=true
nodes/root_scale=1.0
nodes/import_as_skeleton_bones=false
nodes/use_name_suffixes=true
nodes/use_node_type_suffixes=true
meshes/ensure_tangents=true
meshes/generate_lods=true
meshes/create_shadow_meshes=true
meshes/light_baking=1
meshes/lightmap_texel_size=0.2
meshes/force_disable_compression=false
skins/use_named_skins=true
animation/import=true
animation/fps=30
animation/trimming=false
animation/remove_immutable_tracks=true
animation/import_rest_as_RESET=false
import_script/path=""
materials/extract=0
materials/extract_format=0
materials/extract_path=""
_subresources={}
blender/nodes/visible=0
blender/nodes/active_collection_only=false
blender/nodes/punctual_lights=true
blender/nodes/cameras=true
blender/nodes/custom_properties=true
blender/nodes/modifiers=1
blender/meshes/vertex_colors=1
blender/meshes/uvs=true
blender/meshes/normals=true
blender/meshes/export_geometry_nodes_instances=false
blender/meshes/gpu_instances=false
blender/meshes/tangents=true
blender/meshes/skins=2
blender/meshes/export_bones_deforming_mesh_only=false
blender/materials/unpack_enabled=true
blender/materials/export_materials=1
blender/animation/limit_playback=true
blender/animation/always_sample=true
blender/animation/group_tracks=true
gltf/naming_version=2
gltf/texture_map_mode=1
@@ -1,63 +0,0 @@
[remap]
importer="scene"
importer_version=1
type="PackedScene"
uid="uid://bp2eqsu8o3082"
path="res://.godot/imported/ship.blend-1bdca1ba6b72cf6be2f2eb32002cf7c8.scn"
[deps]
source_file="res://assets/blender_models/ship.blend"
dest_files=["res://.godot/imported/ship.blend-1bdca1ba6b72cf6be2f2eb32002cf7c8.scn"]
[params]
nodes/root_type=""
nodes/root_name=""
nodes/root_script=null
mesh_library/use_node_names_as_mesh_names=false
array_mesh/deduplicate_surfaces=true
nodes/apply_root_scale=true
nodes/root_scale=1.0
nodes/import_as_skeleton_bones=false
nodes/use_name_suffixes=true
nodes/use_node_type_suffixes=true
meshes/ensure_tangents=true
meshes/generate_lods=true
meshes/create_shadow_meshes=true
meshes/light_baking=1
meshes/lightmap_texel_size=0.2
meshes/force_disable_compression=false
skins/use_named_skins=true
animation/import=true
animation/fps=30
animation/trimming=false
animation/remove_immutable_tracks=true
animation/import_rest_as_RESET=false
import_script/path=""
materials/extract=0
materials/extract_format=0
materials/extract_path=""
_subresources={}
blender/nodes/visible=0
blender/nodes/active_collection_only=false
blender/nodes/punctual_lights=true
blender/nodes/cameras=true
blender/nodes/custom_properties=true
blender/nodes/modifiers=1
blender/meshes/vertex_colors=1
blender/meshes/uvs=true
blender/meshes/normals=true
blender/meshes/export_geometry_nodes_instances=false
blender/meshes/gpu_instances=false
blender/meshes/tangents=true
blender/meshes/skins=2
blender/meshes/export_bones_deforming_mesh_only=false
blender/materials/unpack_enabled=true
blender/materials/export_materials=1
blender/animation/limit_playback=true
blender/animation/always_sample=true
blender/animation/group_tracks=true
gltf/naming_version=2
gltf/texture_map_mode=1
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+87
View File
@@ -26,3 +26,90 @@ texture_format/s3tc=true
texture_format/etc=false
texture_format/etc2=false
binary_format/architecture="x86_64"
[preset.1]
name="Linux Dedicated Server"
platform="Linux"
runnable=true
dedicated_server=true
custom_features="dedicated_server"
export_filter="all_resources"
include_filter=""
exclude_filter=""
export_path="../server/build/CosmicClashServer.x86_64"
encryption_include_filters=""
encryption_exclude_filters=""
encrypt_pck=false
encrypt_directory=false
script_encryption_key=""
[preset.1.options]
custom_template/debug=""
custom_template/release=""
debug/export_console_script=1
binary_format/embed_pck=true
texture_format/bptc=false
texture_format/s3tc=false
texture_format/etc=false
texture_format/etc2=false
binary_format/architecture="x86_64"
[preset.2]
name="Linux Steam Client"
platform="Linux"
runnable=true
dedicated_server=false
custom_features="steam"
export_filter="all_resources"
include_filter=""
exclude_filter=""
export_path="../steam/build/CosmicClashSteam.x86_64"
encryption_include_filters=""
encryption_exclude_filters=""
encrypt_pck=false
encrypt_directory=false
script_encryption_key=""
[preset.2.options]
custom_template/debug=""
custom_template/release=""
debug/export_console_script=1
binary_format/embed_pck=true
texture_format/bptc=true
texture_format/s3tc=true
texture_format/etc=false
texture_format/etc2=false
binary_format/architecture="x86_64"
[preset.3]
name="Linux Steam Dedicated Server"
platform="Linux"
runnable=true
dedicated_server=true
custom_features="dedicated_server,steam"
export_filter="all_resources"
include_filter=""
exclude_filter=""
export_path="../steam/build/CosmicClashSteamServer.x86_64"
encryption_include_filters=""
encryption_exclude_filters=""
encrypt_pck=false
encrypt_directory=false
script_encryption_key=""
[preset.3.options]
custom_template/debug=""
custom_template/release=""
debug/export_console_script=1
binary_format/embed_pck=true
texture_format/bptc=false
texture_format/s3tc=false
texture_format/etc=false
texture_format/etc2=false
binary_format/architecture="x86_64"
+4 -1
View File
@@ -15,6 +15,7 @@ collision_mask = 13
mass = 3
physics_material_override = SubResource("PhysicsMaterial_ball")
continuous_cd = true
can_sleep = false
inertia = Vector3(3, 3, 3)
gravity_scale = 0.8
linear_damp = 0.1
@@ -25,6 +26,8 @@ metadata/_edit_group_ = true
[node name="CollisionShape3D" type="CollisionShape3D" parent="."]
shape = SubResource("SphereShape3D_c5p07")
[node name="MeshInstance3D" type="MeshInstance3D" parent="."]
[node name="Visual" type="Node3D" parent="."]
[node name="MeshInstance3D" type="MeshInstance3D" parent="Visual"]
transform = Transform3D(0.5, 0, 0, 0, 0.5, 0, 0, 0, 0.5, 0, 0, 0)
mesh = ExtResource("1_ball")
+6 -2
View File
@@ -17,13 +17,17 @@ collision_mask = 7
mass = 5.0
physics_material_override = SubResource("PhysicsMaterial_ship")
inertia = Vector3(7, 1, 7)
can_sleep = false
continuous_cd = true
script = ExtResource("1_efag7")
[node name="Nose" type="MeshInstance3D" parent="."]
[node name="Visual" type="Node3D" parent="."]
[node name="Nose" type="MeshInstance3D" parent="Visual"]
transform = Transform3D(-1, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0, 0)
mesh = ExtResource("3_nose")
[node name="TailFin" type="MeshInstance3D" parent="."]
[node name="TailFin" type="MeshInstance3D" parent="Visual"]
transform = Transform3D(-1, 0, 0, 0, 1, 0, 0, 0, -1, 0, 0.24, 0.72)
mesh = ExtResource("5_talfin")
+63 -4
View File
@@ -21,11 +21,22 @@ run/main_scene="uid://bcq14356s3e2i"
config/features=PackedStringArray("4.7", "Forward Plus")
config/icon="res://icon.svg"
run/main_scene.training="res://scenes/training.tscn"
run/main_scene.dedicated_server="res://scenes/server_boot.tscn"
[autoload]
GameSettings="*res://scripts/game_settings.gd"
ControlPlaneClient="*res://scripts/control_plane_client.gd"
VideoSettings="*res://scripts/video_settings.gd"
InputSettings="*res://scripts/input_settings.gd"
BackgroundFPS="*res://scripts/background_fps.gd"
PerfOverlay="*res://scripts/perf_overlay.gd"
NetSim="*res://scripts/net_sim.gd"
NetworkManager="*res://scripts/network_manager.gd"
MatchNet="*res://scripts/match_net.gd"
MatchSim="*res://scripts/match_sim.gd"
NetDebugOverlay="*res://scripts/net_debug_overlay.gd"
AudioManager="*res://scripts/audio_manager.gd"
[display]
@@ -34,6 +45,7 @@ window/size/viewport_height=1080
window/size/mode=2
window/stretch/mode="viewport"
window/stretch/aspect="expand"
window/vsync/vsync_mode=2
[editor_plugins]
@@ -44,42 +56,49 @@ enabled=PackedStringArray("res://addons/godot_rl_agents/plugin.cfg")
reset_ball={
"deadzone": 0.5,
"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":82,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
, Object(InputEventJoypadButton,"resource_local_to_scene":false,"resource_name":"","device":-1,"button_index":11,"pressure":0.0,"pressed":false,"script":null)
]
}
move_forward={
"deadzone": 0.2,
"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":87,"key_label":0,"unicode":119,"location":0,"echo":false,"script":null)
, Object(InputEventJoypadMotion,"resource_local_to_scene":false,"resource_name":"","device":-1,"axis":5,"axis_value":1.0,"script":null)
]
}
move_back={
"deadzone": 0.2,
"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":83,"key_label":0,"unicode":115,"location":0,"echo":false,"script":null)
, Object(InputEventJoypadMotion,"resource_local_to_scene":false,"resource_name":"","device":-1,"axis":4,"axis_value":1.0,"script":null)
]
}
move_left={
"deadzone": 0.2,
"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":65,"key_label":0,"unicode":97,"location":0,"echo":false,"script":null)
, Object(InputEventJoypadMotion,"resource_local_to_scene":false,"resource_name":"","device":-1,"axis":2,"axis_value":-1.0,"script":null)
]
}
move_right={
"deadzone": 0.2,
"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":68,"key_label":0,"unicode":100,"location":0,"echo":false,"script":null)
, Object(InputEventJoypadMotion,"resource_local_to_scene":false,"resource_name":"","device":-1,"axis":2,"axis_value":1.0,"script":null)
]
}
move_up={
"deadzone": 0.2,
"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":69,"key_label":0,"unicode":101,"location":0,"echo":false,"script":null)
, Object(InputEventJoypadMotion,"resource_local_to_scene":false,"resource_name":"","device":-1,"axis":3,"axis_value":-1.0,"script":null)
]
}
move_down={
"deadzone": 0.2,
"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":81,"key_label":0,"unicode":113,"location":0,"echo":false,"script":null)
, Object(InputEventJoypadMotion,"resource_local_to_scene":false,"resource_name":"","device":-1,"axis":3,"axis_value":1.0,"script":null)
]
}
turbo={
"deadzone": 0.2,
"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":4194325,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
, Object(InputEventJoypadButton,"resource_local_to_scene":false,"resource_name":"","device":-1,"button_index":0,"pressure":0.0,"pressed":false,"script":null)
, Object(InputEventJoypadButton,"resource_local_to_scene":false,"resource_name":"","device":-1,"button_index":7,"pressure":0.0,"pressed":false,"script":null)
]
}
turn_left={
@@ -97,13 +116,13 @@ turn_right={
pitch_up={
"deadzone": 0.2,
"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":73,"key_label":0,"unicode":105,"location":0,"echo":false,"script":null)
, Object(InputEventJoypadMotion,"resource_local_to_scene":false,"resource_name":"","device":-1,"axis":1,"axis_value":-1.0,"script":null)
, Object(InputEventJoypadMotion,"resource_local_to_scene":false,"resource_name":"","device":-1,"axis":1,"axis_value":1.0,"script":null)
]
}
pitch_down={
"deadzone": 0.2,
"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":75,"key_label":0,"unicode":107,"location":0,"echo":false,"script":null)
, Object(InputEventJoypadMotion,"resource_local_to_scene":false,"resource_name":"","device":-1,"axis":1,"axis_value":1.0,"script":null)
, Object(InputEventJoypadMotion,"resource_local_to_scene":false,"resource_name":"","device":-1,"axis":1,"axis_value":-1.0,"script":null)
]
}
roll_left={
@@ -118,6 +137,42 @@ roll_right={
, Object(InputEventJoypadButton,"resource_local_to_scene":false,"resource_name":"","device":-1,"button_index":10,"pressure":0.0,"pressed":false,"script":null)
]
}
toggle_ball_cam={
"deadzone": 0.5,
"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":32,"key_label":0,"unicode":32,"location":0,"echo":false,"script":null)
, Object(InputEventJoypadButton,"resource_local_to_scene":false,"resource_name":"","device":-1,"button_index":8,"pressure":0.0,"pressed":false,"script":null)
]
}
ui_cancel={
"deadzone": 0.5,
"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":4194305,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
, Object(InputEventJoypadButton,"resource_local_to_scene":false,"resource_name":"","device":-1,"button_index":1,"pressure":0.0,"pressed":false,"script":null)
, Object(InputEventJoypadButton,"resource_local_to_scene":false,"resource_name":"","device":-1,"button_index":6,"pressure":0.0,"pressed":false,"script":null)
]
}
ui_accept={
"deadzone": 0.5,
"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":4194309,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
, Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":4194310,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
, Object(InputEventJoypadButton,"resource_local_to_scene":false,"resource_name":"","device":-1,"button_index":0,"pressure":0.0,"pressed":false,"script":null)
]
}
leave_gameplay={
"deadzone": 0.5,
"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":4194305,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
, Object(InputEventJoypadButton,"resource_local_to_scene":false,"resource_name":"","device":-1,"button_index":6,"pressure":0.0,"pressed":false,"script":null)
]
}
toggle_perf_overlay={
"deadzone": 0.5,
"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":4194334,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
]
}
toggle_net_overlay={
"deadzone": 0.5,
"events": [Object(InputEventKey,"resource_local_to_scene":false,"resource_name":"","device":-1,"window_id":0,"alt_pressed":false,"shift_pressed":false,"ctrl_pressed":false,"meta_pressed":false,"pressed":false,"keycode":0,"physical_keycode":4194335,"key_label":0,"unicode":0,"location":0,"echo":false,"script":null)
]
}
[layer_names]
@@ -128,11 +183,15 @@ roll_right={
[physics]
common/physics_jitter_fix=0.0
3d/physics_engine="Jolt Physics"
common/physics_interpolation=true
[rendering]
lights_and_shadows/directional_shadow/size=2048
anti_aliasing/quality/msaa_3d=2
anti_aliasing/quality/screen_space_aa=1
anti_aliasing/quality/use_debanding=true
anti_aliasing/quality/screen_space_aa=1
lights_and_shadows/positional_shadow/atlas_size=2048
lights_and_shadows/soft_shadow_filter_quality=2
+128
View File
@@ -0,0 +1,128 @@
[gd_scene load_steps=3 format=3]
[ext_resource type="Script" path="res://scripts/lobby.gd" id="1_lobby"]
[ext_resource type="Theme" path="res://themes/cosmic_clash_theme.tres" id="2_theme"]
[node name="Lobby" type="Control"]
layout_mode = 3
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
script = ExtResource("1_lobby")
theme = ExtResource("2_theme")
[node name="MarginContainer" type="MarginContainer" parent="."]
layout_mode = 1
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
theme_override_constants/margin_left = 24
theme_override_constants/margin_top = 24
theme_override_constants/margin_right = 24
theme_override_constants/margin_bottom = 24
[node name="ScrollContainer" type="ScrollContainer" parent="MarginContainer"]
layout_mode = 2
follow_focus = true
horizontal_scroll_mode = 0
[node name="CenterContainer" type="CenterContainer" parent="MarginContainer/ScrollContainer"]
layout_mode = 2
size_flags_horizontal = 3
size_flags_vertical = 3
[node name="VBoxContainer" type="VBoxContainer" parent="MarginContainer/ScrollContainer/CenterContainer"]
custom_minimum_size = Vector2(520, 0)
layout_mode = 2
theme_override_constants/separation = 10
[node name="TitleLabel" type="Label" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer"]
layout_mode = 2
theme_override_font_sizes/font_size = 40
text = "Lobby"
horizontal_alignment = 1
[node name="StatusLabel" type="Label" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer"]
unique_name_in_owner = true
modulate = Color(1, 1, 1, 0.65)
layout_mode = 2
theme_override_font_sizes/font_size = 14
text = "Connecting..."
horizontal_alignment = 1
autowrap_mode = 2
[node name="TeamsSeparator" type="HSeparator" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer"]
layout_mode = 2
[node name="TeamsRow" type="HBoxContainer" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer"]
layout_mode = 2
theme_override_constants/separation = 20
[node name="Team0Panel" type="VBoxContainer" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/TeamsRow"]
layout_mode = 2
size_flags_horizontal = 3
theme_override_constants/separation = 4
[node name="Team0Header" type="Label" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/TeamsRow/Team0Panel"]
layout_mode = 2
theme_override_font_sizes/font_size = 18
text = "Team 1"
[node name="Team0List" type="VBoxContainer" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/TeamsRow/Team0Panel"]
unique_name_in_owner = true
layout_mode = 2
theme_override_constants/separation = 2
[node name="TeamsVSeparator" type="VSeparator" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/TeamsRow"]
layout_mode = 2
[node name="Team1Panel" type="VBoxContainer" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/TeamsRow"]
layout_mode = 2
size_flags_horizontal = 3
theme_override_constants/separation = 4
[node name="Team1Header" type="Label" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/TeamsRow/Team1Panel"]
layout_mode = 2
theme_override_font_sizes/font_size = 18
text = "Team 2"
[node name="Team1List" type="VBoxContainer" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/TeamsRow/Team1Panel"]
unique_name_in_owner = true
layout_mode = 2
theme_override_constants/separation = 2
[node name="ControlsSeparator" type="HSeparator" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer"]
layout_mode = 2
[node name="ControlsRow" type="HBoxContainer" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer"]
unique_name_in_owner = true
layout_mode = 2
theme_override_constants/separation = 10
[node name="SwitchTeamButton" type="Button" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/ControlsRow"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 48)
layout_mode = 2
size_flags_horizontal = 3
text = "Switch Team"
[node name="ReadyButton" type="CheckButton" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/ControlsRow"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 48)
layout_mode = 2
size_flags_horizontal = 3
text = "Ready"
[node name="LeaveButton" type="Button" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 48)
layout_mode = 2
text = "Leave"
[connection signal="pressed" from="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/ControlsRow/SwitchTeamButton" to="." method="_on_switch_team_pressed"]
[connection signal="toggled" from="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/ControlsRow/ReadyButton" to="." method="_on_ready_toggled"]
[connection signal="pressed" from="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/LeaveButton" to="." method="_on_leave_pressed"]
+278 -159
View File
@@ -1,6 +1,7 @@
[gd_scene load_steps=2 format=3 uid="uid://bcq14356s3e2i"]
[gd_scene load_steps=3 format=3 uid="uid://bcq14356s3e2i"]
[ext_resource type="Script" path="res://scripts/main_menu.gd" id="1_menu"]
[ext_resource type="Theme" path="res://themes/cosmic_clash_theme.tres" id="2_theme"]
[node name="MainMenu" type="Control"]
layout_mode = 3
@@ -10,8 +11,263 @@ anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
script = ExtResource("1_menu")
theme = ExtResource("2_theme")
[node name="CenterContainer" type="CenterContainer" parent="."]
[node name="MarginContainer" type="MarginContainer" parent="."]
layout_mode = 1
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
theme_override_constants/margin_left = 24
theme_override_constants/margin_top = 24
theme_override_constants/margin_right = 24
theme_override_constants/margin_bottom = 24
[node name="ScrollContainer" type="ScrollContainer" parent="MarginContainer"]
layout_mode = 2
follow_focus = true
horizontal_scroll_mode = 0
[node name="CenterContainer" type="CenterContainer" parent="MarginContainer/ScrollContainer"]
layout_mode = 2
size_flags_horizontal = 3
size_flags_vertical = 3
[node name="VBoxContainer" type="VBoxContainer" parent="MarginContainer/ScrollContainer/CenterContainer"]
custom_minimum_size = Vector2(420, 0)
layout_mode = 2
theme_override_constants/separation = 10
[node name="TitleLabel" type="Label" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer"]
layout_mode = 2
theme_override_font_sizes/font_size = 48
text = "Cosmic Clash"
horizontal_alignment = 1
[node name="SubtitleLabel" type="Label" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer"]
modulate = Color(1, 1, 1, 0.55)
layout_mode = 2
theme_override_font_sizes/font_size = 16
text = "Physics-based soccer in space"
horizontal_alignment = 1
[node name="TitleSpacer" type="Control" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer"]
custom_minimum_size = Vector2(0, 14)
layout_mode = 2
[node name="FreePlayButton" type="Button" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 56)
layout_mode = 2
text = "Free Play"
[node name="FreePlayHint" type="Label" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer"]
modulate = Color(1, 1, 1, 0.55)
layout_mode = 2
theme_override_font_sizes/font_size = 13
text = "Solo practice — no timer, R resets the ball"
horizontal_alignment = 1
[node name="ArenaRow" type="HBoxContainer" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer"]
layout_mode = 2
theme_override_constants/separation = 10
[node name="ArenaLabel" type="Label" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/ArenaRow"]
layout_mode = 2
text = "Arena"
[node name="ArenaDropdown" type="OptionButton" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/ArenaRow"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 40)
layout_mode = 2
size_flags_horizontal = 3
[node name="MatchSeparator" type="HSeparator" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer"]
layout_mode = 2
[node name="MatchHeader" type="Label" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer"]
layout_mode = 2
theme_override_font_sizes/font_size = 22
text = "Match"
[node name="MatchHint" type="Label" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer"]
modulate = Color(1, 1, 1, 0.55)
layout_mode = 2
theme_override_font_sizes/font_size = 13
text = "A 2:30 match — you vs a trained bot"
[node name="MatchRow" type="HBoxContainer" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer"]
layout_mode = 2
theme_override_constants/separation = 10
[node name="DifficultyLabel" type="Label" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/MatchRow"]
layout_mode = 2
text = "Difficulty"
[node name="DifficultyDropdown" type="OptionButton" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/MatchRow"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 40)
layout_mode = 2
size_flags_horizontal = 3
[node name="MatchButton" type="Button" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer"]
custom_minimum_size = Vector2(0, 56)
layout_mode = 2
text = "Play Match"
[node name="MultiplayerSeparator" type="HSeparator" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer"]
layout_mode = 2
[node name="MultiplayerHeader" type="Label" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer"]
layout_mode = 2
theme_override_font_sizes/font_size = 22
text = "Multiplayer"
[node name="MultiplayerHint" type="Label" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer"]
modulate = Color(1, 1, 1, 0.55)
layout_mode = 2
theme_override_font_sizes/font_size = 13
text = "LAN / direct IP — host a match or join one"
[node name="FindMatchButton" type="Button" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer"]
custom_minimum_size = Vector2(0, 48)
layout_mode = 2
text = "Find Match"
[node name="HostButton" type="Button" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer"]
custom_minimum_size = Vector2(0, 48)
layout_mode = 2
text = "Host"
[node name="JoinRow" type="HBoxContainer" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer"]
layout_mode = 2
theme_override_constants/separation = 10
[node name="JoinAddressEdit" type="LineEdit" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/JoinRow"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 40)
layout_mode = 2
size_flags_horizontal = 3
text = "127.0.0.1"
placeholder_text = "IP address"
[node name="JoinButton" type="Button" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/JoinRow"]
custom_minimum_size = Vector2(96, 40)
layout_mode = 2
text = "Join"
[node name="MultiplayerErrorLabel" type="Label" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer"]
unique_name_in_owner = true
modulate = Color(1, 0.5, 0.5, 1)
layout_mode = 2
theme_override_font_sizes/font_size = 13
text = ""
autowrap_mode = 2
visible = false
[node name="SettingsSeparator" type="HSeparator" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer"]
layout_mode = 2
[node name="SettingsButton" type="Button" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer"]
custom_minimum_size = Vector2(0, 56)
layout_mode = 2
text = "Settings"
[node name="DevSection" type="VBoxContainer" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer"]
unique_name_in_owner = true
layout_mode = 2
theme_override_constants/separation = 10
[node name="DevSeparator" type="HSeparator" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/DevSection"]
layout_mode = 2
[node name="DevHeader" type="Label" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/DevSection"]
layout_mode = 2
theme_override_font_sizes/font_size = 22
text = "Developer"
[node name="DevHint" type="Label" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/DevSection"]
modulate = Color(1, 1, 1, 0.55)
layout_mode = 2
theme_override_font_sizes/font_size = 13
text = "Dev-only — hidden in release builds"
[node name="DevOpponentRow" type="HBoxContainer" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/DevSection"]
layout_mode = 2
theme_override_constants/separation = 10
[node name="DevOpponentLabel" type="Label" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/DevSection/DevOpponentRow"]
layout_mode = 2
text = "Opponent override"
[node name="DevBotDropdown" type="OptionButton" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/DevSection/DevOpponentRow"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 40)
layout_mode = 2
size_flags_horizontal = 3
[node name="SpectateSeparator" type="HSeparator" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/DevSection"]
layout_mode = 2
[node name="SpectateHeader" type="Label" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/DevSection"]
layout_mode = 2
theme_override_font_sizes/font_size = 22
text = "Spectate"
[node name="SpectateHint" type="Label" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/DevSection"]
modulate = Color(1, 1, 1, 0.55)
layout_mode = 2
theme_override_font_sizes/font_size = 13
text = "Watch two bots play each other"
[node name="SpectateRow" type="HBoxContainer" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/DevSection"]
layout_mode = 2
theme_override_constants/separation = 10
[node name="BotADropdown" type="OptionButton" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/DevSection/SpectateRow"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 40)
layout_mode = 2
size_flags_horizontal = 3
[node name="VsLabel" type="Label" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/DevSection/SpectateRow"]
layout_mode = 2
text = "vs"
[node name="BotBDropdown" type="OptionButton" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/DevSection/SpectateRow"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 40)
layout_mode = 2
size_flags_horizontal = 3
[node name="SpectateButton" type="Button" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/DevSection"]
custom_minimum_size = Vector2(0, 56)
layout_mode = 2
text = "Watch Match"
[node name="ConnectingOverlay" type="Control" parent="."]
unique_name_in_owner = true
visible = false
layout_mode = 1
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
mouse_filter = 1
[node name="Backdrop" type="ColorRect" parent="ConnectingOverlay"]
layout_mode = 1
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
color = Color(0, 0, 0, 0.7)
[node name="CenterContainer" type="CenterContainer" parent="ConnectingOverlay"]
layout_mode = 1
anchors_preset = 15
anchor_right = 1.0
@@ -19,168 +275,31 @@ anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
[node name="VBoxContainer" type="VBoxContainer" parent="CenterContainer"]
custom_minimum_size = Vector2(420, 0)
[node name="VBoxContainer" type="VBoxContainer" parent="ConnectingOverlay/CenterContainer"]
custom_minimum_size = Vector2(360, 0)
layout_mode = 2
theme_override_constants/separation = 10
theme_override_constants/separation = 14
[node name="TitleLabel" type="Label" parent="CenterContainer/VBoxContainer"]
[node name="ConnectingStatusLabel" type="Label" parent="ConnectingOverlay/CenterContainer/VBoxContainer"]
unique_name_in_owner = true
layout_mode = 2
theme_override_font_sizes/font_size = 48
text = "Cosmic Clash"
theme_override_font_sizes/font_size = 18
text = "Connecting..."
horizontal_alignment = 1
autowrap_mode = 2
[node name="SubtitleLabel" type="Label" parent="CenterContainer/VBoxContainer"]
modulate = Color(1, 1, 1, 0.55)
layout_mode = 2
theme_override_font_sizes/font_size = 16
text = "Physics-based soccer in space"
horizontal_alignment = 1
[node name="TitleSpacer" type="Control" parent="CenterContainer/VBoxContainer"]
custom_minimum_size = Vector2(0, 14)
layout_mode = 2
[node name="FreePlayButton" type="Button" parent="CenterContainer/VBoxContainer"]
custom_minimum_size = Vector2(0, 56)
layout_mode = 2
text = "Free Play"
[node name="FreePlayHint" type="Label" parent="CenterContainer/VBoxContainer"]
modulate = Color(1, 1, 1, 0.55)
layout_mode = 2
theme_override_font_sizes/font_size = 13
text = "Solo practice — no timer, R resets the ball"
horizontal_alignment = 1
[node name="ArenaRow" type="HBoxContainer" parent="CenterContainer/VBoxContainer"]
layout_mode = 2
theme_override_constants/separation = 10
[node name="ArenaLabel" type="Label" parent="CenterContainer/VBoxContainer/ArenaRow"]
layout_mode = 2
text = "Arena"
[node name="ArenaDropdown" type="OptionButton" parent="CenterContainer/VBoxContainer/ArenaRow"]
[node name="ConnectingCancelButton" type="Button" parent="ConnectingOverlay/CenterContainer/VBoxContainer"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 40)
custom_minimum_size = Vector2(0, 48)
layout_mode = 2
size_flags_horizontal = 3
text = "Cancel"
[node name="MatchSeparator" type="HSeparator" parent="CenterContainer/VBoxContainer"]
layout_mode = 2
[node name="MatchHeader" type="Label" parent="CenterContainer/VBoxContainer"]
layout_mode = 2
theme_override_font_sizes/font_size = 22
text = "Match"
[node name="MatchHint" type="Label" parent="CenterContainer/VBoxContainer"]
modulate = Color(1, 1, 1, 0.55)
layout_mode = 2
theme_override_font_sizes/font_size = 13
text = "A 2:30 match — you vs a trained bot"
[node name="MatchRow" type="HBoxContainer" parent="CenterContainer/VBoxContainer"]
layout_mode = 2
theme_override_constants/separation = 10
[node name="DifficultyLabel" type="Label" parent="CenterContainer/VBoxContainer/MatchRow"]
layout_mode = 2
text = "Difficulty"
[node name="DifficultyDropdown" type="OptionButton" parent="CenterContainer/VBoxContainer/MatchRow"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 40)
layout_mode = 2
size_flags_horizontal = 3
[node name="MatchButton" type="Button" parent="CenterContainer/VBoxContainer"]
custom_minimum_size = Vector2(0, 56)
layout_mode = 2
text = "Play Match"
[node name="SettingsSeparator" type="HSeparator" parent="CenterContainer/VBoxContainer"]
layout_mode = 2
[node name="SettingsButton" type="Button" parent="CenterContainer/VBoxContainer"]
custom_minimum_size = Vector2(0, 56)
layout_mode = 2
text = "Settings"
[node name="DevSection" type="VBoxContainer" parent="CenterContainer/VBoxContainer"]
unique_name_in_owner = true
layout_mode = 2
theme_override_constants/separation = 10
[node name="DevSeparator" type="HSeparator" parent="CenterContainer/VBoxContainer/DevSection"]
layout_mode = 2
[node name="DevHeader" type="Label" parent="CenterContainer/VBoxContainer/DevSection"]
layout_mode = 2
theme_override_font_sizes/font_size = 22
text = "Developer"
[node name="DevHint" type="Label" parent="CenterContainer/VBoxContainer/DevSection"]
modulate = Color(1, 1, 1, 0.55)
layout_mode = 2
theme_override_font_sizes/font_size = 13
text = "Dev-only — hidden in release builds"
[node name="DevOpponentRow" type="HBoxContainer" parent="CenterContainer/VBoxContainer/DevSection"]
layout_mode = 2
theme_override_constants/separation = 10
[node name="DevOpponentLabel" type="Label" parent="CenterContainer/VBoxContainer/DevSection/DevOpponentRow"]
layout_mode = 2
text = "Opponent override"
[node name="DevBotDropdown" type="OptionButton" parent="CenterContainer/VBoxContainer/DevSection/DevOpponentRow"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 40)
layout_mode = 2
size_flags_horizontal = 3
[node name="SpectateSeparator" type="HSeparator" parent="CenterContainer/VBoxContainer/DevSection"]
layout_mode = 2
[node name="SpectateHeader" type="Label" parent="CenterContainer/VBoxContainer/DevSection"]
layout_mode = 2
theme_override_font_sizes/font_size = 22
text = "Spectate"
[node name="SpectateHint" type="Label" parent="CenterContainer/VBoxContainer/DevSection"]
modulate = Color(1, 1, 1, 0.55)
layout_mode = 2
theme_override_font_sizes/font_size = 13
text = "Watch two bots play each other"
[node name="SpectateRow" type="HBoxContainer" parent="CenterContainer/VBoxContainer/DevSection"]
layout_mode = 2
theme_override_constants/separation = 10
[node name="BotADropdown" type="OptionButton" parent="CenterContainer/VBoxContainer/DevSection/SpectateRow"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 40)
layout_mode = 2
size_flags_horizontal = 3
[node name="VsLabel" type="Label" parent="CenterContainer/VBoxContainer/DevSection/SpectateRow"]
layout_mode = 2
text = "vs"
[node name="BotBDropdown" type="OptionButton" parent="CenterContainer/VBoxContainer/DevSection/SpectateRow"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 40)
layout_mode = 2
size_flags_horizontal = 3
[node name="SpectateButton" type="Button" parent="CenterContainer/VBoxContainer/DevSection"]
custom_minimum_size = Vector2(0, 56)
layout_mode = 2
text = "Watch Match"
[connection signal="pressed" from="CenterContainer/VBoxContainer/FreePlayButton" to="." method="_on_free_play_pressed"]
[connection signal="pressed" from="CenterContainer/VBoxContainer/MatchButton" to="." method="_on_match_pressed"]
[connection signal="pressed" from="CenterContainer/VBoxContainer/SettingsButton" to="." method="_on_settings_pressed"]
[connection signal="pressed" from="CenterContainer/VBoxContainer/DevSection/SpectateButton" to="." method="_on_spectate_pressed"]
[connection signal="pressed" from="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/FreePlayButton" to="." method="_on_free_play_pressed"]
[connection signal="pressed" from="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/MatchButton" to="." method="_on_match_pressed"]
[connection signal="pressed" from="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/FindMatchButton" to="." method="_on_find_match_pressed"]
[connection signal="pressed" from="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/HostButton" to="." method="_on_host_pressed"]
[connection signal="pressed" from="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/JoinRow/JoinButton" to="." method="_on_join_pressed"]
[connection signal="text_submitted" from="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/JoinRow/JoinAddressEdit" to="." method="_on_join_address_submitted"]
[connection signal="pressed" from="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/SettingsButton" to="." method="_on_settings_pressed"]
[connection signal="pressed" from="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/DevSection/SpectateButton" to="." method="_on_spectate_pressed"]
[connection signal="pressed" from="ConnectingOverlay/CenterContainer/VBoxContainer/ConnectingCancelButton" to="." method="_on_connecting_cancel_pressed"]
-1
View File
@@ -7,5 +7,4 @@
script = ExtResource("1_m")
bot_model_path = "res://bots/promoted/easy.json"
[node name="HUD" parent="." instance=ExtResource("3_m")]
+119
View File
@@ -0,0 +1,119 @@
[gd_scene load_steps=3 format=3]
[ext_resource type="Script" path="res://scripts/matchmaking.gd" id="1_matchmaking"]
[ext_resource type="Theme" path="res://themes/cosmic_clash_theme.tres" id="2_theme"]
[node name="Matchmaking" type="Control"]
layout_mode = 3
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
script = ExtResource("1_matchmaking")
theme = ExtResource("2_theme")
[node name="MarginContainer" type="MarginContainer" parent="."]
layout_mode = 1
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
theme_override_constants/margin_left = 24
theme_override_constants/margin_top = 24
theme_override_constants/margin_right = 24
theme_override_constants/margin_bottom = 24
[node name="ScrollContainer" type="ScrollContainer" parent="MarginContainer"]
layout_mode = 2
follow_focus = true
horizontal_scroll_mode = 0
[node name="CenterContainer" type="CenterContainer" parent="MarginContainer/ScrollContainer"]
layout_mode = 2
size_flags_horizontal = 3
size_flags_vertical = 3
[node name="VBoxContainer" type="VBoxContainer" parent="MarginContainer/ScrollContainer/CenterContainer"]
custom_minimum_size = Vector2(480, 0)
layout_mode = 2
theme_override_constants/separation = 12
[node name="TitleLabel" type="Label" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer"]
layout_mode = 2
theme_override_font_sizes/font_size = 40
text = "Find a Match"
horizontal_alignment = 1
[node name="PlaylistDropdown" type="OptionButton" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 48)
layout_mode = 2
[node name="StatusLabel" type="Label" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer"]
unique_name_in_owner = true
layout_mode = 2
theme_override_font_sizes/font_size = 22
text = "Ready to search"
horizontal_alignment = 1
[node name="DetailLabel" type="Label" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer"]
unique_name_in_owner = true
modulate = Color(1, 1, 1, 0.65)
layout_mode = 2
autowrap_mode = 2
horizontal_alignment = 1
[node name="RankedProfileLabel" type="Label" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer"]
unique_name_in_owner = true
modulate = Color(1, 1, 1, 0.65)
layout_mode = 2
text = "Ranked profile unavailable"
horizontal_alignment = 1
visible = false
[node name="QueueButton" type="Button" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 52)
layout_mode = 2
text = "Search"
[node name="CancelButton" type="Button" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 48)
layout_mode = 2
text = "Cancel Search"
visible = false
[node name="ProposalRow" type="HBoxContainer" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer"]
layout_mode = 2
theme_override_constants/separation = 10
[node name="AcceptButton" type="Button" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/ProposalRow"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 48)
layout_mode = 2
size_flags_horizontal = 3
text = "Accept"
visible = false
[node name="DeclineButton" type="Button" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/ProposalRow"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 48)
layout_mode = 2
size_flags_horizontal = 3
text = "Decline"
visible = false
[node name="BackButton" type="Button" parent="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 48)
layout_mode = 2
text = "Back"
[connection signal="pressed" from="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/QueueButton" to="." method="_on_queue_pressed"]
[connection signal="pressed" from="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/CancelButton" to="." method="_on_cancel_pressed"]
[connection signal="pressed" from="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/ProposalRow/AcceptButton" to="." method="_on_accept_pressed"]
[connection signal="pressed" from="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/ProposalRow/DeclineButton" to="." method="_on_decline_pressed"]
[connection signal="pressed" from="MarginContainer/ScrollContainer/CenterContainer/VBoxContainer/BackButton" to="." method="_on_back_pressed"]
+6
View File
@@ -0,0 +1,6 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://scripts/networked_match.gd" id="1_nm"]
[node name="NetworkedMatch" type="Node3D"]
script = ExtResource("1_nm")
+6
View File
@@ -0,0 +1,6 @@
[gd_scene load_steps=2 format=3]
[ext_resource type="Script" path="res://scripts/server_boot.gd" id="1_sb"]
[node name="ServerBoot" type="Node"]
script = ExtResource("1_sb")
+203 -26
View File
@@ -1,6 +1,8 @@
[gd_scene load_steps=2 format=3]
[gd_scene load_steps=4 format=3]
[ext_resource type="Script" path="res://scripts/settings_menu.gd" id="1_settings"]
[ext_resource type="Theme" path="res://themes/cosmic_clash_theme.tres" id="2_theme"]
[ext_resource type="Script" path="res://scripts/controls_settings.gd" id="3_controls"]
[node name="SettingsMenu" type="Control"]
layout_mode = 3
@@ -10,55 +12,117 @@ anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
script = ExtResource("1_settings")
theme = ExtResource("2_theme")
[node name="CenterContainer" type="CenterContainer" parent="."]
[node name="MarginContainer" type="MarginContainer" parent="."]
layout_mode = 1
anchors_preset = 15
anchor_right = 1.0
anchor_bottom = 1.0
grow_horizontal = 2
grow_vertical = 2
theme_override_constants/margin_left = 24
theme_override_constants/margin_top = 24
theme_override_constants/margin_right = 24
theme_override_constants/margin_bottom = 24
[node name="VBoxContainer" type="VBoxContainer" parent="CenterContainer"]
custom_minimum_size = Vector2(420, 0)
[node name="VBoxContainer" type="VBoxContainer" parent="MarginContainer"]
layout_mode = 2
theme_override_constants/separation = 10
[node name="TitleLabel" type="Label" parent="CenterContainer/VBoxContainer"]
[node name="TitleLabel" type="Label" parent="MarginContainer/VBoxContainer"]
layout_mode = 2
theme_override_font_sizes/font_size = 36
text = "Settings"
horizontal_alignment = 1
[node name="TitleSpacer" type="Control" parent="CenterContainer/VBoxContainer"]
custom_minimum_size = Vector2(0, 14)
[node name="TabContainer" type="TabContainer" parent="MarginContainer/VBoxContainer"]
layout_mode = 2
size_flags_vertical = 3
tab_alignment = 1
[node name="AARow" type="HBoxContainer" parent="CenterContainer/VBoxContainer"]
[node name="Video" type="ScrollContainer" parent="MarginContainer/VBoxContainer/TabContainer"]
layout_mode = 2
follow_focus = true
horizontal_scroll_mode = 0
[node name="CenterContainer" type="CenterContainer" parent="MarginContainer/VBoxContainer/TabContainer/Video"]
layout_mode = 2
size_flags_horizontal = 3
size_flags_vertical = 3
[node name="VBoxContainer" type="VBoxContainer" parent="MarginContainer/VBoxContainer/TabContainer/Video/CenterContainer"]
custom_minimum_size = Vector2(420, 0)
layout_mode = 2
theme_override_constants/separation = 10
[node name="AALabel" type="Label" parent="CenterContainer/VBoxContainer/AARow"]
[node name="PresetRow" type="HBoxContainer" parent="MarginContainer/VBoxContainer/TabContainer/Video/CenterContainer/VBoxContainer"]
layout_mode = 2
theme_override_constants/separation = 10
[node name="PresetLabel" type="Label" parent="MarginContainer/VBoxContainer/TabContainer/Video/CenterContainer/VBoxContainer/PresetRow"]
custom_minimum_size = Vector2(110, 0)
layout_mode = 2
text = "Anti-aliasing"
text = "Graphics preset"
[node name="AADropdown" type="OptionButton" parent="CenterContainer/VBoxContainer/AARow"]
[node name="PresetDropdown" type="OptionButton" parent="MarginContainer/VBoxContainer/TabContainer/Video/CenterContainer/VBoxContainer/PresetRow"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 40)
layout_mode = 2
size_flags_horizontal = 3
[node name="GlowRow" type="HBoxContainer" parent="CenterContainer/VBoxContainer"]
[node name="AARow" type="HBoxContainer" parent="MarginContainer/VBoxContainer/TabContainer/Video/CenterContainer/VBoxContainer"]
layout_mode = 2
theme_override_constants/separation = 10
[node name="GlowLabel" type="Label" parent="CenterContainer/VBoxContainer/GlowRow"]
[node name="AALabel" type="Label" parent="MarginContainer/VBoxContainer/TabContainer/Video/CenterContainer/VBoxContainer/AARow"]
custom_minimum_size = Vector2(110, 0)
layout_mode = 2
text = "Anti-aliasing"
[node name="AADropdown" type="OptionButton" parent="MarginContainer/VBoxContainer/TabContainer/Video/CenterContainer/VBoxContainer/AARow"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 40)
layout_mode = 2
size_flags_horizontal = 3
[node name="ResolutionRow" type="HBoxContainer" parent="MarginContainer/VBoxContainer/TabContainer/Video/CenterContainer/VBoxContainer"]
layout_mode = 2
theme_override_constants/separation = 10
[node name="ResolutionLabel" type="Label" parent="MarginContainer/VBoxContainer/TabContainer/Video/CenterContainer/VBoxContainer/ResolutionRow"]
custom_minimum_size = Vector2(110, 0)
layout_mode = 2
text = "Resolution scale"
[node name="ResolutionSlider" type="HSlider" parent="MarginContainer/VBoxContainer/TabContainer/Video/CenterContainer/VBoxContainer/ResolutionRow"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 24)
layout_mode = 2
size_flags_horizontal = 3
size_flags_vertical = 4
min_value = 0.5
max_value = 1.0
step = 0.05
value = 1.0
[node name="ResolutionValueLabel" type="Label" parent="MarginContainer/VBoxContainer/TabContainer/Video/CenterContainer/VBoxContainer/ResolutionRow"]
unique_name_in_owner = true
custom_minimum_size = Vector2(48, 0)
layout_mode = 2
text = "100%"
horizontal_alignment = 2
[node name="GlowRow" type="HBoxContainer" parent="MarginContainer/VBoxContainer/TabContainer/Video/CenterContainer/VBoxContainer"]
layout_mode = 2
theme_override_constants/separation = 10
[node name="GlowLabel" type="Label" parent="MarginContainer/VBoxContainer/TabContainer/Video/CenterContainer/VBoxContainer/GlowRow"]
custom_minimum_size = Vector2(110, 0)
layout_mode = 2
text = "Glow intensity"
[node name="GlowSlider" type="HSlider" parent="CenterContainer/VBoxContainer/GlowRow"]
[node name="GlowSlider" type="HSlider" parent="MarginContainer/VBoxContainer/TabContainer/Video/CenterContainer/VBoxContainer/GlowRow"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 24)
layout_mode = 2
@@ -69,23 +133,23 @@ max_value = 1.5
step = 0.05
value = 1.0
[node name="GlowValueLabel" type="Label" parent="CenterContainer/VBoxContainer/GlowRow"]
[node name="GlowValueLabel" type="Label" parent="MarginContainer/VBoxContainer/TabContainer/Video/CenterContainer/VBoxContainer/GlowRow"]
unique_name_in_owner = true
custom_minimum_size = Vector2(48, 0)
layout_mode = 2
text = "100%"
horizontal_alignment = 2
[node name="BrightnessRow" type="HBoxContainer" parent="CenterContainer/VBoxContainer"]
[node name="BrightnessRow" type="HBoxContainer" parent="MarginContainer/VBoxContainer/TabContainer/Video/CenterContainer/VBoxContainer"]
layout_mode = 2
theme_override_constants/separation = 10
[node name="BrightnessLabel" type="Label" parent="CenterContainer/VBoxContainer/BrightnessRow"]
[node name="BrightnessLabel" type="Label" parent="MarginContainer/VBoxContainer/TabContainer/Video/CenterContainer/VBoxContainer/BrightnessRow"]
custom_minimum_size = Vector2(110, 0)
layout_mode = 2
text = "Brightness"
[node name="BrightnessSlider" type="HSlider" parent="CenterContainer/VBoxContainer/BrightnessRow"]
[node name="BrightnessSlider" type="HSlider" parent="MarginContainer/VBoxContainer/TabContainer/Video/CenterContainer/VBoxContainer/BrightnessRow"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 24)
layout_mode = 2
@@ -96,23 +160,136 @@ max_value = 1.3
step = 0.02
value = 1.0
[node name="BrightnessValueLabel" type="Label" parent="CenterContainer/VBoxContainer/BrightnessRow"]
[node name="BrightnessValueLabel" type="Label" parent="MarginContainer/VBoxContainer/TabContainer/Video/CenterContainer/VBoxContainer/BrightnessRow"]
unique_name_in_owner = true
custom_minimum_size = Vector2(48, 0)
layout_mode = 2
text = "100%"
horizontal_alignment = 2
[node name="ButtonSpacer" type="Control" parent="CenterContainer/VBoxContainer"]
custom_minimum_size = Vector2(0, 14)
[node name="VsyncRow" type="HBoxContainer" parent="MarginContainer/VBoxContainer/TabContainer/Video/CenterContainer/VBoxContainer"]
layout_mode = 2
theme_override_constants/separation = 10
[node name="BackButton" type="Button" parent="CenterContainer/VBoxContainer"]
[node name="VsyncLabel" type="Label" parent="MarginContainer/VBoxContainer/TabContainer/Video/CenterContainer/VBoxContainer/VsyncRow"]
custom_minimum_size = Vector2(110, 0)
layout_mode = 2
text = "VSync"
[node name="VsyncDropdown" type="OptionButton" parent="MarginContainer/VBoxContainer/TabContainer/Video/CenterContainer/VBoxContainer/VsyncRow"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 40)
layout_mode = 2
size_flags_horizontal = 3
[node name="FpsCapRow" type="HBoxContainer" parent="MarginContainer/VBoxContainer/TabContainer/Video/CenterContainer/VBoxContainer"]
layout_mode = 2
theme_override_constants/separation = 10
[node name="FpsCapLabel" type="Label" parent="MarginContainer/VBoxContainer/TabContainer/Video/CenterContainer/VBoxContainer/FpsCapRow"]
custom_minimum_size = Vector2(110, 0)
layout_mode = 2
text = "FPS cap"
[node name="FpsCapDropdown" type="OptionButton" parent="MarginContainer/VBoxContainer/TabContainer/Video/CenterContainer/VBoxContainer/FpsCapRow"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 40)
layout_mode = 2
size_flags_horizontal = 3
[node name="FpsReadoutRow" type="HBoxContainer" parent="MarginContainer/VBoxContainer/TabContainer/Video/CenterContainer/VBoxContainer"]
layout_mode = 2
theme_override_constants/separation = 10
[node name="FpsReadoutTitleLabel" type="Label" parent="MarginContainer/VBoxContainer/TabContainer/Video/CenterContainer/VBoxContainer/FpsReadoutRow"]
custom_minimum_size = Vector2(110, 0)
layout_mode = 2
text = "Current"
[node name="FpsReadoutLabel" type="Label" parent="MarginContainer/VBoxContainer/TabContainer/Video/CenterContainer/VBoxContainer/FpsReadoutRow"]
unique_name_in_owner = true
layout_mode = 2
size_flags_horizontal = 3
text = "0 fps"
[node name="Controls" type="ScrollContainer" parent="MarginContainer/VBoxContainer/TabContainer"]
visible = false
layout_mode = 2
follow_focus = true
horizontal_scroll_mode = 0
script = ExtResource("3_controls")
[node name="CenterContainer" type="CenterContainer" parent="MarginContainer/VBoxContainer/TabContainer/Controls"]
layout_mode = 2
size_flags_horizontal = 3
size_flags_vertical = 3
[node name="VBoxContainer" type="VBoxContainer" parent="MarginContainer/VBoxContainer/TabContainer/Controls/CenterContainer"]
custom_minimum_size = Vector2(520, 0)
layout_mode = 2
theme_override_constants/separation = 10
[node name="DeviceRow" type="HBoxContainer" parent="MarginContainer/VBoxContainer/TabContainer/Controls/CenterContainer/VBoxContainer"]
layout_mode = 2
theme_override_constants/separation = 10
[node name="DeviceLabel" type="Label" parent="MarginContainer/VBoxContainer/TabContainer/Controls/CenterContainer/VBoxContainer/DeviceRow"]
custom_minimum_size = Vector2(160, 0)
layout_mode = 2
text = "Device"
[node name="KeyboardButton" type="Button" parent="MarginContainer/VBoxContainer/TabContainer/Controls/CenterContainer/VBoxContainer/DeviceRow"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 40)
layout_mode = 2
size_flags_horizontal = 3
toggle_mode = true
button_pressed = true
text = "Keyboard"
[node name="ControllerButton" type="Button" parent="MarginContainer/VBoxContainer/TabContainer/Controls/CenterContainer/VBoxContainer/DeviceRow"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 40)
layout_mode = 2
size_flags_horizontal = 3
toggle_mode = true
text = "Controller"
[node name="StatusLabel" type="Label" parent="MarginContainer/VBoxContainer/TabContainer/Controls/CenterContainer/VBoxContainer"]
unique_name_in_owner = true
modulate = Color(1, 0.85, 0.5, 1)
layout_mode = 2
theme_override_font_sizes/font_size = 13
text = ""
autowrap_mode = 2
[node name="BindingList" type="VBoxContainer" parent="MarginContainer/VBoxContainer/TabContainer/Controls/CenterContainer/VBoxContainer"]
unique_name_in_owner = true
layout_mode = 2
theme_override_constants/separation = 6
[node name="InvertPitchCheck" type="CheckBox" parent="MarginContainer/VBoxContainer/TabContainer/Controls/CenterContainer/VBoxContainer"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 40)
layout_mode = 2
text = "Invert pitch"
[node name="ResetButton" type="Button" parent="MarginContainer/VBoxContainer/TabContainer/Controls/CenterContainer/VBoxContainer"]
unique_name_in_owner = true
custom_minimum_size = Vector2(0, 44)
layout_mode = 2
text = "Reset all bindings to defaults"
[node name="BackButton" type="Button" parent="MarginContainer/VBoxContainer"]
custom_minimum_size = Vector2(0, 56)
layout_mode = 2
text = "Back"
[connection signal="item_selected" from="CenterContainer/VBoxContainer/AARow/AADropdown" to="." method="_on_aa_dropdown_item_selected"]
[connection signal="value_changed" from="CenterContainer/VBoxContainer/GlowRow/GlowSlider" to="." method="_on_glow_slider_value_changed"]
[connection signal="value_changed" from="CenterContainer/VBoxContainer/BrightnessRow/BrightnessSlider" to="." method="_on_brightness_slider_value_changed"]
[connection signal="pressed" from="CenterContainer/VBoxContainer/BackButton" to="." method="_on_back_pressed"]
[connection signal="item_selected" from="MarginContainer/VBoxContainer/TabContainer/Video/CenterContainer/VBoxContainer/PresetRow/PresetDropdown" to="." method="_on_preset_dropdown_item_selected"]
[connection signal="item_selected" from="MarginContainer/VBoxContainer/TabContainer/Video/CenterContainer/VBoxContainer/AARow/AADropdown" to="." method="_on_aa_dropdown_item_selected"]
[connection signal="value_changed" from="MarginContainer/VBoxContainer/TabContainer/Video/CenterContainer/VBoxContainer/ResolutionRow/ResolutionSlider" to="." method="_on_resolution_slider_value_changed"]
[connection signal="value_changed" from="MarginContainer/VBoxContainer/TabContainer/Video/CenterContainer/VBoxContainer/GlowRow/GlowSlider" to="." method="_on_glow_slider_value_changed"]
[connection signal="value_changed" from="MarginContainer/VBoxContainer/TabContainer/Video/CenterContainer/VBoxContainer/BrightnessRow/BrightnessSlider" to="." method="_on_brightness_slider_value_changed"]
[connection signal="item_selected" from="MarginContainer/VBoxContainer/TabContainer/Video/CenterContainer/VBoxContainer/VsyncRow/VsyncDropdown" to="." method="_on_vsync_dropdown_item_selected"]
[connection signal="item_selected" from="MarginContainer/VBoxContainer/TabContainer/Video/CenterContainer/VBoxContainer/FpsCapRow/FpsCapDropdown" to="." method="_on_fps_cap_dropdown_item_selected"]
[connection signal="pressed" from="MarginContainer/VBoxContainer/BackButton" to="." method="_on_back_pressed"]
+33
View File
@@ -30,6 +30,11 @@ class_name HUDController
@onready var camera_mode_label = get_node_or_null("Control/Instruments/Cluster/CameraModeLabel")
var ship: Node
# §6.3 (task 5.8). Set by the game mode BEFORE this node enters the tree when
# the local peer has no ship of its own. Distinct from `ship == null` by
# accident: a missing ship is still an error for a player, and silently
# degrading to a spectator HUD would hide that.
var spectator_mode := false
var _last_score := {0: 0, 1: 0}
var _goal_tween: Tween
@@ -43,6 +48,16 @@ func _initialize_hud():
# this runs — not discovered via group, since the "ship" group can have
# 2+ members and there's no reliable way to tell which one is "ours".
if not ship:
# §6.3 (task 5.8): a spectator legitimately has no ship of its own, and
# must still get the score, clock and goal celebration. Only the
# per-ship instrument cluster is meaningless without one, so hide that
# and carry on wiring everything else — this used to push_error and
# bail, which left a spectator with a completely dead HUD.
if spectator_mode:
print("HUDController: spectator mode — hiding ship instruments")
_hide_ship_instruments()
_connect_mode_signals()
return
push_error("HUDController: No ship assigned")
return
@@ -59,6 +74,24 @@ func _initialize_hud():
if camera_rig and camera_rig.has_signal("camera_mode_changed"):
camera_rig.camera_mode_changed.connect(_on_ship_camera_mode_changed)
_connect_mode_signals()
func _hide_ship_instruments() -> void:
# The per-ship cluster (speed, altitude, thrust, boost, camera mode) has no
# meaning without a ship. Everything else on the HUD still does.
for node in [speed_gauge, altitude_gauge, camera_mode_label]:
if node and is_instance_valid(node):
node.visible = false
var cluster := get_node_or_null("Control/Instruments/Cluster")
if cluster and is_instance_valid(cluster):
cluster.visible = false
# Everything that depends on the MODE rather than on owning a ship: clock,
# score, team identity, match-ended, kickoff countdown. A spectator gets all
# of it.
func _connect_mode_signals() -> void:
# Connect to game manager's timer signal; modes without a timer
# (e.g. free play) just don't show one
var game_manager = get_tree().get_first_node_in_group("game")
@@ -0,0 +1,37 @@
class_name AdaptiveInputDepthController
extends RefCounted
# Client-only policy for choosing whether the server's input jitter buffer may
# run at depth zero. It deliberately does not change server buffering, action
# encoding, or bot behavior; NetworkedMatch pins --test-bot clients at depth 1.
const TARGET_DEPTH_SAFE := 1
const TARGET_DEPTH_LOW_LATENCY := 0
const CLEAN_JITTER_MS := 3.0
const EXIT_JITTER_MS := 5.0
const REQUIRED_STABLE_TICKS := 240
const REENTRY_COOLDOWN_TICKS := 120
var target_depth := TARGET_DEPTH_SAFE
var stable_low_jitter_ticks := 0
var cooldown_ticks := 0
func update(rtt_ms: float, jitter_ms: float, advertised_depth: int) -> int:
if cooldown_ticks > 0:
cooldown_ticks -= 1
# -2 is a genuine server starvation sentinel. -1 means no header yet and
# must not be mistaken for starvation.
if advertised_depth < -1 or jitter_ms > EXIT_JITTER_MS:
target_depth = TARGET_DEPTH_SAFE
stable_low_jitter_ticks = 0
cooldown_ticks = REENTRY_COOLDOWN_TICKS
return target_depth
if rtt_ms >= 0.0 and jitter_ms < CLEAN_JITTER_MS:
stable_low_jitter_ticks += 1
if stable_low_jitter_ticks >= REQUIRED_STABLE_TICKS and cooldown_ticks == 0:
target_depth = TARGET_DEPTH_LOW_LATENCY
else:
stable_low_jitter_ticks = 0
target_depth = TARGET_DEPTH_SAFE
return target_depth
@@ -0,0 +1 @@
uid://dofgtukllr7yr
+152
View File
@@ -0,0 +1,152 @@
class_name AgonesSDK
extends Node
# Dependency-free REST bridge for the Agones sidecar. The Go supervisor owns
# the process-ready probe and /ready transition; this node owns the game
# process's periodic Health pings and terminal Shutdown/annotation calls.
const HEALTH_INTERVAL_SECONDS := 2.0
const REQUEST_TIMEOUT_SECONDS := 2.0
const MAX_ANNOTATION_VALUE_LENGTH := 4096
var _base_url := ""
var _health_timer: Timer = null
var _health_in_flight := false
var _health_started_msec := 0
# Set when start_health() is called before this node is inside the tree, so
# _ready() can arm the timer at the first moment it is legal to do so.
var _health_pending := false
# Health is armed here rather than by the caller. A Timer only ticks while its
# owner is inside the SceneTree, so arming it from a caller that has not yet
# parented this node produces a node that looks configured and never pings —
# which is exactly how every allocated GameServer silently failed its Agones
# health check and was recycled.
func _ready() -> void:
if _health_pending:
_health_pending = false
_arm_health()
func configure_from_environment() -> bool:
var port := OS.get_environment("AGONES_SDK_HTTP_PORT")
if port.is_empty() or not port.is_valid_int() or int(port) < 1 or int(port) > 65535:
return false
_base_url = "http://127.0.0.1:%d" % int(port)
return true
func configure_for_testing(base_url: String) -> bool:
if not base_url.begins_with("http://127.0.0.1:") and not base_url.begins_with("http://localhost:"):
return false
_base_url = base_url.trim_suffix("/")
return true
func is_available() -> bool:
return not _base_url.is_empty()
# Returns whether health pings are running. It is a bool rather than void
# because every way this can fail used to be silent, and a game server that
# believes it is healthy while sending nothing is worse than one that refuses
# to start: Agones recycles the former every ~20 seconds forever.
func start_health() -> bool:
if not is_available():
push_error("AgonesSDK: start_health() before configuration; no health pings will be sent")
return false
if _health_timer != null:
return true
if not is_inside_tree():
# Deferred rather than fatal: the caller may legitimately configure
# before parenting. _ready() arms it. Still reported, because if the
# node is never parented this is the whole failure.
_health_pending = true
push_warning("AgonesSDK: start_health() called outside the tree; deferring until ready")
return false
_arm_health()
return true
func _arm_health() -> void:
if _health_timer != null:
return
_health_timer = Timer.new()
_health_timer.name = "AgonesHealth"
_health_timer.wait_time = HEALTH_INTERVAL_SECONDS
_health_timer.one_shot = false
_health_timer.timeout.connect(_send_health)
add_child(_health_timer)
_health_timer.start()
_send_health()
func health_is_running() -> bool:
return _health_timer != null and is_inside_tree()
func stop_health() -> void:
if _health_timer != null:
_health_timer.stop()
_health_timer.queue_free()
_health_timer = null
func health() -> int:
return await _request(HTTPClient.METHOD_POST, "/health", {})
func mark_ready() -> int:
return await _request(HTTPClient.METHOD_POST, "/ready", {})
func shutdown() -> int:
return await _request(HTTPClient.METHOD_POST, "/shutdown", {})
func set_annotation(key: String, value: String) -> int:
if not annotation_is_valid(key, value):
return 400
return await _request(HTTPClient.METHOD_PUT, "/metadata/annotation", {"key": key, "value": value})
static func annotation_is_valid(key: String, value: String) -> bool:
return not (key.is_empty() or value.is_empty() or value.length() > MAX_ANNOTATION_VALUE_LENGTH or "\n" in key or "\r" in key or "\n" in value or "\r" in value)
func _send_health() -> void:
if not is_available():
return
# The latch stops overlapping requests, but it must never become permanent.
# It is set across an await, and a request that never completes would
# otherwise silence health for the lifetime of the process. HTTPRequest's
# own timeout normally resolves this; the elapsed check is the backstop for
# the case where request_completed never fires at all.
if _health_in_flight:
var stuck_for := Time.get_ticks_msec() - _health_started_msec
if stuck_for < int(REQUEST_TIMEOUT_SECONDS * 2.0 * 1000.0):
return
push_warning("Agones health ping did not complete in %dms; sending another" % stuck_for)
_health_in_flight = true
_health_started_msec = Time.get_ticks_msec()
var status := await health()
_health_in_flight = false
if status < 200 or status >= 300:
push_warning("Agones health ping failed (%d)" % status)
func _request(method: int, path: String, payload: Dictionary) -> int:
if not is_available() or not path.begins_with("/"):
return 408
var request := HTTPRequest.new()
request.timeout = REQUEST_TIMEOUT_SECONDS
add_child(request)
var body := JSON.stringify(payload)
var err := request.request(_base_url + path, PackedStringArray(["Content-Type: application/json"]), method, body)
if err != OK:
request.queue_free()
return 599
var result = await request.request_completed
request.queue_free()
return int(result[1])
+19
View File
@@ -1,6 +1,13 @@
class_name AIShipController
extends ShipController
# Emitted if a cached teammate/opponent reference is found freed and dropped
# from the roster (see _decide). No despawn path exists anywhere in this
# codebase today — rosters are fixed at match start — so this never fires in
# practice; it's cheap insurance against ShipObservations.build() crashing on
# a stale reference if that ever changes.
signal roster_changed
# Drives a ship from a trained self-play policy (see TRAINING.md). Builds the
# same canonical observation as training (ShipObservations) and runs the
# policy MLP in GDScript (PolicyNetwork) — the shipped bot has no Python,
@@ -50,6 +57,13 @@ var _scene_refs_ready := false
func _ready():
if not model_path.is_empty():
load_policy(model_path)
# Stagger the first decision across [1, reaction_ticks] so bots sharing a
# reaction cadence don't all run policy inference on the same physics
# tick — six bots landing together is a ~2.4 ms spike in a 16.7 ms budget
# (policy_network.gd's forward pass). The phase offset this establishes
# persists across subsequent decisions since each one re-arms the same
# period from wherever _ticks_until_decision currently sits.
_ticks_until_decision = randi_range(1, maxi(reaction_ticks, 1))
# League training swaps a frozen opponent's policy between episodes without
@@ -83,6 +97,11 @@ func get_action() -> ShipAction:
func _decide() -> void:
if _teammates.any(func(s): return not is_instance_valid(s)) \
or _opponents.any(func(s): return not is_instance_valid(s)):
_teammates = _teammates.filter(is_instance_valid)
_opponents = _opponents.filter(is_instance_valid)
roster_changed.emit()
var obs := ShipObservations.build(_ship, _teammates, _opponents, _ball, _attack_goal_position)
var out := _policy.forward(obs)
# See ShipActionCodec for the decode — the single source of truth shared
+48 -12
View File
@@ -19,23 +19,59 @@ extends Node3D
@export var glow_hdr_threshold := 1.0
var _env: Environment
# Lights authored with shadow_enabled = true (the DirectionalLight3D + 4
# PitchLights omnis) — captured once, before gating ever touches them. Every
# call after the first re-applies VideoSettings.shadows_enabled to exactly
# these lights, so the set can't self-poison (if it were re-derived from
# current state, a light this same code just turned off would look
# indistinguishable from FillLight, which is authored off on purpose and must
# never be turned on by the preset ladder).
var _shadow_capable_lights: Array[Light3D] = []
func _ready():
add_to_group("arena")
# A headless server never renders, so duplicating and configuring a full
# Environment (glow/SSAO/SSIL/SDFGI) for it is pure waste — mirrors the
# same guard at ship.gd and arena_boundary.gd.
if DisplayServer.get_name() == "headless":
return
var world_env := get_node_or_null("WorldEnvironment") as WorldEnvironment
if world_env and world_env.environment:
var env := world_env.environment.duplicate(true) as Environment
world_env.environment = env
_env = world_env.environment.duplicate(true) as Environment
world_env.environment = _env
if sky_material:
if not env.sky:
env.sky = Sky.new()
env.sky.sky_material = sky_material
env.ambient_light_color = ambient_light_color
env.ambient_light_energy = ambient_light_energy
env.glow_intensity = glow_intensity
env.glow_strength = glow_strength
env.glow_bloom = glow_bloom
env.glow_hdr_threshold = glow_hdr_threshold
VideoSettings.apply_to_environment(env)
if not _env.sky:
_env.sky = Sky.new()
_env.sky.sky_material = sky_material
_env.ambient_light_color = ambient_light_color
_env.ambient_light_energy = ambient_light_energy
_env.glow_intensity = glow_intensity
_env.glow_strength = glow_strength
_env.glow_bloom = glow_bloom
_env.glow_hdr_threshold = glow_hdr_threshold
for light in find_children("*", "Light3D", true, false):
if (light as Light3D).shadow_enabled:
_shadow_capable_lights.append(light)
_apply_video_settings()
# Task 0.17: a preset change from the settings menu must take effect
# on the arena that's already loaded, not just the next one — this is
# the "settings persist and apply without a restart" acceptance bar.
VideoSettings.settings_changed.connect(_apply_video_settings)
# Re-run on every VideoSettings.settings_changed (preset or individual
# toggle) as well as once at load. Shadow gating lives here rather than in
# VideoSettings.apply_to_environment() because it targets Light3D nodes in
# this arena's own tree, not the Environment resource.
func _apply_video_settings() -> void:
if not is_instance_valid(_env):
return
VideoSettings.apply_to_environment(_env)
for light in _shadow_capable_lights:
if is_instance_valid(light):
light.shadow_enabled = VideoSettings.shadows_enabled
func get_ball_spawn() -> Transform3D:
+17 -1
View File
@@ -117,6 +117,10 @@ var _field_material: ShaderMaterial
# Cached active camera for _process(), mirroring ship_camera.gd's _get_ball()
# pattern so the viewport lookup isn't repeated every frame.
var _camera: Camera3D
var _last_camera_local_pos := Vector3.INF
# Below this, the shader's per-pixel facing test can't produce a visibly
# different result — skip the to_local()/set_shader_parameter() call.
const CAMERA_UNIFORM_UPDATE_THRESHOLD := 0.05
# Group every generated collider is tagged with. A CollisionShape3D only
# registers a shape with a CollisionObject3D that is its DIRECT parent — an
@@ -184,6 +188,14 @@ func get_surface_pull(
global_pos: Vector3, wall_strength: float, wall_range: float,
ceiling_strength: float, ceiling_range: float
) -> Vector3:
# Early-out: every dynamic body pays to_local() plus five _falloff calls
# every tick even mid-arena, where every term is exactly zero. Compared
# directly against global_pos, matching the same identity-transform
# assumption GameMode._is_escaped already makes against these constants.
if absf(global_pos.x) < INNER_HALF_X - wall_range \
and absf(global_pos.z) < INNER_HALF_Z - wall_range \
and global_pos.y < INNER_HEIGHT - ceiling_range:
return Vector3.ZERO
var p := to_local(global_pos)
var pull := Vector3.ZERO
pull += Vector3(1, 0, 0) * _falloff(INNER_HALF_X - p.x, wall_range) * wall_strength
@@ -214,7 +226,11 @@ func _process(_delta: float) -> void:
var camera := _get_camera()
if camera == null:
return # headless (RL/CI) has no camera
_field_material.set_shader_parameter("camera_local_pos", to_local(camera.global_position))
var local_pos := to_local(camera.global_position)
if local_pos.distance_to(_last_camera_local_pos) < CAMERA_UNIFORM_UPDATE_THRESHOLD:
return
_last_camera_local_pos = local_pos
_field_material.set_shader_parameter("camera_local_pos", local_pos)
# Caches the viewport's active camera; a plain is_instance_valid revalidation
+23
View File
@@ -24,3 +24,26 @@ const ARENAS := [
static func random_path() -> String:
var candidates := ARENAS.filter(func(arena): return arena["random"])
return candidates[randi() % candidates.size()]["path"]
# The arenas a server may rotate through, in declaration order. Same filter as
# random_path(): an elevated-goal variant is Free-Play-only until a checkpoint
# trained on it is promoted, and a dedicated server rotating onto one would
# hand every bot-filled slot an arena it cannot score in.
static func rotation_paths() -> Array:
return ARENAS.filter(func(arena): return arena["random"]).map(func(arena): return arena["path"])
# Task 6.5's arena rotation, as pure arithmetic so it is unit-testable without
# a server: given how many matches have already been played, which arena is
# next. `random` deliberately still uses the global RNG (the caller wants
# variety, not reproducibility); `sequential` is a pure function of the count,
# which is what makes "the server cycles arenas" an assertable claim rather
# than an observation about luck.
static func path_for_match(match_index: int, mode: String) -> String:
var paths := rotation_paths()
if paths.is_empty():
return ARENAS[0]["path"]
if mode == "random":
return paths[randi() % paths.size()]
return paths[posmod(match_index, paths.size())]
+85
View File
@@ -0,0 +1,85 @@
class_name AssignmentState
extends RefCounted
# Verified assignment-ready manifest returned by the control plane. The join
# authorisation is retained in memory only and is never written to the restart
# snapshot; transport installation belongs to the explicit ENet/Steam layer.
var available := false
var match_id := ""
var server_id := ""
var slot := -1
var expires_at := ""
var protocol_version := 0
var transport := ""
var endpoint := ""
var join_authorisation := ""
var error_message := ""
func apply(payload: Dictionary, expected_player_id: String = "") -> bool:
for key in ["match_id", "server_id", "player_id", "slot", "expires_at", "protocol_version", "transport", "endpoint", "join_authorisation"]:
if not payload.has(key):
return _reject("Assignment response is missing " + key)
if not payload["match_id"] is String or not payload["server_id"] is String or not payload["player_id"] is String or not _valid_nonnegative_integer(payload["slot"]) or not payload["expires_at"] is String or not _valid_nonnegative_integer(payload["protocol_version"]) or not payload["transport"] is String or not payload["endpoint"] is String or not payload["join_authorisation"] is String:
return _reject("Assignment response contains invalid types")
var next_match_id := String(payload["match_id"])
var next_server_id := String(payload["server_id"])
var next_transport := String(payload["transport"])
var next_endpoint := String(payload["endpoint"])
var next_player_id := String(payload["player_id"])
var next_expires_at := String(payload["expires_at"])
if not is_valid_expiry_timestamp(next_expires_at):
return _reject("Assignment response contains invalid expiry")
var expiry_unix := Time.get_unix_time_from_datetime_string(next_expires_at)
if not is_valid_opaque_id(next_match_id) or not is_valid_opaque_id(next_server_id) or not is_valid_opaque_id(next_player_id) or (not expected_player_id.is_empty() and next_player_id != expected_player_id) or int(payload["slot"]) < 0 or int(payload["slot"]) > 5 or int(payload["protocol_version"]) < 1 or (next_transport != "enet" and next_transport != "steam_sdr") or not _valid_endpoint(next_endpoint) or expiry_unix <= Time.get_unix_time_from_system() or String(payload["join_authorisation"]).is_empty():
return _reject("Assignment response contains invalid values")
match_id = next_match_id
server_id = next_server_id
slot = int(payload["slot"])
expires_at = next_expires_at
protocol_version = int(payload["protocol_version"])
transport = next_transport
endpoint = next_endpoint
join_authorisation = String(payload["join_authorisation"])
available = true
error_message = ""
return true
static func is_valid_expiry_timestamp(value: String) -> bool:
if value.is_empty():
return false
var timestamp_pattern := RegEx.create_from_string("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$")
return timestamp_pattern.search(value) != null
static func is_valid_opaque_id(value: String) -> bool:
if value.length() < 16 or value.length() > 128:
return false
var resource_pattern := RegEx.create_from_string("^[A-Za-z0-9_-]+$")
return resource_pattern.search(value) != null
static func _valid_endpoint(value: String) -> bool:
if value.is_empty() or value.contains("/") or value.contains("?") or value.contains("#"):
return false
var separator := value.rfind(":")
if separator <= 0 or separator >= value.length() - 1:
return false
var port := value.substr(separator + 1)
return port.is_valid_int() and int(port) >= 1 and int(port) <= 65535
static func _valid_nonnegative_integer(value: Variant) -> bool:
if value is int:
return int(value) >= 0
if value is float:
return is_finite(float(value)) and float(value) >= 0.0 and float(value) == floor(float(value))
return false
func _reject(reason: String) -> bool:
available = false
error_message = reason
return false
+149
View File
@@ -0,0 +1,149 @@
extends Node
# Dependency-free audio foundation. Authored assets can replace these tones
# later without changing gameplay call sites or the multiplayer event flow.
const SAMPLE_RATE := 44100
const MAX_INTENSITY := 1.0
var enabled := true
var _engine_player: AudioStreamPlayer
var _engine_turbo := false
var _last_wall_scrape_ms := -1000
func bind_tree_buttons(root: Node) -> void:
if root == null:
return
for node in root.find_children("*", "BaseButton", true, false):
bind_button(node as BaseButton)
func bind_button(button: BaseButton) -> void:
if button == null:
return
var callback := Callable(self, "play_ui_click")
if not button.pressed.is_connected(callback):
button.pressed.connect(callback)
func play_ui_click() -> void:
_play_tone(880.0, 0.045, 0.10)
func play_countdown(count: int) -> void:
if count <= 0:
_play_tone(1046.5, 0.12, 0.18)
else:
_play_tone(countdown_frequency(count), 0.08, 0.14)
func play_impact(intensity: float) -> void:
var amount := clamp_intensity(intensity)
if amount <= 0.0:
return
_play_tone(150.0 + 180.0 * amount, 0.06 + 0.08 * amount, 0.08 + 0.18 * amount)
func play_wall_scrape(intensity: float) -> void:
var amount := clamp_intensity(intensity)
if amount <= 0.0:
return
var now_ms := Time.get_ticks_msec()
if now_ms - _last_wall_scrape_ms < 80:
return
_last_wall_scrape_ms = now_ms
_play_tone(110.0 + 90.0 * amount, 0.05 + 0.07 * amount, 0.05 + 0.10 * amount)
func play_goal() -> void:
_play_tone(523.25, 0.22, 0.22)
_play_tone(783.99, 0.30, 0.18)
func set_engine_state(thrust: float, turbo: bool) -> void:
var amount := clamp_intensity(thrust)
var rising_turbo := should_play_turbo_cue(_engine_turbo, turbo, amount)
if not enabled or amount <= 0.01:
stop_engine()
return
if rising_turbo:
_play_tone(260.0, 0.16, 0.16)
_engine_turbo = turbo
if _engine_player == null or not is_instance_valid(_engine_player):
_engine_player = AudioStreamPlayer.new()
_engine_player.stream = _engine_stream()
add_child(_engine_player)
_engine_player.play()
_engine_player.pitch_scale = engine_pitch(amount, turbo)
_engine_player.volume_db = linear_to_db(engine_volume(amount, turbo))
func stop_engine() -> void:
if _engine_player != null and is_instance_valid(_engine_player):
_engine_player.stop()
_engine_turbo = false
static func engine_pitch(thrust: float, turbo: bool) -> float:
var amount := clamp_intensity(thrust)
return 0.75 + amount * 0.55 + (0.30 if turbo and amount > 0.01 else 0.0)
static func engine_volume(thrust: float, turbo: bool) -> float:
var amount := clamp_intensity(thrust)
return clampf(0.015 + amount * 0.045 + (0.025 if turbo and amount > 0.01 else 0.0), 0.0, 0.1)
static func should_play_turbo_cue(previous_turbo: bool, turbo: bool, thrust: float) -> bool:
return turbo and not previous_turbo and clamp_intensity(thrust) > 0.01
static func clamp_intensity(value: float) -> float:
if not is_finite(value):
return 0.0
return clampf(value, 0.0, MAX_INTENSITY)
static func countdown_frequency(count: int) -> float:
return 440.0 + float(clampi(count, 1, 9)) * 55.0
func _play_tone(frequency: float, duration: float, volume: float) -> void:
if not enabled or frequency <= 0.0 or duration <= 0.0 or volume <= 0.0:
return
var stream := AudioStreamWAV.new()
stream.format = AudioStreamWAV.FORMAT_16_BITS
stream.mix_rate = SAMPLE_RATE
stream.stereo = false
stream.data = _tone_data(frequency, duration, volume)
var player := AudioStreamPlayer.new()
player.stream = stream
add_child(player)
player.finished.connect(player.queue_free)
player.play()
func _engine_stream() -> AudioStreamWAV:
var stream := AudioStreamWAV.new()
stream.format = AudioStreamWAV.FORMAT_16_BITS
stream.mix_rate = SAMPLE_RATE
stream.stereo = false
stream.loop_mode = AudioStreamWAV.LOOP_FORWARD
stream.data = _tone_data(92.0, 1.0, 0.65)
stream.loop_end = SAMPLE_RATE
return stream
func _tone_data(frequency: float, duration: float, volume: float) -> PackedByteArray:
var frames := maxi(1, int(duration * SAMPLE_RATE))
var data := PackedByteArray()
data.resize(frames * 2)
for index in frames:
var envelope := minf(1.0, float(index) / 256.0) * minf(1.0, float(frames - index) / 1024.0)
var sample := int(sin(TAU * frequency * float(index) / SAMPLE_RATE) * volume * envelope * 32767.0)
if sample < 0:
sample += 65536
data[index * 2] = sample & 0xff
data[index * 2 + 1] = (sample >> 8) & 0xff
return data
+22
View File
@@ -0,0 +1,22 @@
extends Node
# Autoload: drops Engine.max_fps while the window is unfocused, so an idle
# background window doesn't keep rendering at whatever uncapped rate the
# hardware can hit. Independent of — and complementary to — the per-menu
# refresh-rate cap in main_menu.gd/settings_menu.gd, which only covers menu
# screens; this covers every scene, including gameplay.
const BACKGROUND_FPS := 30
# 0 means "uncapped"; also what we restore to if focus is lost before any
# menu/gameplay scene has had a chance to set its own cap.
var _foreground_max_fps := 0
func _notification(what: int) -> void:
match what:
NOTIFICATION_APPLICATION_FOCUS_OUT:
_foreground_max_fps = Engine.max_fps
Engine.max_fps = BACKGROUND_FPS
NOTIFICATION_APPLICATION_FOCUS_IN:
Engine.max_fps = _foreground_max_fps
+1
View File
@@ -0,0 +1 @@
uid://kkge43vtwhyv
+73 -1
View File
@@ -18,6 +18,63 @@ const MAX_SPEED := 32.0
var _boundary: ArenaBoundary
var _trail: GPUParticles3D
@onready var visual: Node3D = $Visual
var _pending_teleport: Transform3D
var _has_pending_teleport := false
var _pending_teleport_linear_velocity := Vector3.ZERO
var _pending_teleport_angular_velocity := Vector3.ZERO
var _pending_teleport_has_velocity := false
# Queues an authoritative teleport, applied at the top of the next
# _integrate_forces — the only Jolt-safe place to write state.transform
# directly (see GameMode._reset_body / task 0.15) — instead of racing the
# physics step via set_deferred("global_transform", ...).
func queue_teleport(to: Transform3D) -> void:
_pending_teleport = to
_has_pending_teleport = true
_pending_teleport_has_velocity = false
# Kept parallel to Ship's network correction hook. A locally predicted ball
# must resume from the authoritative velocity after a correction; gameplay
# resets still deliberately use queue_teleport() and zero both velocities.
# The queued-but-not-yet-applied teleport target, or null when none is
# pending. queue_teleport() defers the actual write to the next
# _integrate_forces (task 0.15), so global_transform still reads the OLD pose
# in between — anything that needs to broadcast where a body is ABOUT to be
# (networked_match.gd's kickoff) must read this instead, or it ships the
# pre-reset position and corrects it a tick later.
func get_pending_teleport():
return _pending_teleport if _has_pending_teleport else null
func queue_teleport_with_velocity(to: Transform3D, new_linear_velocity: Vector3, new_angular_velocity: Vector3) -> void:
_pending_teleport = to
_pending_teleport_linear_velocity = new_linear_velocity
_pending_teleport_angular_velocity = new_angular_velocity
_pending_teleport_has_velocity = true
_has_pending_teleport = true
# -1 = use the real linear_velocity (default; see _physics_process below).
# A frozen remote ball (Phase 4) holds zero velocity — Godot/Jolt zeroes and
# ignores velocity writes on frozen bodies — so the trail needs a
# presentation-only speed fed in from outside instead of reading physics
# state that will never reflect the ball's true remote motion.
var _visual_speed_override: float = -1.0
# Prediction correction hook: exactly like Ship's visual offset, but kept
# here so a locally predicted ball can move its collider to authority while
# the mesh catches up over a short presentation-only decay.
var net_visual_offset := Vector3.ZERO
const NET_VISUAL_OFFSET_DECAY := 0.88
const MAX_NET_VISUAL_OFFSET := 0.4
func set_visual_speed(speed: float) -> void:
_visual_speed_override = speed
func _ready() -> void:
@@ -31,8 +88,15 @@ func _ready() -> void:
func _physics_process(_delta: float) -> void:
if net_visual_offset != Vector3.ZERO:
net_visual_offset = net_visual_offset.limit_length(MAX_NET_VISUAL_OFFSET)
net_visual_offset *= pow(NET_VISUAL_OFFSET_DECAY, _delta * 60.0)
if net_visual_offset.length_squared() < 0.0001:
net_visual_offset = Vector3.ZERO
visual.position = net_visual_offset
if _trail:
var speed_ratio := clampf(linear_velocity.length() / MAX_SPEED, 0.0, 1.0)
var speed := _visual_speed_override if _visual_speed_override >= 0.0 else linear_velocity.length()
var speed_ratio := clampf(speed / MAX_SPEED, 0.0, 1.0)
_trail.emitting = speed_ratio > 0.12
_trail.amount_ratio = smoothstep(0.12, 1.0, speed_ratio)
@@ -68,6 +132,14 @@ func _build_trail() -> void:
func _integrate_forces(state: PhysicsDirectBodyState3D) -> void:
if _has_pending_teleport:
_has_pending_teleport = false
state.transform = _pending_teleport
state.linear_velocity = _pending_teleport_linear_velocity if _pending_teleport_has_velocity else Vector3.ZERO
state.angular_velocity = _pending_teleport_angular_velocity if _pending_teleport_has_velocity else Vector3.ZERO
_pending_teleport_has_velocity = false
reset_physics_interpolation()
if _boundary:
var pull := _boundary.get_surface_pull(
global_position, wall_pull_strength, wall_pull_range,
+153
View File
@@ -0,0 +1,153 @@
class_name ConnectionLeaseClient
extends Node
const AssignmentState = preload("res://scripts/assignment_state.gd")
signal reconciliation_failed(reason: String)
const CLAIMED := "claimed"
const UNAVAILABLE := "unavailable"
const REJECTED := "rejected"
var _base_url := ""
var _workload_token := ""
var _match_id := ""
var _server_id := ""
var _pending: Array[Dictionary] = []
var _processing := false
func configure(base_url: String, workload_token: String, match_id: String, server_id: String) -> bool:
base_url = base_url.strip_edges().trim_suffix("/")
workload_token = workload_token.strip_edges()
if not valid_configuration(base_url, workload_token, match_id, server_id):
return false
_base_url = base_url
_workload_token = workload_token
_match_id = match_id
_server_id = server_id
return true
# Admission awaits one bounded request only. If the control plane is down, the
# same process may continue using its local generation and this exact event is
# retained ahead of every later disconnect/reconnect for ordered reconciliation.
func claim(player_id: String, expected_generation: int) -> Dictionary:
if not AssignmentState.is_valid_opaque_id(player_id) or expected_generation < 0:
return {"status": REJECTED}
var event := _connect_event(player_id, expected_generation)
if _processing or not _pending.is_empty():
if expected_generation == 0:
return {"status": REJECTED}
_pending.append(event)
_start_processing()
return {"status": UNAVAILABLE, "generation": expected_generation + 1}
var response := await _send(event, true)
if String(response.get("status", "")) == UNAVAILABLE:
if expected_generation == 0:
return {"status": REJECTED}
_pending.append(event)
_start_processing()
return {"status": UNAVAILABLE, "generation": expected_generation + 1}
return response
func record_disconnect(player_id: String, generation: int) -> void:
if not AssignmentState.is_valid_opaque_id(player_id) or generation < 1:
return
_pending.append(_disconnect_event(player_id, generation))
_start_processing()
func _start_processing() -> void:
if _processing or _pending.is_empty() or not is_inside_tree():
return
_process_pending()
func _process_pending() -> void:
_processing = true
while not _pending.is_empty() and is_inside_tree():
var event := _pending[0]
var response := await _send(event)
var status := String(response.get("status", ""))
if status == CLAIMED:
_pending.pop_front()
continue
if status == REJECTED:
reconciliation_failed.emit("durable connection lease conflict")
_processing = false
return
await get_tree().create_timer(1.0).timeout
_processing = false
func _send(event: Dictionary, allow_recovery := false) -> Dictionary:
var request := HTTPRequest.new()
request.timeout = 1.0
add_child(request)
var operation := String(event["operation"])
var endpoint := "%s/v1/servers/%s/%s" % [_base_url, _server_id.uri_encode(), operation]
var start_error := request.request(endpoint, [
"Authorization: Bearer " + _workload_token,
"Content-Type: application/json",
"Idempotency-Key: " + String(event["key"]),
], HTTPClient.METHOD_POST, JSON.stringify(event["payload"]))
if start_error != OK:
request.queue_free()
return {"status": UNAVAILABLE}
var raw: Array = await request.request_completed
request.queue_free()
return classify_response(operation, int(event["generation"]), int(raw[0]), int(raw[1]), raw[3], allow_recovery)
func _connect_event(player_id: String, expected_generation: int) -> Dictionary:
return {
"operation": "connect",
"generation": expected_generation,
"key": event_key(_match_id, player_id, "connect", expected_generation),
"payload": {"player_id": player_id, "expected_generation": expected_generation},
}
func _disconnect_event(player_id: String, generation: int) -> Dictionary:
return {
"operation": "disconnect",
"generation": generation,
"key": event_key(_match_id, player_id, "disconnect", generation),
"payload": {"player_id": player_id, "generation": generation},
}
static func classify_response(operation: String, generation: int, request_result: int, response_code: int, body: PackedByteArray, allow_recovery := false) -> Dictionary:
if request_result != HTTPRequest.RESULT_SUCCESS or response_code == 0 or response_code == 429 or response_code >= 500:
return {"status": UNAVAILABLE}
if operation == "disconnect" and response_code == 204:
return {"status": CLAIMED, "generation": generation}
if operation == "connect" and response_code == 200:
var decoded = JSON.parse_string(body.get_string_from_utf8())
if decoded is Dictionary and _valid_generation(decoded.get("generation")):
var claimed_generation := int(decoded["generation"])
if claimed_generation == generation + 1 or (allow_recovery and generation == 0 and claimed_generation > 1):
return {"status": CLAIMED, "generation": claimed_generation}
return {"status": REJECTED}
static func _valid_generation(value: Variant) -> bool:
if value is int:
return int(value) >= 1
if value is float:
return is_finite(float(value)) and float(value) >= 1.0 and float(value) == floor(float(value)) and float(value) <= 9007199254740991.0
return false
static func event_key(match_id: String, player_id: String, operation: String, generation: int) -> String:
return "server-lease-" + (match_id + "\n" + player_id + "\n" + operation + "\n" + str(generation)).sha256_text()
static func valid_configuration(base_url: String, workload_token: String, match_id: String, server_id: String) -> bool:
if not (base_url.begins_with("http://") or base_url.begins_with("https://")) or base_url.contains("\n") or base_url.contains("\r") or base_url.contains("?") or base_url.contains("#") or base_url.contains("@"):
return false
if workload_token.is_empty() or workload_token.contains("\n") or workload_token.contains("\r"):
return false
return AssignmentState.is_valid_opaque_id(match_id) and AssignmentState.is_valid_opaque_id(server_id)
+889
View File
@@ -0,0 +1,889 @@
extends Node
# Authenticated HTTP boundary for matchmaking. ENet/Steam carries the match
# itself; this client only handles queue/proposal control-plane state.
signal request_succeeded(operation: String, payload: Dictionary)
signal request_failed(operation: String, http_code: int, detail: String)
signal session_expired()
signal probe_challenge_received(region: String, nonce_base64: String)
signal probe_recorded(region: String, server_rtt_ms: int)
signal session_changed(player_id: String)
signal websocket_event(event: Dictionary)
signal websocket_status_changed(status: String)
signal assignment_connection_started(assignment: AssignmentState)
signal assignment_connection_failed(detail: String)
const DEFAULT_BASE_URL := "http://127.0.0.1:8080"
# Release builds must point at the real control plane rather than a developer's
# loopback. The environment variable is read at startup so the same binary can
# be pointed at a staging or production endpoint without a rebuild.
const BASE_URL_ENV := "COSMIC_CLASH_CONTROL_PLANE_URL"
const PERSIST_PATH := "user://matchmaking_state.cfg"
const AUTHORITATIVE_RECOVERY_INTERVAL_SECONDS := 5.0
var base_url := DEFAULT_BASE_URL
var access_token := ""
var auth_expired := false
var player_id := ""
var session_expires_at := ""
var state: MatchmakingState
var ranked_profile: RankedProfileState
var assignment: AssignmentState
var _request: HTTPRequest
var _operation := ""
var _last_queue_create: Dictionary = {}
var _last_mutation: Dictionary = {}
var _last_mutation_retryable := false
var _websocket: WebSocketPeer
var _websocket_status := "DISCONNECTED"
var _websocket_retry_seconds := 0.0
var _websocket_backoff := 1.0
var _authoritative_recovery_seconds := AUTHORITATIVE_RECOVERY_INTERVAL_SECONDS
var _pending_proposal_id := ""
var _pending_assignment_match_id := ""
var _pending_resync_resource_id := ""
# The final wiring step of the matchmaking pipeline: once state.phase reaches
# ASSIGNED, the client must actually start the game transport. connect_to_assignment()
# already existed with correct validation/signal behavior, but nothing ever
# called it -- a player would sit on "Your match server is ready" forever.
# These two fields defer the connect attempt until the assignment fetch
# (triggered independently, earlier, by ASSIGNMENT_READY) has actually
# completed, and prevent a duplicate/replayed ASSIGNED update from firing a
# second connection attempt for the same match.
var _pending_connect_match_id := ""
var _connect_attempted_match_id := ""
func _ready() -> void:
state = MatchmakingState.new()
ranked_profile = RankedProfileState.new()
assignment = AssignmentState.new()
_load_persisted_state()
state.changed.connect(_persist_state)
_request = HTTPRequest.new()
_request.timeout = 10.0
add_child(_request)
_request.request_completed.connect(_on_request_completed)
state.resync_required.connect(_on_resync_required)
_websocket = WebSocketPeer.new()
assignment_connection_failed.connect(_on_assignment_connection_failed)
NetworkManager.connection_failed.connect(_on_network_connection_failed)
# Covers §8.43's "failed reconnect UX": connect_to_assignment()'s own
# synchronous failures (assignment missing/expired, invalid endpoint,
# NetworkManager.join() erroring immediately) previously only emitted
# assignment_connection_failed -- a signal nothing in the client actually
# listened to. state.phase would stay stuck at ASSIGNED, the UI would keep
# showing "Your match server is ready" forever, and there was no way back to
# a fresh search.
func _on_assignment_connection_failed(detail: String) -> void:
state.fail(detail)
# The likelier real-world failure than the synchronous one above:
# NetworkManager.join() returns OK immediately (the attempt started), but the
# actual ENet handshake fails asynchronously later -- unreachable server,
# refused connection, ENet's own ~5s connect timeout. This is exactly the gap
# main_menu.gd's own _on_connection_failed exists to cover for the direct-join
# flow (see its header comment); nothing covered it for a matchmaking-driven
# connect. Guarded to CONNECTING so this never reacts to an unrelated
# connection_failed, such as one belonging to main_menu.gd's own direct join.
func _on_network_connection_failed() -> void:
if state.phase == MatchmakingState.CONNECTING:
state.fail("Unable to connect to the match server")
func _process(_delta: float) -> void:
if not auth_expired and is_session_expired(session_expires_at):
_expire_session()
if _websocket == null:
return
_websocket.poll()
var ready_state := _websocket.get_ready_state()
if ready_state == WebSocketPeer.STATE_OPEN:
_websocket_retry_seconds = 0.0
_websocket_backoff = 1.0
_set_websocket_status("CONNECTED")
while _websocket.get_available_packet_count() > 0:
_handle_websocket_packet(_websocket.get_packet())
elif ready_state == WebSocketPeer.STATE_CONNECTING:
_set_websocket_status("CONNECTING")
elif ready_state == WebSocketPeer.STATE_CLOSED:
_set_websocket_status("DISCONNECTED")
if not auth_expired and is_valid_access_token(access_token):
_websocket_retry_seconds -= _delta
if _websocket_retry_seconds <= 0.0:
_websocket_retry_seconds = _websocket_backoff
_websocket_backoff = minf(_websocket_backoff * 2.0, 30.0)
connect_event_stream()
if not _pending_proposal_id.is_empty() and _operation.is_empty() and not player_id.is_empty():
var proposal_id := _pending_proposal_id
_pending_proposal_id = ""
recover_proposal(proposal_id)
elif not _pending_assignment_match_id.is_empty() and _operation.is_empty() and not player_id.is_empty():
var match_id := _pending_assignment_match_id
_pending_assignment_match_id = ""
fetch_assignment(match_id)
if not _pending_connect_match_id.is_empty() and _assignment_ready_for(_pending_connect_match_id):
var match_id := _pending_connect_match_id
_pending_connect_match_id = ""
_connect_attempted_match_id = match_id
connect_to_assignment()
_poll_authoritative_recovery(_delta)
# The assignment fetch (triggered independently by ASSIGNMENT_READY, which
# always precedes ASSIGNED) and the ASSIGNED transition that should start the
# transport can arrive in either order. This is the shared readiness check
# both _connect_when_assigned and the deferred _process retry above use.
func _assignment_ready_for(match_id: String) -> bool:
return assignment != null and assignment.available and assignment.match_id == match_id and _assignment_is_fresh(assignment)
# Starts (or defers, if the assignment fetch triggered by the earlier
# ASSIGNMENT_READY event hasn't completed yet) the game transport once the
# ticket-state machine reaches ASSIGNED. connect_to_assignment() itself
# already existed with full validation and failure signalling; nothing ever
# called it, so a player reaching "Your match server is ready" never actually
# connected. _connect_attempted_match_id guards against a duplicate/replayed
# ASSIGNED update firing a second connection attempt for the same match.
func _connect_when_assigned(match_id: String) -> void:
if state.phase != MatchmakingState.ASSIGNED or not is_valid_resource_id(match_id) or match_id == _connect_attempted_match_id:
return
if _assignment_ready_for(match_id):
_connect_attempted_match_id = match_id
connect_to_assignment()
else:
_pending_connect_match_id = match_id
# configured_base_url resolves the endpoint this build should use, preferring
# explicit configuration over the loopback development default.
static func configured_base_url() -> String:
var configured := OS.get_environment(BASE_URL_ENV).strip_edges()
if is_valid_base_url(configured):
return configured
return DEFAULT_BASE_URL
# has_session reports whether matchmaking requests can be made at all. Without
# it every request fails ERR_UNAUTHORIZED at the first guard in _start_request.
func has_session() -> bool:
return not access_token.is_empty() and not is_session_expired(session_expires_at)
func configure(url: String, token: String) -> bool:
var normalized := url.strip_edges().trim_suffix("/")
var normalized_token := token.strip_edges()
if not is_valid_base_url(normalized) or not is_valid_access_token(normalized_token):
return false
base_url = normalized
access_token = normalized_token
session_expires_at = ""
auth_expired = false
if _websocket != null:
connect_event_stream()
return true
func connect_event_stream() -> Error:
if not is_valid_access_token(access_token) or auth_expired or not is_valid_base_url(base_url):
return ERR_UNAUTHORIZED
var socket_url := websocket_url(base_url) + "/v1/events"
_websocket = WebSocketPeer.new()
# Godot 4.7 moved handshake headers onto WebSocketPeer; the second
# connect_to_url argument is TLSOptions, not an HTTP header array. Keep the
# bearer token in the authenticated handshake without putting it in the URL.
_websocket.handshake_headers = PackedStringArray(["Authorization: Bearer " + access_token])
var err := _websocket.connect_to_url(socket_url)
if err != OK:
_set_websocket_status("DISCONNECTED")
return err
_websocket_retry_seconds = 0.0
_set_websocket_status("CONNECTING")
return OK
func disconnect_event_stream() -> void:
if _websocket != null:
_websocket.close()
_websocket_retry_seconds = 0.0
_websocket_backoff = 1.0
_set_websocket_status("DISCONNECTED")
static func websocket_url(url: String) -> String:
if url.begins_with("https://"):
return "wss://" + url.trim_prefix("https://")
if url.begins_with("http://"):
return "ws://" + url.trim_prefix("http://")
return ""
func queue_create(ticket_id: String, playlist: String, client_build: String, protocol_version: int) -> Error:
if not is_valid_resource_id(ticket_id) or (playlist != "casual" and playlist != "ranked") or client_build.is_empty() or protocol_version < 1:
return ERR_INVALID_PARAMETER
if not state.begin_queue(ticket_id, playlist):
return ERR_INVALID_PARAMETER
var key := _idempotency_key("queue")
_last_queue_create = {"ticket_id": ticket_id, "playlist": playlist, "client_build": client_build, "protocol_version": protocol_version, "key": key}
var err := _start_request("queue_create", HTTPClient.METHOD_POST, "/v1/queue", {"ticket_id": ticket_id, "playlist": playlist, "client_build": client_build, "protocol_version": protocol_version}, key)
if err != OK:
state.fail("Could not start matchmaking: %s" % error_string(err))
return err
# Regional latency probing. The backend issues a single-use nonce, the client
# echoes it back with its opaque platform location, and the backend derives the
# round trip from its own timestamps -- no client-measured latency is accepted.
#
# Until a ticket has RTT evidence for at least one region the matcher will not
# consider it (server/domain.validCandidate requires a non-empty map), so this
# has to complete before searching is meaningful.
const PROBE_REGIONS := ["EU", "NA"]
func request_probe_challenge(region: String) -> Error:
if not is_valid_probe_region(region):
return ERR_INVALID_PARAMETER
return _start_request("probe_challenge_" + region, HTTPClient.METHOD_POST, "/v1/probes/%s/challenge" % region, {}, "")
func submit_probe_answer(region: String, nonce_base64: String, opaque_location_base64: String) -> Error:
if not is_valid_probe_region(region) or nonce_base64.is_empty() or opaque_location_base64.is_empty():
return ERR_INVALID_PARAMETER
return _start_request("probe_answer_" + region, HTTPClient.METHOD_POST, "/v1/probes/%s" % region, {
"nonce": nonce_base64,
"opaque_location": opaque_location_base64,
}, "")
static func is_valid_probe_region(region: String) -> bool:
return region == "EU" or region == "NA"
# The platform location is opaque to us by design: the backend treats it as a
# blob and never derives placement from anything the client measured. Without a
# Steam runtime there is nothing to report, so send a stable non-empty marker
# rather than failing the probe -- the RTT is what actually matters and that is
# measured by the backend either way.
static func opaque_location_payload() -> String:
if Engine.has_singleton("Steam"):
var steam := Engine.get_singleton("Steam")
if steam.has_method("getLocalPingLocation"):
var location = steam.call("getLocalPingLocation")
if location is String and not String(location).is_empty():
return Marshalls.utf8_to_base64(String(location))
return Marshalls.utf8_to_base64("no-platform-ping-location")
func login_steam(web_api_ticket: String) -> Error:
if not is_valid_web_api_ticket(web_api_ticket):
return ERR_INVALID_PARAMETER
return _start_request("steam_session", HTTPClient.METHOD_POST, "/v1/session/steam", {"web_api_ticket": web_api_ticket}, "")
func retry_queue_create() -> Error:
if _last_queue_create.is_empty() or not _last_queue_create.has("ticket_id"):
return ERR_INVALID_DATA
var ticket_id := String(_last_queue_create["ticket_id"])
var playlist := String(_last_queue_create["playlist"])
if not state.begin_queue(ticket_id, playlist):
return ERR_INVALID_PARAMETER
var err := _start_request("queue_create", HTTPClient.METHOD_POST, "/v1/queue", {"ticket_id": ticket_id, "playlist": playlist, "client_build": String(_last_queue_create["client_build"]), "protocol_version": int(_last_queue_create["protocol_version"])}, String(_last_queue_create["key"]))
if err != OK:
state.fail("Could not retry matchmaking: %s" % error_string(err))
return err
func can_retry_queue_create() -> bool:
return not _last_queue_create.is_empty() and state.phase == MatchmakingState.FAILED and String(_last_queue_create.get("ticket_id", "")) == state.ticket_id
func retry_last_mutation() -> Error:
if not can_retry_last_mutation():
return ERR_INVALID_DATA
var request := _last_mutation.duplicate(true)
return _start_request(String(request["operation"]), int(request["method"]), String(request["path"]), request["payload"], String(request["key"]), int(request["expected_revision"]))
func can_retry_last_mutation() -> bool:
return _last_mutation_retryable and not _last_mutation.is_empty() and _operation.is_empty() and not auth_expired and is_valid_access_token(access_token)
func recover_queue(ticket_id: String) -> Error:
if not is_valid_resource_id(ticket_id):
return ERR_INVALID_PARAMETER
return _start_request("queue_recover", HTTPClient.METHOD_GET, "/v1/queue/" + ticket_id, {}, "")
func recover_proposal(proposal_id: String) -> Error:
if not is_valid_resource_id(proposal_id):
return ERR_INVALID_PARAMETER
return _start_request("proposal_recover", HTTPClient.METHOD_GET, "/v1/proposals/" + proposal_id, {}, "")
static func resync_target(resource_id: String, ticket_id: String, proposal_id: String, proposal_open: bool) -> String:
if resource_id == ticket_id and not ticket_id.is_empty():
return ticket_id
if resource_id == proposal_id and not proposal_id.is_empty():
return proposal_id if proposal_open else ticket_id
return ""
func fetch_ranked_profile() -> Error:
return _start_request("ranked_profile", HTTPClient.METHOD_GET, "/v1/profile/ranked", {}, "")
func fetch_assignment(match_id: String) -> Error:
if not is_valid_resource_id(match_id) or player_id.is_empty():
return ERR_INVALID_PARAMETER
return _start_request("assignment", HTTPClient.METHOD_GET, "/v1/assignments/" + match_id, {}, "")
# Starts the assigned game transport only after AssignmentState has validated
# the complete player-scoped manifest. The signed authorisation is passed to
# MatchNet's hello RPC, never appended to the endpoint URL or logged. Server
# admission remains authoritative; this method only owns the client-side
# readiness/transport boundary.
func connect_to_assignment() -> Error:
if assignment == null or not assignment.available or not _assignment_is_fresh(assignment):
var unavailable_detail := "Match assignment is unavailable or expired"
assignment_connection_failed.emit(unavailable_detail)
return ERR_UNAUTHORIZED
var endpoint := _split_assignment_endpoint(assignment.endpoint)
if endpoint.is_empty():
var invalid_detail := "Match assignment endpoint is invalid"
assignment_connection_failed.emit(invalid_detail)
return ERR_INVALID_PARAMETER
var transport := NetworkManager.TRANSPORT_ENET if assignment.transport == "enet" else NetworkManager.TRANSPORT_STEAM
MatchNet.join_authorisation = assignment.join_authorisation
state.mark_connecting()
var err := NetworkManager.join(String(endpoint["host"]), int(endpoint["port"]), transport)
if err != OK:
MatchNet.join_authorisation = ""
assignment_connection_failed.emit("Unable to connect to match server")
return err
assignment_connection_started.emit(assignment)
return OK
static func _assignment_is_fresh(value: AssignmentState) -> bool:
if value == null or not AssignmentState.is_valid_expiry_timestamp(value.expires_at):
return false
var expiry := Time.get_unix_time_from_datetime_string(value.expires_at)
return expiry > Time.get_unix_time_from_system()
static func _split_assignment_endpoint(value: String) -> Dictionary:
if not AssignmentState._valid_endpoint(value):
return {}
var separator := value.rfind(":")
return {"host": value.substr(0, separator), "port": int(value.substr(separator + 1))}
func heartbeat(ticket_id: String, expected_revision: int) -> Error:
if not is_valid_resource_id(ticket_id) or expected_revision < 0:
return ERR_INVALID_PARAMETER
return _start_request("queue_heartbeat", HTTPClient.METHOD_POST, "/v1/queue/%s/heartbeat" % ticket_id, {}, _idempotency_key("heartbeat"), expected_revision)
func cancel_queue(ticket_id: String, expected_revision: int) -> Error:
if not is_valid_resource_id(ticket_id) or expected_revision < 0 or not state.can_cancel():
return ERR_INVALID_PARAMETER
return _start_request("queue_cancel", HTTPClient.METHOD_POST, "/v1/queue/%s/cancel" % ticket_id, {}, _idempotency_key("cancel"), expected_revision)
func respond_to_proposal(proposal_id: String, accept: bool, expected_revision: int) -> Error:
if not is_valid_resource_id(proposal_id) or expected_revision < 0:
return ERR_INVALID_PARAMETER
var action := "accept" if accept else "decline"
return _start_request("proposal_" + action, HTTPClient.METHOD_POST, "/v1/proposals/%s/%s" % [proposal_id, action], {}, _idempotency_key("proposal"), expected_revision)
static func is_valid_base_url(url: String) -> bool:
if url.is_empty() or url.contains(" ") or url.contains("\r") or url.contains("\n") or url.contains("?") or url.contains("#") or url.contains("@") or url.ends_with("/"):
return false
return url.begins_with("http://") or url.begins_with("https://")
static func is_valid_web_api_ticket(ticket: String) -> bool:
return not ticket.is_empty() and ticket.length() <= 4096 and not ticket.contains("\r") and not ticket.contains("\n")
static func is_valid_access_token(token: String) -> bool:
var separator := token.find(":")
return separator > 0 and separator < token.length() - 1 and token.length() <= 4096 and not token.contains("\r") and not token.contains("\n")
static func is_session_expired(expires_at: String, now_unix: int = -1) -> bool:
if expires_at.is_empty():
return false
if not is_valid_rfc3339_timestamp(expires_at):
return true
var expiry_unix := Time.get_unix_time_from_datetime_string(expires_at)
if expiry_unix < 0:
return true
var current_unix := now_unix
if current_unix < 0:
current_unix = int(Time.get_unix_time_from_system())
return expiry_unix <= current_unix
static func is_valid_session_response(payload: Dictionary) -> bool:
if not payload.has("expires_at") or not payload["expires_at"] is String:
return false
var expires_at := String(payload["expires_at"])
return is_valid_rfc3339_timestamp(expires_at) and not is_session_expired(expires_at)
static func is_valid_rfc3339_timestamp(value: String) -> bool:
if value.is_empty():
return false
var timestamp_pattern := RegEx.create_from_string("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}(?:\\.\\d+)?(?:Z|[+-]\\d{2}:\\d{2})$")
if timestamp_pattern.search(value) == null:
return false
var year := int(value.substr(0, 4))
var month := int(value.substr(5, 2))
var day := int(value.substr(8, 2))
var hour := int(value.substr(11, 2))
var minute := int(value.substr(14, 2))
var second := int(value.substr(17, 2))
if month < 1 or month > 12 or hour > 23 or minute > 59 or second > 59:
return false
var days_in_month := [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
var leap_year := year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
if leap_year:
days_in_month[1] = 29
if day < 1 or day > days_in_month[month - 1]:
return false
var timezone_index := value.find("+", 19)
if timezone_index < 0:
timezone_index = value.find("-", 19)
if timezone_index >= 0:
var offset_hour := int(value.substr(timezone_index + 1, 2))
var offset_minute := int(value.substr(timezone_index + 4, 2))
if offset_hour > 23 or offset_minute > 59:
return false
return true
static func is_valid_resource_id(value: String) -> bool:
if value.length() < 16 or value.length() > 128:
return false
var resource_pattern := RegEx.create_from_string("^[A-Za-z0-9_-]+$")
return resource_pattern.search(value) != null
static func is_retryable_mutation_response(response_code: int) -> bool:
return response_code == 0 or response_code == HTTPClient.RESPONSE_REQUEST_TIMEOUT or response_code == HTTPClient.RESPONSE_TOO_MANY_REQUESTS or response_code >= 500
static func should_recover_queue_after_conflict(operation: String, response_code: int, ticket_id: String) -> bool:
return response_code == HTTPClient.RESPONSE_CONFLICT and operation in ["queue_heartbeat", "queue_cancel"] and not ticket_id.is_empty()
static func normalize_ticket(payload: Dictionary) -> Dictionary:
var result := payload.duplicate(true)
for pair in [["enqueued_at", "enqueued_at_unix"], ["expires_at", "expires_at_unix"]]:
var source_key: String = pair[0]
var target_key: String = pair[1]
if not result.has(source_key):
continue
if not result[source_key] is String or not is_valid_rfc3339_timestamp(String(result[source_key])):
result[target_key] = -1
else:
result[target_key] = Time.get_unix_time_from_datetime_string(String(result[source_key]))
return result
static func normalize_proposal(payload: Dictionary) -> Dictionary:
var result := payload.duplicate(true)
if not result.has("expires_at"):
return result
if not result["expires_at"] is String or not is_valid_rfc3339_timestamp(String(result["expires_at"])):
result["expires_at_unix"] = -1
else:
result["expires_at_unix"] = int(Time.get_unix_time_from_datetime_string(String(result["expires_at"])))
return result
func _start_request(operation: String, method: HTTPClient.Method, path: String, payload: Dictionary, idempotency_key: String, expected_revision: int = -1) -> Error:
if _request == null or not _operation.is_empty() or not is_valid_base_url(base_url):
return ERR_BUSY if not _operation.is_empty() else ERR_UNAUTHORIZED
if operation != "steam_session" and access_token.is_empty():
return ERR_UNAUTHORIZED
if operation != "steam_session" and is_session_expired(session_expires_at):
_expire_session()
return ERR_UNAUTHORIZED
var headers := PackedStringArray(["Accept: application/json"])
if operation != "steam_session":
headers.append("Authorization: Bearer " + access_token)
if not idempotency_key.is_empty():
headers.append("Idempotency-Key: " + idempotency_key)
if expected_revision >= 0:
headers.append("If-Match-Revision: %d" % expected_revision)
var body := "" if payload.is_empty() else JSON.stringify(payload)
_operation = operation
var err := _request.request(base_url + path, headers, method, body)
if err != OK:
_operation = ""
return err
if not idempotency_key.is_empty():
_last_mutation = {"operation": operation, "method": method, "path": path, "payload": payload.duplicate(true), "key": idempotency_key, "expected_revision": expected_revision}
_last_mutation_retryable = false
return OK
func _expire_session() -> void:
if auth_expired:
return
access_token = ""
auth_expired = true
disconnect_event_stream()
state.fail("Session expired; sign in again")
ranked_profile.set_error("Session expired; sign in again")
session_expired.emit()
func _on_request_completed(result: HTTPRequest.Result, response_code: int, _headers: PackedStringArray, body: PackedByteArray) -> void:
var operation := _operation
_operation = ""
if result != HTTPRequest.RESULT_SUCCESS:
_last_mutation_retryable = _last_mutation.get("operation", "") == operation
if operation == "ranked_profile":
ranked_profile.set_error("Ranked profile request failed")
elif operation == "queue_create":
state.fail("Control-plane request failed")
elif operation == "queue_recover" or operation == "proposal_recover":
state.set_notice("Could not refresh matchmaking state; retrying")
else:
state.set_notice("Control-plane request failed; retrying is safe")
request_failed.emit(operation, response_code, "network error")
return
var parsed = JSON.parse_string(body.get_string_from_utf8())
if not parsed is Dictionary:
_last_mutation_retryable = _last_mutation.get("operation", "") == operation
if operation == "ranked_profile":
ranked_profile.set_error("Ranked profile returned invalid JSON")
elif operation == "queue_create":
state.fail("Control-plane returned invalid JSON")
elif operation == "queue_recover" or operation == "proposal_recover":
state.set_notice("Could not refresh matchmaking state; retrying")
else:
state.set_notice("Control-plane returned invalid JSON; retrying is safe")
request_failed.emit(operation, response_code, "invalid JSON")
return
if response_code < 200 or response_code >= 300:
_last_mutation_retryable = _last_mutation.get("operation", "") == operation and is_retryable_mutation_response(response_code)
var detail := String(parsed.get("error", "request rejected"))
var recover_proposal_after_conflict := response_code == HTTPClient.RESPONSE_CONFLICT and (operation == "proposal_accept" or operation == "proposal_decline") and not state.proposal_id.is_empty()
var recover_queue_after_conflict := should_recover_queue_after_conflict(operation, response_code, state.ticket_id)
if response_code == HTTPClient.RESPONSE_UNAUTHORIZED:
access_token = ""
auth_expired = true
disconnect_event_stream()
state.fail("Session expired; sign in again")
ranked_profile.set_error("Session expired; sign in again")
session_expired.emit()
elif response_code == HTTPClient.RESPONSE_GONE and operation == "queue_recover":
state.expire("Queue ticket expired")
elif response_code == HTTPClient.RESPONSE_SERVICE_UNAVAILABLE:
state.set_notice("Matchmaking is temporarily unavailable; retrying is safe")
elif response_code == HTTPClient.RESPONSE_UPGRADE_REQUIRED and operation == "queue_create":
# Distinct from the generic queue_create failure below: retrying
# with the same client build can never succeed, so the retry
# offer must not be shown (can_retry_queue_create() checks
# _last_queue_create; clearing it here suppresses "Retry Search").
_last_queue_create = {}
state.fail("Your client is out of date -- please update to continue searching")
elif operation == "ranked_profile":
ranked_profile.set_error(detail)
elif response_code == HTTPClient.RESPONSE_NOT_FOUND and (operation == "queue_recover" or operation == "proposal_recover"):
state.fail("Matchmaking record is no longer available")
elif operation == "queue_create" or operation == "queue_recover" or operation == "proposal_recover":
state.fail(detail)
else:
state.set_notice(detail)
request_failed.emit(operation, response_code, detail)
if recover_proposal_after_conflict:
_pending_resync_resource_id = state.proposal_id
call_deferred("_run_pending_resync")
if recover_queue_after_conflict:
_pending_resync_resource_id = state.ticket_id
call_deferred("_run_pending_resync")
return
var payload: Dictionary = parsed
_last_mutation_retryable = false
if operation == "steam_session":
var returned_token := String(payload.get("access_token", ""))
var returned_player_id := String(payload.get("player_id", ""))
if not is_valid_resource_id(returned_player_id) or not is_valid_access_token(returned_token) or not is_valid_session_response(payload):
request_failed.emit(operation, response_code, "invalid session response")
return
player_id = returned_player_id
access_token = returned_token
auth_expired = false
session_expires_at = String(payload.get("expires_at", ""))
connect_event_stream()
session_changed.emit(player_id)
elif operation == "queue_create" or operation == "queue_recover" or operation == "queue_heartbeat" or operation == "queue_cancel":
if not _valid_queue_response(payload):
state.fail("Queue response contains invalid contract data")
request_failed.emit(operation, response_code, "invalid queue response")
return
if operation == "queue_create":
state.begin_queue(String(payload["ticket_id"]), String(payload.get("playlist", "")))
elif operation.begins_with("proposal_"):
if not _valid_proposal_response(payload):
state.fail("Proposal response contains an invalid proposal identifier")
request_failed.emit(operation, response_code, "invalid proposal identifier")
return
if operation.begins_with("queue_"):
if state.apply_ticket_update(normalize_ticket(payload), operation == "queue_recover"):
_queue_proposal_if_ready(payload)
_queue_assignment_if_ready(payload)
_connect_when_assigned(String(payload.get("match_id", "")))
elif operation.begins_with("proposal_"):
state.apply_proposal_update(normalize_proposal(payload))
elif operation == "ranked_profile":
if not ranked_profile.apply(payload):
request_failed.emit(operation, response_code, ranked_profile.error_message)
return
elif operation == "assignment":
if not assignment.apply(payload, player_id):
request_failed.emit(operation, response_code, assignment.error_message)
return
elif operation.begins_with("probe_challenge_"):
# Answer immediately: the nonce is single-use and short-lived, and the
# interval to this answer is exactly what the backend measures.
var challenge_region := operation.trim_prefix("probe_challenge_")
var nonce := String(payload.get("nonce", ""))
if nonce.is_empty():
request_failed.emit(operation, response_code, "probe challenge did not include a nonce")
return
probe_challenge_received.emit(challenge_region, nonce)
elif operation.begins_with("probe_answer_"):
probe_recorded.emit(operation.trim_prefix("probe_answer_"), int(payload.get("server_rtt_ms", -1)))
request_succeeded.emit(operation, payload)
if not _pending_resync_resource_id.is_empty():
call_deferred("_run_pending_resync")
func _handle_websocket_packet(packet: PackedByteArray) -> void:
var parsed = JSON.parse_string(packet.get_string_from_utf8())
if not parsed is Dictionary or not _valid_websocket_event(parsed):
websocket_status_changed.emit("INVALID_EVENT")
return
var event: Dictionary = parsed
websocket_event.emit(event)
var event_name := String(event["event"])
if event_name == "state_changed":
# Allocation and match lifecycle rows are keyed by match ID, not ticket
# ID. Recover the owner-scoped ticket projection instead of feeding the
# match revision/resource into the ticket reducer. ASSIGNMENT_READY also
# carries the durable lookup key, so the assignment fetch can follow the
# recovery request without depending on a circular assignment_changed
# notification from the assignment GET itself.
if event.has("match_id"):
var match_id := String(event["match_id"])
_on_resync_required(state.ticket_id)
if String(event["state"]) == "ASSIGNMENT_READY":
_pending_assignment_match_id = match_id
return
var update := event.duplicate(true)
update["ticket_id"] = String(event["resource_id"])
if not state.apply_ticket_update(update):
return
elif event_name == "proposal_changed":
var proposal_update := event.duplicate(true)
proposal_update["proposal_id"] = String(event["resource_id"])
if state.prepare_proposal_recovery(String(proposal_update["proposal_id"])):
state.apply_proposal_update(proposal_update)
elif event_name == "assignment_changed":
state.mark_assignment_ready()
_pending_assignment_match_id = String(event["match_id"])
elif event_name == "error":
state.set_notice("Control-plane error: %s" % String(event["code"]))
_on_resync_required(String(event["resource_id"]))
static func _valid_websocket_event(event: Dictionary) -> bool:
if not event.has("event") or not event["event"] is String or String(event["event"]).is_empty():
return false
if not event.has("revision") or not _valid_revision(event["revision"]):
return false
if not event.has("resource_id") or not event["resource_id"] is String or not is_valid_resource_id(String(event["resource_id"])):
return false
if not event.has("occurred_at") or not event["occurred_at"] is String or not is_valid_rfc3339_timestamp(String(event["occurred_at"])):
return false
var event_name := String(event["event"])
if event_name == "assignment_changed":
return event.has("match_id") and event["match_id"] is String and is_valid_resource_id(String(event["match_id"])) and event.has("server_id") and event["server_id"] is String and is_valid_resource_id(String(event["server_id"]))
if event_name == "error":
return event.has("code") and String(event["code"]) in ["REVISION_GAP", "NOT_AUTHORISED", "INVALID_STATE", "RATE_LIMITED"]
if event_name == "state_changed":
if not event.has("state") or String(event["state"]) not in ["QUEUED", "PROPOSED", "ACCEPTED", "ALLOCATING", "PROCESS_READY", "ASSIGNMENT_READY", "ASSIGNED", "CONNECTING", "LIVE", "RESULT_PENDING", "COMPLETED", "CANCELLED", "EXPIRED", "FAILED"]:
return false
if event.has("match_id"):
return event["match_id"] is String and is_valid_resource_id(String(event["match_id"])) and String(event["match_id"]) == String(event["resource_id"])
return true
if event_name == "proposal_changed":
return event.has("state") and String(event["state"]) in ["OPEN", "ACCEPTED", "DECLINED", "EXPIRED", "CANCELLED"]
return false
static func _valid_revision(value: Variant) -> bool:
if value is int:
return int(value) >= 0
if value is float:
return is_finite(float(value)) and float(value) >= 0.0 and float(value) == floor(float(value))
return false
static func _valid_response_opaque_id(payload: Dictionary, key: String) -> bool:
return payload.has(key) and payload[key] is String and is_valid_resource_id(String(payload[key]))
static func _valid_queue_response(payload: Dictionary) -> bool:
for key in ["ticket_id", "player_id", "playlist", "state", "revision", "enqueued_at", "expires_at"]:
if not payload.has(key):
return false
if not _valid_response_opaque_id(payload, "ticket_id") or not _valid_response_opaque_id(payload, "player_id"):
return false
if not payload["playlist"] is String or not String(payload["playlist"]) in ["casual", "ranked"]:
return false
if not payload["state"] is String or not String(payload["state"]) in ["QUEUED", "PROPOSED", "ACCEPTED", "ALLOCATING", "PROCESS_READY", "ASSIGNMENT_READY", "ASSIGNED", "CONNECTING", "LIVE", "RESULT_PENDING", "COMPLETED", "CANCELLED", "EXPIRED", "FAILED"]:
return false
if payload.has("match_id"):
if not payload["match_id"] is String or not is_valid_resource_id(String(payload["match_id"])):
return false
if String(payload["state"]) not in ["ALLOCATING", "PROCESS_READY", "ASSIGNMENT_READY", "ASSIGNED", "CONNECTING", "LIVE", "RESULT_PENDING", "COMPLETED", "FAILED", "CANCELLED"]:
return false
if payload.has("proposal_id"):
if not payload["proposal_id"] is String or not is_valid_resource_id(String(payload["proposal_id"])):
return false
if String(payload["state"]) != "PROPOSED":
return false
if payload.has("match_id") and payload.has("proposal_id"):
return false
if not _valid_revision(payload["revision"]):
return false
return payload["enqueued_at"] is String and is_valid_rfc3339_timestamp(String(payload["enqueued_at"])) and payload["expires_at"] is String and is_valid_rfc3339_timestamp(String(payload["expires_at"]))
func _queue_assignment_if_ready(payload: Dictionary) -> void:
if String(payload.get("state", "")) != "ASSIGNMENT_READY":
return
var match_id := String(payload.get("match_id", ""))
if is_valid_resource_id(match_id):
_pending_assignment_match_id = match_id
func _queue_proposal_if_ready(payload: Dictionary) -> void:
if String(payload.get("state", "")) != "PROPOSED":
return
var proposal_id := String(payload.get("proposal_id", ""))
if is_valid_resource_id(proposal_id) and state.prepare_proposal_recovery(proposal_id):
_pending_proposal_id = proposal_id
func _poll_authoritative_recovery(delta: float) -> void:
if auth_expired or not is_valid_access_token(access_token) or state.ticket_id.is_empty() or state.phase in [MatchmakingState.CANCELLED, MatchmakingState.EXPIRED, MatchmakingState.FAILED, MatchmakingState.COMPLETED]:
_authoritative_recovery_seconds = AUTHORITATIVE_RECOVERY_INTERVAL_SECONDS
return
_authoritative_recovery_seconds -= maxf(0.0, delta)
if _authoritative_recovery_seconds > 0.0 or not _operation.is_empty():
return
_authoritative_recovery_seconds = AUTHORITATIVE_RECOVERY_INTERVAL_SECONDS
var resource_id := state.proposal_id if state.has_open_proposal() else state.ticket_id
_run_resync(resource_id)
static func _valid_proposal_response(payload: Dictionary) -> bool:
if not _valid_response_opaque_id(payload, "proposal_id") or not payload.has("expires_at") or not payload["expires_at"] is String or not is_valid_rfc3339_timestamp(String(payload["expires_at"])) or not payload.has("participants") or not payload["participants"] is Array:
return false
var participants: Array = payload["participants"]
if participants.size() < 2 or participants.size() > 6:
return false
var seen := {}
for participant in participants:
if not participant is Dictionary:
return false
if not participant.has("player_id") or not participant["player_id"] is String or not is_valid_resource_id(String(participant["player_id"])) or seen.has(String(participant["player_id"])):
return false
if not participant.has("response") or not participant["response"] is String or not String(participant["response"]) in ["PENDING", "ACCEPTED", "DECLINED", "TIMED_OUT"]:
return false
if not participant.has("team") or not participant.has("slot") or not _valid_revision(participant["team"]) or not _valid_revision(participant["slot"]):
return false
var team := int(participant["team"])
var slot := int(participant["slot"])
if team > 1 or slot > 5 or slot / 3 != team:
return false
seen[String(participant["player_id"])] = true
return true
func _on_resync_required(resource_id: String) -> void:
if not _operation.is_empty():
_pending_resync_resource_id = resource_id
return
_run_resync(resource_id)
func _run_pending_resync() -> void:
if not _operation.is_empty() or _pending_resync_resource_id.is_empty():
return
var resource_id := _pending_resync_resource_id
_pending_resync_resource_id = ""
_run_resync(resource_id)
func _run_resync(resource_id: String) -> void:
var target := resync_target(resource_id, state.ticket_id, state.proposal_id, state.has_open_proposal())
if target == state.ticket_id and not state.ticket_id.is_empty():
recover_queue(state.ticket_id)
elif target == state.proposal_id and not state.proposal_id.is_empty():
recover_proposal(state.proposal_id)
func _set_websocket_status(status: String) -> void:
if _websocket_status == status:
return
_websocket_status = status
websocket_status_changed.emit(status)
if status == "CONNECTED":
if not state.ticket_id.is_empty() and state.phase not in [MatchmakingState.CANCELLED, MatchmakingState.EXPIRED, MatchmakingState.FAILED, MatchmakingState.LIVE, MatchmakingState.COMPLETED]:
var resource_id := state.proposal_id if state.has_open_proposal() else state.ticket_id
if _operation.is_empty():
_run_resync(resource_id)
else:
# A reconnect must not lose its authoritative recovery merely because
# the previous mutation has not acknowledged yet. The deferred path
# runs after that request completes and avoids an ERR_BUSY drop.
_pending_resync_resource_id = resource_id
func _idempotency_key(prefix: String) -> String:
return "%s-%s-%s" % [prefix, str(Time.get_ticks_usec()), str(randi())]
func _persist_state(snapshot: Dictionary) -> void:
var config := ConfigFile.new()
config.set_value("matchmaking", "snapshot", JSON.stringify(snapshot))
config.save(PERSIST_PATH)
func _load_persisted_state() -> void:
var config := ConfigFile.new()
if config.load(PERSIST_PATH) != OK:
return
var raw = config.get_value("matchmaking", "snapshot", "")
if not raw is String or String(raw).is_empty():
return
var parsed = JSON.parse_string(String(raw))
if parsed is Dictionary and not state.restore_snapshot(parsed):
state.fail("Saved matchmaking state is invalid")
+188
View File
@@ -0,0 +1,188 @@
extends ScrollContainer
# Settings screen's Controls tab: rebinds every action in InputSettings.ACTIONS
# for either device, toggles invert-pitch, and resets to the project.godot
# defaults. InputSettings owns the bindings themselves and their persistence;
# this script is only the editor for them, and deliberately keeps
# settings_menu.gd video-only.
#
# Rows are built in code rather than laid out in settings.tscn so the list stays
# derived from InputSettings.ACTIONS — adding a rebindable action means editing
# that one const, not this scene as well.
# A joypad axis has to travel this far before a capture accepts it. Resting
# stick drift is routinely a few percent off centre and would otherwise bind
# itself the instant the player opened a capture.
const AXIS_CAPTURE_THRESHOLD := 0.5
@onready var keyboard_button: Button = %KeyboardButton
@onready var controller_button: Button = %ControllerButton
@onready var status_label: Label = %StatusLabel
@onready var binding_list: VBoxContainer = %BindingList
@onready var invert_pitch_check: CheckBox = %InvertPitchCheck
@onready var reset_button: Button = %ResetButton
var _device: String = InputSettings.DEVICE_KEYBOARD
# The action currently awaiting an input event, or "" when not capturing.
var _capturing: String = ""
# action -> the row's Button, so a rebuild-free label refresh is possible and
# so capture can restore the right button's text on cancel.
var _row_buttons: Dictionary = {}
func _ready() -> void:
keyboard_button.pressed.connect(_on_device_selected.bind(InputSettings.DEVICE_KEYBOARD))
controller_button.pressed.connect(_on_device_selected.bind(InputSettings.DEVICE_JOYPAD))
invert_pitch_check.toggled.connect(_on_invert_pitch_toggled)
reset_button.pressed.connect(_on_reset_pressed)
invert_pitch_check.button_pressed = InputSettings.invert_pitch
_update_device_buttons()
_rebuild_rows()
func _on_device_selected(device: String) -> void:
_cancel_capture()
_device = device
_update_device_buttons()
_rebuild_rows()
func _update_device_buttons() -> void:
keyboard_button.button_pressed = _device == InputSettings.DEVICE_KEYBOARD
controller_button.button_pressed = _device == InputSettings.DEVICE_JOYPAD
func _rebuild_rows() -> void:
for child in binding_list.get_children():
child.queue_free()
_row_buttons.clear()
var last_group := ""
for entry in InputSettings.ACTIONS:
var group: String = entry["group"]
if group != last_group:
last_group = group
binding_list.add_child(_make_group_header(group))
var row := HBoxContainer.new()
row.add_theme_constant_override("separation", 10)
var label := Label.new()
label.text = entry["label"]
label.custom_minimum_size = Vector2(200, 0)
row.add_child(label)
var button := Button.new()
var action: String = entry["action"]
button.text = InputSettings.binding_text(action, _device)
button.custom_minimum_size = Vector2(0, 36)
button.size_flags_horizontal = Control.SIZE_EXPAND_FILL
button.clip_text = true
button.pressed.connect(_begin_capture.bind(action))
row.add_child(button)
_row_buttons[action] = button
binding_list.add_child(row)
# Re-bound after every rebuild: the rows above are new nodes each time, so
# the buttons AudioManager was tracking no longer exist.
AudioManager.bind_tree_buttons(self)
func _make_group_header(group: String) -> Label:
var header := Label.new()
header.text = group
header.add_theme_font_size_override("font_size", 18)
header.modulate = Color(1, 1, 1, 0.7)
return header
func _begin_capture(action: String) -> void:
_cancel_capture()
_capturing = action
var button: Button = _row_buttons[action]
button.text = "Press a key…" if _device == InputSettings.DEVICE_KEYBOARD else "Press a button…"
status_label.text = "Listening — press Escape to cancel."
func _cancel_capture() -> void:
if _capturing == "":
return
var action := _capturing
_capturing = ""
if _row_buttons.has(action) and is_instance_valid(_row_buttons[action]):
_row_buttons[action].text = InputSettings.binding_text(action, _device)
status_label.text = ""
# _input rather than _unhandled_input: the row Button has focus while capturing,
# and an unhandled-input handler would never see the key that Button consumes as
# its own activation. Everything consumed here is marked handled so the pending
# event cannot also re-press that button and re-enter capture.
func _input(event: InputEvent) -> void:
if _capturing == "":
return
if event.is_action_pressed("ui_cancel"):
get_viewport().set_input_as_handled()
_cancel_capture()
return
var captured := _capturable_event(event)
if captured == null:
return
get_viewport().set_input_as_handled()
var action := _capturing
_capturing = ""
var displaced := InputSettings.set_binding(action, captured)
_rebuild_rows()
if displaced.is_empty():
status_label.text = ""
else:
status_label.text = "Unbound %s — it was using the same input." % ", ".join(_labels_for(displaced))
# Returns the event to bind, or null if this event is not a legal binding for
# the device kind currently being edited. Keeping the check here means a joypad
# press can never land in the keyboard column just because that tab was open.
func _capturable_event(event: InputEvent) -> InputEvent:
if _device == InputSettings.DEVICE_KEYBOARD:
if event is InputEventKey and event.pressed and not event.echo:
var key := InputEventKey.new()
key.physical_keycode = event.physical_keycode
return key
return null
if event is InputEventJoypadButton and event.pressed:
var button := InputEventJoypadButton.new()
button.button_index = event.button_index
return button
if event is InputEventJoypadMotion and absf(event.axis_value) >= AXIS_CAPTURE_THRESHOLD:
var motion := InputEventJoypadMotion.new()
motion.axis = event.axis
motion.axis_value = signf(event.axis_value)
return motion
return null
func _labels_for(actions: PackedStringArray) -> PackedStringArray:
var out := PackedStringArray()
for action in actions:
for entry in InputSettings.ACTIONS:
if entry["action"] == action:
out.append(entry["label"])
break
return out
func _on_invert_pitch_toggled(pressed: bool) -> void:
InputSettings.invert_pitch = pressed
func _on_reset_pressed() -> void:
_cancel_capture()
InputSettings.reset_all()
invert_pitch_check.button_pressed = InputSettings.invert_pitch
_rebuild_rows()
status_label.text = "Bindings reset to defaults."
+1
View File
@@ -0,0 +1 @@
uid://dk7plirjfqvld
+21
View File
@@ -0,0 +1,21 @@
class_name EnetTransport
extends NetTransport
func transport_id() -> String:
return "enet"
func is_available() -> bool:
return true
func create_server(port: int, max_clients: int) -> Dictionary:
var peer := ENetMultiplayerPeer.new()
var err := peer.create_server(port, max_clients)
return {"error": err, "peer": peer if err == OK else null, "reason": error_string(err)}
func create_client(address: String, port: int) -> Dictionary:
var peer := ENetMultiplayerPeer.new()
var err := peer.create_client(address, port)
return {"error": err, "peer": peer if err == OK else null, "reason": error_string(err)}
+1
View File
@@ -0,0 +1 @@
uid://505pjuvqynm0
+103 -73
View File
@@ -17,16 +17,10 @@ var hud: HUDController
var ball: RigidBody3D
var ships: Array[Ship] = []
var _ship_spawn_transforms := {}
var _hit_stop_generation := 0
var _hit_stop_active := false
var _time_scale_before_hit_stop := 1.0
var _camera_rig: ShipCameraRig
var _goal_slowmo_active := false
var _time_scale_before_goal := 1.0
var _goal_in_progress := false
const GOAL_CELEBRATION_SECONDS := 1.6
const GOAL_SLOWMO_SCALE := 0.22
# Shared by modes that keep score (Match, Spectate); Free Play never
# references this or emits a score_changed signal, and HUDController relies
@@ -38,6 +32,18 @@ var score := {0: 0, 1: 0}
func _ready():
# Group lets the HUD discover the game mode for timer/score signals
add_to_group("game")
# At the default 8, a client hitching to ~20 fps runs up to 8 physics
# ticks in one rendered frame — and each of those ticks costs roughly as
# much as the frame that caused the hitch, so the client can spiral
# further behind instead of recovering. 4 trades a lower worst-case
# catch-up rate for bounded per-frame cost.
Engine.max_physics_steps_per_frame = 4
# A fresh RandomNumberGenerator defaults to a fixed internal state (unlike
# the global randf_range, which Godot auto-randomizes at startup), so an
# explicit randomize() is required unless a seed was set for reproducible
# kickoffs (see kickoff_rng_seed above).
if kickoff_rng_seed == 0:
_kickoff_rng.randomize()
for child in get_children():
if child is Arena:
arena = child
@@ -51,8 +57,9 @@ func _ready():
if not arena:
push_error("GameMode: scene has no Arena child")
return
for goal in arena.get_goals():
goal.goal_scored.connect(_handle_goal_scored)
if _owns_goal_logic():
for goal in arena.get_goals():
goal.goal_scored.connect(_handle_goal_scored)
_start()
@@ -68,6 +75,31 @@ func _start() -> void:
pass
# Virtual: whether this mode decides goals from its own local Goal sensors.
# True for every mode today. A future networked client mode overrides this
# false — it must learn a goal happened from an authoritative server message,
# not from an interpolated remote ball wandering through its local Goal
# Area3D, which would score client-side against no one.
func _owns_goal_logic() -> bool:
return true
# Virtual: whether this mode simulates and enforces its own world (escaped-
# body respawn runs locally in _physics_process). True for every mode today.
# A future networked client mode overrides this false — the server is
# authoritative for body positions, and a client respawning a body itself
# would fight that authority.
func _owns_world_simulation() -> bool:
return true
# Virtual: how long the goal cinematic holds before resuming play. Subclasses
# that want a different cadence override this instead of touching
# GOAL_CELEBRATION_SECONDS directly.
func _goal_pause_seconds() -> float:
return GOAL_CELEBRATION_SECONDS
# Virtual: the ball entered the goal owned (conceded) by `_conceding_team`.
func _on_goal_scored(_conceding_team: int) -> void:
pass
@@ -88,7 +120,14 @@ func _handle_goal_scored(conceding_team: int) -> void:
_goal_in_progress = true
_on_goal_registered(conceding_team)
await _play_goal_celebration(1 - conceding_team, conceding_team)
# A scene change (Esc, match end) queued during the celebration removes
# this node from the tree before the await chain finishes; resuming past
# that point would touch arena/hud state that is mid-teardown.
if not is_inside_tree():
return
await _on_goal_scored(conceding_team)
if not is_inside_tree():
return
_goal_in_progress = false
@@ -97,34 +136,24 @@ func _play_goal_celebration(scoring_team: int, conceding_team: int) -> void:
# real-time presentation delay between episodes.
if DisplayServer.get_name() == "headless" or not is_instance_valid(_camera_rig):
return
_restore_hit_stop()
_goal_slowmo_active = true
_time_scale_before_goal = Engine.time_scale
Engine.time_scale = minf(Engine.time_scale, GOAL_SLOWMO_SCALE)
AudioManager.play_goal()
var goal_position := Vector3.ZERO
for goal in arena.get_goals():
if goal.team == conceding_team:
goal_position = goal.global_position
break
# The cinematic camera cut itself (hard FOV change, cut to a fixed angle)
# carries the "moment" that Engine.time_scale slow-mo used to sell —
# world simulation speed is never touched, so this behaves identically
# for a future networked client watching a shared server sim.
_camera_rig.begin_goal_cut(goal_position)
if hud:
hud.show_goal_celebration(scoring_team)
await get_tree().create_timer(GOAL_CELEBRATION_SECONDS, true, false, true).timeout
await get_tree().create_timer(_goal_pause_seconds(), true, false, true).timeout
if is_instance_valid(_camera_rig):
_camera_rig.end_goal_cut()
if hud and is_instance_valid(hud):
hud.hide_goal_celebration()
# Defensive unwind: impact feedback is suppressed while goal slow-mo owns
# time scale, but restore any hit-stop that was already queued this frame.
_restore_hit_stop()
_restore_goal_slowmo()
func _restore_goal_slowmo() -> void:
if not _goal_slowmo_active:
return
Engine.time_scale = _time_scale_before_goal
_goal_slowmo_active = false
func spawn_ball() -> RigidBody3D:
@@ -136,7 +165,7 @@ func spawn_ball() -> RigidBody3D:
func spawn_ship(team: int, spawn_index: int = 0, controller: ShipController = null) -> Ship:
var ship: Ship = ship_scene.instantiate()
ship.name = "ShipTeam%d_%d" % [team, ships.size()]
ship.name = "Ship_T%d_S%d" % [team, spawn_index]
add_child(ship)
var spawns := arena.get_ship_spawns(team)
var spawn_transform := spawns[spawn_index] if spawn_index < spawns.size() else Transform3D.IDENTITY
@@ -154,8 +183,8 @@ func spawn_camera_rig(target: Ship) -> ShipCameraRig:
var rig: ShipCameraRig = CAMERA_RIG_SCENE.instantiate()
add_child(rig)
_camera_rig = rig
rig.impact_feedback.connect(AudioManager.play_impact)
rig.target = target
rig.impact_feedback.connect(_on_player_impact)
# Also wires the scene's static HUD (if any) to the same ship, rather
# than letting it guess via the "ship" group.
if hud:
@@ -163,42 +192,6 @@ func spawn_camera_rig(target: Ship) -> ShipCameraRig:
return rig
func _on_player_impact(intensity: float) -> void:
if not _goal_slowmo_active:
_run_hit_stop(intensity)
func _run_hit_stop(intensity: float) -> void:
if _goal_slowmo_active:
return
_hit_stop_generation += 1
var generation := _hit_stop_generation
if not _hit_stop_active:
_time_scale_before_hit_stop = Engine.time_scale
_hit_stop_active = true
Engine.time_scale = minf(
Engine.time_scale, lerpf(0.22, 0.06, clampf(intensity, 0.0, 1.0))
)
await get_tree().create_timer(
lerpf(0.025, 0.065, clampf(intensity, 0.0, 1.0)), true, false, true
).timeout
if generation == _hit_stop_generation:
_restore_hit_stop()
func _restore_hit_stop() -> void:
if not _hit_stop_active:
return
Engine.time_scale = _time_scale_before_hit_stop
_hit_stop_active = false
func _exit_tree() -> void:
# A scene change during the unscaled timer must never strand global time.
_restore_hit_stop()
_restore_goal_slowmo()
# Given an already-resolved (path, reaction_ticks, action_noise) — callers
# apply their own GameSettings-override logic first, which differs between
# modes (Match lets GameSettings override all three fields, Spectate only
@@ -233,6 +226,16 @@ func _record_goal(scoring_team: int) -> void:
const KICKOFF_POSITION_JITTER := 0.3
const KICKOFF_YAW_JITTER := deg_to_rad(15.0)
# Owned rather than global `randf_range`, so a fixed seed makes kickoffs
# exactly reproducible (replay logs, deterministic tests) without disturbing
# any other system's random stream.
@export var kickoff_rng_seed: int = 0:
set(value):
kickoff_rng_seed = value
if value != 0:
_kickoff_rng.seed = value
var _kickoff_rng := RandomNumberGenerator.new()
func reset_ball() -> void:
if is_instance_valid(ball):
@@ -243,28 +246,41 @@ func reset_ships() -> void:
for ship in ships:
if is_instance_valid(ship):
_reset_body(ship, _jittered(_ship_spawn_transforms[ship], KICKOFF_POSITION_JITTER, KICKOFF_YAW_JITTER))
if is_instance_valid(_camera_rig):
# _reset_body's queue_teleport defers the actual transform write to
# the ship's next _integrate_forces (task 0.15) — snapping the camera
# now would read the pre-teleport position. Wait one physics tick so
# the teleport has already landed; without this the camera would also
# smoothly chase the teleported ship across the arena instead of
# cutting with it.
await get_tree().physics_frame
if is_instance_valid(_camera_rig):
_camera_rig.snap_to_target()
func _jittered(to: Transform3D, position_jitter: float, yaw_jitter: float) -> Transform3D:
var offset := Vector3(randf_range(-position_jitter, position_jitter), 0.0, randf_range(-position_jitter, position_jitter))
var offset := Vector3(_kickoff_rng.randf_range(-position_jitter, position_jitter), 0.0, _kickoff_rng.randf_range(-position_jitter, position_jitter))
var basis := to.basis
if yaw_jitter > 0.0:
basis = basis.rotated(Vector3.UP, randf_range(-yaw_jitter, yaw_jitter))
basis = basis.rotated(Vector3.UP, _kickoff_rng.randf_range(-yaw_jitter, yaw_jitter))
return Transform3D(basis, to.origin + offset)
func _reset_body(body: RigidBody3D, to: Transform3D) -> void:
# Deferred: a RigidBody3D transform can't be set mid-physics-step
body.set_deferred("global_transform", to)
body.set_deferred("linear_velocity", Vector3.ZERO)
body.set_deferred("angular_velocity", Vector3.ZERO)
# A kickoff reset is a teleport: without this, physics interpolation
# smears the body across the arena for a frame
body.call_deferred("reset_physics_interpolation")
# Queued and applied inside the body's own _integrate_forces — the only
# Jolt-safe place to write state.transform — instead of racing the
# physics step via set_deferred (task 0.15). Dynamic dispatch: Ship and
# Ball both implement queue_teleport(), but RigidBody3D itself doesn't,
# so a statically-typed call here won't resolve.
body.call("queue_teleport", to)
func _unhandled_input(event):
if event.is_action_pressed("ui_cancel"):
# leave_gameplay (Escape / Start), NOT ui_cancel. ui_cancel carries the B
# button so menus behave the way a controller player expects, and B is far
# too easy to hit by accident for "abandon the match you are playing".
# Menus and the lobby still use ui_cancel; only live gameplay is guarded.
if event.is_action_pressed("leave_gameplay"):
get_tree().change_scene_to_file(ScenePaths.MAIN_MENU)
@@ -282,17 +298,31 @@ const ESCAPE_MARGIN := 15.0
func _physics_process(_delta: float) -> void:
_respawn_escaped_bodies()
if _owns_world_simulation():
_respawn_escaped_bodies()
func _respawn_escaped_bodies() -> void:
var respawned := false
for ship in ships:
if is_instance_valid(ship) and _is_escaped(ship.global_position):
push_warning("GameMode: ship escaped the enclosed arena — check boundary colliders")
_reset_body(ship, _ship_spawn_transforms[ship])
respawned = true
if is_instance_valid(ball) and _is_escaped(ball.global_position):
push_warning("GameMode: ball escaped the enclosed arena — check boundary colliders")
_reset_body(ball, arena.get_ball_spawn())
respawned = true
if respawned:
_on_bodies_respawned()
# Virtual (task 5.9). An escape respawn is a teleport, and a networked client
# interpolating toward it would smoothly slide a body the width of the arena
# and then fight the correction. NetworkedMatch overrides this to bump
# reset_gen so clients hard-snap instead. Single-player modes need nothing.
func _on_bodies_respawned() -> void:
pass
func _is_escaped(position: Vector3) -> bool:
+1 -1
View File
@@ -38,7 +38,7 @@ func _process(delta: float) -> void:
_pitch = new_pitch
_roll = new_roll
if changed:
queue_redraw()
_throttled_redraw(delta)
func _draw() -> void:
+1 -1
View File
@@ -33,7 +33,7 @@ func _process(delta: float) -> void:
var changed := absf(new_value - _value) > max_value * 0.001
_value = new_value
if changed:
queue_redraw()
_throttled_redraw(delta)
func _draw() -> void:
+1 -1
View File
@@ -35,7 +35,7 @@ func _process(delta: float) -> void:
var changed := absf(angle_delta_deg(_heading, new_heading)) > REDRAW_EPSILON_DEG
_heading = new_heading
if changed:
queue_redraw()
_throttled_redraw(delta)
func _draw() -> void:
+16
View File
@@ -7,6 +7,13 @@ extends Control
# _process (smoothing 1-2 distinct fields) and _draw (entirely bespoke).
const SMOOTHING := 12.0
# _draw does real work (text shaping, building point arrays); nobody can
# perceive an instrument repainting faster than this, so redraws are paced
# to it independently of the render frame rate — value smoothing itself
# still runs every _process call, only the (expensive) repaint is throttled.
const REDRAW_INTERVAL := 1.0 / 60.0
var _time_since_redraw := 0.0
static func lerp_angle_deg(from: float, to: float, weight: float) -> float:
@@ -23,3 +30,12 @@ static func angle_delta_deg(from: float, to: float) -> float:
func _smoothing_weight(delta: float) -> float:
return 1.0 - exp(-SMOOTHING * delta) # frame-rate independent
# Call instead of queue_redraw() directly once a subclass's _process has
# decided the smoothed value moved enough to warrant a repaint.
func _throttled_redraw(delta: float) -> void:
_time_since_redraw += delta
if _time_since_redraw >= REDRAW_INTERVAL:
_time_since_redraw = 0.0
queue_redraw()
+178
View File
@@ -0,0 +1,178 @@
class_name InputJitterBuffer
extends RefCounted
# Per-player server-side input state (MULTIPLAYER_SPEC.md §3; multiplayer-next.md task 3.2).
# Deliberately a standalone RefCounted with no scene/RPC dependency — same
# reason net_codec.gd and net_interpolator.gd are pure classes — so task
# 3.5's unit tests can drive it with scripted arrival traces with no live
# match. NetworkedMatch owns one instance per connected slot and is the only
# thing that talks to the network layer; this class only knows about
# sequence numbers and ShipActions.
#
# Ring is fixed-size and slot-tagged (§3.1 step 5's "a client can never make
# the server allocate"): ingest() writes seq % RING_SIZE regardless of how
# large or malicious seq is, and consume() only ever trusts a slot whose
# stored seq exactly matches the one it expects — a stale or wrapped-around
# entry is indistinguishable from an empty one. Range/rate validation of seq
# against the current server tick is the CALLER's job (task 3.4), not this
# class's, since only the caller knows the current server tick.
const RING_SIZE := 32
# 500ms at 60Hz (MULTIPLAYER_SPEC.md §3.2's own numbers) — a duration, not a
# tick-rate-derived constant, so left as a literal rather than pulling in
# SimConstants for one number.
const STARVE_ZERO_TICKS := 30
var last_applied_seq := -1 # -1: consume() has never been called yet
var last_action := ShipAction.new()
var starved_ticks := 0
var stalled := false
var _ring_action: Array = []
var _ring_seq: PackedInt32Array = PackedInt32Array()
# True once ingest() has ever been called for real. Consumption is a no-op
# (no starvation counted, no advancement) until then — see ingest()'s own
# comment for why an un-seeded buffer would otherwise never converge with
# what the client is actually sending.
var _seeded := false
# Highest seq ever seen by ingest(), regardless of whether it's still in the
# ring — consume()'s only way to tell "the data is gone because the ring
# overflowed" apart from "the data just hasn't arrived yet". See consume()'s
# own comment for why this exists: an adversarial review found that without
# it, a backlog bigger than RING_SIZE (a host stall, or persistent client/
# server clock drift) permanently zeroed a connected player's input for the
# rest of the match.
#
# Deliberately public (no underscore), same as last_applied_seq: the
# networked_match.gd caller's seq-range guard (§3.1 step 4) must bound
# against THIS, not against last_applied_seq. A second adversarial review
# found that bounding against last_applied_seq caps every accepted seq at
# last_applied_seq + RING_SIZE, which in turn caps this field at the same
# ceiling — making the resync condition below (which needs this field to
# reach expected + RING_SIZE) arithmetically unreachable on the only call
# path that exists in production. The two fixes looked independent but
# shared a variable and silently cancelled each other out. highest_ingested
# tracks the client's own send epoch instead, which the guard can safely
# let run ahead of a lagging consumer.
var highest_ingested_seq := -1
func _init() -> void:
_ring_action.resize(RING_SIZE)
_ring_seq.resize(RING_SIZE)
for i in RING_SIZE:
_ring_seq[i] = -1
# newest_seq/actions match NetCodec.unpack_input's own "seq"/"actions"
# fields directly: actions[i] is the action for sequence (newest_seq - i),
# newest-first. Already-consumed or stale entries are silently discarded
# (§3.1 step 5) — this is what makes redundant re-delivery of an already-
# applied tick harmless.
func ingest(newest_seq: int, actions: Array) -> void:
if not _seeded:
# The server starts calling consume() every tick the instant this
# slot exists — well before this player's first packet has had time
# to arrive (connection handshake, arena/ship spawn, first
# _physics_process tick on the client all take real time first). An
# un-seeded last_applied_seq of -1 would have consume() "expecting"
# sequence 0, 1, 2, ... via pure starvation the whole time, racing
# arbitrarily far ahead of whatever the client's own from-1
# numbering has actually reached by the time real packets show up —
# and since both sides only ever advance monotonically with no
# resync mechanism, that gap would never close. Seed to align
# "expected" with reality the moment real data first exists.
last_applied_seq = newest_seq - actions.size()
_seeded = true
if newest_seq > highest_ingested_seq:
highest_ingested_seq = newest_seq
for i in actions.size():
var seq: int = newest_seq - i
if seq <= last_applied_seq:
continue
var idx := seq % RING_SIZE
_ring_seq[idx] = seq
_ring_action[idx] = actions[i]
# Contiguous run of not-yet-applied entries starting right after
# last_applied_seq — reported as input_buffer_depth in every snapshot
# (§3.3) and consumed client-side by the input_lead control loop (task 3.3).
func depth() -> int:
if not _seeded or last_applied_seq < 0:
return 0
var d := 0
var seq := last_applied_seq + 1
while d < RING_SIZE and _ring_seq[seq % RING_SIZE] == seq:
d += 1
seq += 1
return d
# Called once per server physics tick, before the step (§3.2). A no-op
# (returns the zero-initialized last_action, no starvation counted) until
# this player's first real packet has ever arrived — see ingest()'s comment.
func consume() -> ShipAction:
if not _seeded:
return last_action
var expected := last_applied_seq + 1
var idx := expected % RING_SIZE
# Ring-overflow resync. A fixed-size ring can only ever hold RING_SIZE
# ticks of not-yet-consumed data at once — if the caller has fallen
# further behind the newest data actually arriving than that (a host
# stall, or persistent client/server clock drift), every tick between
# "expected" and "highest_ingested_seq - RING_SIZE" has already been
# irrecoverably overwritten by more recent arrivals landing on the same
# ring slots. Waiting for it tick-by-tick would starve — and, past
# STARVE_ZERO_TICKS, zero this player's ship — for the ENTIRE gap even
# though fresh, real input already exists in the ring right now. An
# adversarial review found and reproduced this exact failure (a ~0.7s
# host freeze permanently zeroed a connected player's input for the
# rest of the match, with no self-recovery). Skip the unrecoverable
# span and resync directly to what the ring can still actually provide.
if highest_ingested_seq - expected >= RING_SIZE:
last_applied_seq = highest_ingested_seq - RING_SIZE
expected = last_applied_seq + 1
idx = expected % RING_SIZE
if _ring_seq[idx] == expected:
last_action = _ring_action[idx]
starved_ticks = 0
stalled = false
last_applied_seq = expected
return last_action
# Repeat-last, not zero: inputs are heavily autocorrelated at 60Hz,
# and the client already predicted with the real input either way,
# so repeating minimises expected divergence (§3.2). Only zero after
# a sustained stall, so a disconnecting player's ship doesn't fly
# into a wall at full throttle forever.
starved_ticks += 1
if starved_ticks > STARVE_ZERO_TICKS:
last_action = ShipAction.new()
stalled = true
# Only GIVE UP on `expected` when strictly newer data has actually
# arrived, which proves it was lost or reordered rather than merely late.
#
# Advancing unconditionally (what this did originally) is catastrophic
# rather than merely lossy, because ingest() discards anything
# `seq <= last_applied_seq`. One starve on a sequence the client has not
# even sent yet leaves the server permanently one ahead of arrivals:
# both sides then advance one per tick, the gap never closes, and every
# honest packet is discarded on arrival for the rest of the match. An
# adversarial review reproduced exactly that on a clean LAN — the client's
# own input_lead RELEASE (delta == 0, which deliberately issues no new
# sequence for one tick) is sufficient to trigger it, so it fired roughly
# every 6.5s of ordinary play, blacking out input for 30 ticks until the
# lead controller's debounce allowed a +3 attack to jump the client clear.
#
# Holding cannot deadlock: if the client genuinely goes silent,
# highest_ingested_seq stops moving, starved_ticks still climbs, and the
# STARVE_ZERO_TICKS zeroing plus `stalled` above still fire on schedule.
# If it falls far behind instead, the ring-overflow resync above still
# jumps the cursor forward. Both escape paths are unchanged.
if highest_ingested_seq > expected:
last_applied_seq = expected
return last_action
+1
View File
@@ -0,0 +1 @@
uid://cp818kexskb34
+120
View File
@@ -0,0 +1,120 @@
class_name InputLeadController
extends RefCounted
# Client-owned input_lead control loop (MULTIPLAYER_SPEC.md §3.3; multiplayer-next.md task 3.3).
# Standalone RefCounted, same reason as input_jitter_buffer.gd — scene-free
# so it's directly unit-testable against scripted depth traces.
#
# §3.3's own rationale for why this is the CLIENT's job alone, not shared
# with any server-side adaptation: three control loops acting on one plant
# (buffer occupancy) with different time constants is a textbook
# oscillation, and on a jittery link it presents to the player as
# intermittent sticky controls that are nearly impossible to attribute.
# The server (InputJitterBuffer, §3.2) only ever reports input_buffer_depth
# — it does nothing adaptive with it.
#
# "Lead" is realized concretely as extra distance between this client's own
# outgoing sequence numbers and what the server has actually consumed:
# skipping a sequence number (jumping the client's own seq counter by more
# than 1 for one tick) buys the server one more tick of buffered depth
# before it would starve; duplicating one (not incrementing the seq counter
# for one tick — the same seq gets sent again) narrows that margin by one
# tick of latency. The server's own ring buffer doesn't need to know this
# happened: a skipped seq just means "the redundant copies of it never
# existed, it's an ordinary drop" (already handled), and a duplicated seq
# is a same-seq resend, already discarded harmlessly once consumed
# (InputJitterBuffer.ingest()'s "seq <= last_applied_seq" check).
#
# Fast attack, slow release — a symmetric ±1-per-N-ticks slew would take
# two full seconds to absorb a single wifi spike, during which the player
# steers and the ship does not turn, "the most rage-inducing failure mode
# in any netcode" per §3.3's own words.
const LEAD_MIN := 1
const LEAD_MAX := 12
# "Never change it more than once per 30 ticks" (§3.3) — the floor that
# binds the fast-attack side; slow-release's own 60-tick cadence already
# exceeds it, so this one constant covers both.
const MIN_CHANGE_INTERVAL_TICKS := 30
const RELEASE_INTERVAL_TICKS := 60
const CLEAN_SURPLUS_TICKS := 120 # 2s at 60Hz
# §3.3: "target_depth = 1 (16.7 ms), not 2." Release only fires when the
# server-reported depth is genuinely ABOVE this — see update()'s own
# comment for why gating on `lead` alone (an adversarial review's original
# finding here) was wrong.
const TARGET_DEPTH := 1
var lead := LEAD_MIN
var _ticks_since_change := 0
var _clean_surplus_ticks := 0
# Call once per client physics tick with the most recently known server-
# reported input_buffer_depth for THIS client's own slot (echoed in every
# snapshot, §3.2) — or -1 if no snapshot carrying that field has arrived
# yet. Returns the seq delta the caller should add for this tick's
# outgoing packet: ordinarily 1 (ship normally increments its send
# sequence by exactly one tick's worth), or 1+N / 0 on a tick where a lead
# change actually fires (skip N extra / duplicate the current one).
func update(input_buffer_depth: int, target_depth: int = TARGET_DEPTH) -> int:
_ticks_since_change += 1
if input_buffer_depth == -1:
return 1 # no server depth has arrived yet
if input_buffer_depth < -1:
# -1 is an explicit server starvation sentinel, distinct from a
# healthy zero-depth buffer on an adaptive clean link.
_clean_surplus_ticks = 0
if _ticks_since_change >= MIN_CHANGE_INTERVAL_TICKS and lead < LEAD_MAX:
var starve_lead := mini(lead + 3, LEAD_MAX)
var starve_delta := starve_lead - lead
lead = starve_lead
_ticks_since_change = 0
return 1 + starve_delta
return 1
target_depth = maxi(0, target_depth)
if input_buffer_depth <= target_depth - 1:
# A starve: the server's ring was empty for this player when it
# built that snapshot. React immediately, not after 2 seconds of
# evidence like release requires — but still debounced against
# MIN_CHANGE_INTERVAL_TICKS so a burst of consecutive starve
# reports doesn't compound into repeated, overlapping jumps.
_clean_surplus_ticks = 0
if _ticks_since_change >= MIN_CHANGE_INTERVAL_TICKS and lead < LEAD_MAX:
var new_lead := mini(lead + 3, LEAD_MAX)
var delta := new_lead - lead
lead = new_lead
_ticks_since_change = 0
return 1 + delta
return 1
# Release must react to the ACTUAL server-reported depth, not to this
# controller's own memory of past attacks. A first pass at this fix
# added the depth check above but left the OLD gate, `lead > LEAD_MIN`,
# still ANDed onto the final condition below — so a backlog this
# controller did NOT itself cause (a server hitch, persistent client/
# server clock drift, a ring resync) still could never be drained:
# with lead pinned at its starting floor, that clause always failed
# even while input_buffer_depth sat well above target. A second
# adversarial review caught it, confirmed by this file's own
# test_release_drains_a_backlog_it_never_caused_itself, whose original
# assertion text literally said "lead cannot release below its own
# floor even under large surplus" as if that were correct.
#
# The fix splits the one gate into two separate decisions: whether to
# duplicate this tick's seq (the only thing that actually narrows real
# buffered depth) follows the real signal alone, below; whether to
# keep decrementing `lead`'s own bookkeeping below its documented
# floor is a separate, cosmetic-only choice made inside that branch.
if input_buffer_depth > target_depth:
_clean_surplus_ticks += 1
else:
_clean_surplus_ticks = 0
if _clean_surplus_ticks >= CLEAN_SURPLUS_TICKS and _ticks_since_change >= RELEASE_INTERVAL_TICKS:
if lead > LEAD_MIN:
lead -= 1
_ticks_since_change = 0
return 0 # duplicate this tick's seq — one tick of latency recovered
return 1
@@ -0,0 +1 @@
uid://bvwwwkf82nkdk
+329
View File
@@ -0,0 +1,329 @@
extends Node
# Autoload: persisted keyboard/controller bindings on top of project.godot's
# [input] defaults, plus the flight-feel preferences that belong with them
# (invert pitch). The Settings screen's Controls tab (controls_settings.gd) is
# the only writer; PlayerShipController is the only reader of pitch_sign().
#
# project.godot stays the single source of truth for *defaults*: _ready()
# snapshots whatever InputMap holds at boot, before any override is applied, so
# the default table is never duplicated in GDScript and can never drift from the
# file. An override is only ever a delta on top of that snapshot.
#
# Persisted to user://input.cfg rather than user://settings.cfg, deliberately.
# VideoSettings.save() builds a fresh ConfigFile and writes it, which would drop
# every section it does not itself know about — so two autoloads sharing one
# file would silently erase each other. A separate file sidesteps that entirely
# instead of coupling the two save paths.
# Each action is bound at most once per device kind. That is a deliberate
# simplification of Godot's arbitrary-length event list: it makes a rebind row
# a single button rather than an editable list, and makes "what is X bound to?"
# answerable. The consequence is that applying a binding replaces the whole
# event list for that action (see apply()), so anything project.godot binds
# beyond one keyboard + one joypad event per action would be dropped here.
const DEVICE_KEYBOARD := "keyboard"
const DEVICE_JOYPAD := "joypad"
const SETTINGS_PATH := "user://input.cfg"
# The rebindable action list, and the only place the Controls tab and the tests
# read it from. Order is display order. Actions NOT listed here (ui_*, the F3/F4
# debug overlays) are deliberately not rebindable.
const ACTIONS := [
{"action": "move_forward", "label": "Thrust forward", "group": "Flight"},
{"action": "move_back", "label": "Thrust backward", "group": "Flight"},
{"action": "move_left", "label": "Strafe left", "group": "Flight"},
{"action": "move_right", "label": "Strafe right", "group": "Flight"},
{"action": "move_up", "label": "Thrust up", "group": "Flight"},
{"action": "move_down", "label": "Thrust down", "group": "Flight"},
{"action": "turbo", "label": "Turbo", "group": "Flight"},
{"action": "turn_left", "label": "Yaw left", "group": "Attitude"},
{"action": "turn_right", "label": "Yaw right", "group": "Attitude"},
{"action": "pitch_up", "label": "Pitch up", "group": "Attitude"},
{"action": "pitch_down", "label": "Pitch down", "group": "Attitude"},
{"action": "roll_left", "label": "Roll left", "group": "Attitude"},
{"action": "roll_right", "label": "Roll right", "group": "Attitude"},
{"action": "toggle_ball_cam", "label": "Ball camera", "group": "Other"},
{"action": "reset_ball", "label": "Reset ball (Free Play)", "group": "Other"},
]
# button_index -> label, using the Xbox names the default map is expressed in.
# InputEvent.as_text() renders these as "Joypad Button 9 (Left Shoulder)", which
# is both long and wrong-looking in a rebind row.
const JOY_BUTTON_NAMES := {
JOY_BUTTON_A: "A", JOY_BUTTON_B: "B", JOY_BUTTON_X: "X", JOY_BUTTON_Y: "Y",
JOY_BUTTON_BACK: "Back", JOY_BUTTON_GUIDE: "Guide", JOY_BUTTON_START: "Start",
JOY_BUTTON_LEFT_STICK: "L3", JOY_BUTTON_RIGHT_STICK: "R3",
JOY_BUTTON_LEFT_SHOULDER: "LB", JOY_BUTTON_RIGHT_SHOULDER: "RB",
JOY_BUTTON_DPAD_UP: "D-Pad Up", JOY_BUTTON_DPAD_DOWN: "D-Pad Down",
JOY_BUTTON_DPAD_LEFT: "D-Pad Left", JOY_BUTTON_DPAD_RIGHT: "D-Pad Right",
}
# axis -> [label at negative deflection, label at positive deflection]. The
# triggers rest at 0 and only travel positive, so their negative half is never
# a reachable binding and is labelled as such rather than as a direction.
const JOY_AXIS_NAMES := {
JOY_AXIS_LEFT_X: ["Left Stick Left", "Left Stick Right"],
JOY_AXIS_LEFT_Y: ["Left Stick Up", "Left Stick Down"],
JOY_AXIS_RIGHT_X: ["Right Stick Left", "Right Stick Right"],
JOY_AXIS_RIGHT_Y: ["Right Stick Up", "Right Stick Down"],
JOY_AXIS_TRIGGER_LEFT: ["LT", "LT"],
JOY_AXIS_TRIGGER_RIGHT: ["RT", "RT"],
}
signal bindings_changed
# Push the right stick forward and the nose goes down (flight-sim). Ticking this
# flips it. Applied in PlayerShipController rather than by rewriting the
# bindings, so it stays one preference instead of two swapped rows the player
# then has to reason about.
var invert_pitch: bool = false
# action -> {DEVICE_KEYBOARD: InputEvent|null, DEVICE_JOYPAD: InputEvent|null},
# snapshotted from InputMap at boot before any override lands.
var _defaults: Dictionary = {}
# Same shape, but only for actions the player has actually customised. A device
# key that is absent means "still using the default"; a device key present with
# null means "the player deliberately unbound it".
var _overrides: Dictionary = {}
func _ready() -> void:
_capture_defaults()
_load()
apply()
# Reads project.godot's [input] back out of InputMap. Anything that is neither a
# key nor a joypad button/motion event (mouse buttons, say) is ignored rather
# than mis-filed under a device kind it does not belong to.
func _capture_defaults() -> void:
_defaults.clear()
for entry in ACTIONS:
var action: String = entry["action"]
var slots := {DEVICE_KEYBOARD: null, DEVICE_JOYPAD: null}
if InputMap.has_action(action):
for event in InputMap.action_get_events(action):
var kind := device_kind_of(event)
if kind != "" and slots[kind] == null:
slots[kind] = event
_defaults[action] = slots
# "" for an event this system cannot express (mouse, gesture, MIDI), which is
# also the signal to callers that it is not a legal binding.
static func device_kind_of(event: InputEvent) -> String:
if event is InputEventKey:
return DEVICE_KEYBOARD
if event is InputEventJoypadButton or event is InputEventJoypadMotion:
return DEVICE_JOYPAD
return ""
func _load() -> void:
_overrides.clear()
var cfg := ConfigFile.new()
if cfg.load(SETTINGS_PATH) != OK:
return
invert_pitch = cfg.get_value("input", "invert_pitch", invert_pitch)
for entry in ACTIONS:
var action: String = entry["action"]
for device in [DEVICE_KEYBOARD, DEVICE_JOYPAD]:
var key := "%s.%s" % [action, device]
if not cfg.has_section_key("bindings", key):
continue
var stored = cfg.get_value("bindings", key)
if not (stored is Dictionary):
continue
# An empty dict is the "deliberately unbound" sentinel — see save().
if stored.is_empty():
_set_override(action, device, null)
continue
var event := event_from_dict(stored)
if event != null:
_set_override(action, device, event)
func save() -> void:
var cfg := ConfigFile.new()
cfg.set_value("input", "invert_pitch", invert_pitch)
for action in _overrides:
var slots: Dictionary = _overrides[action]
for device in slots:
var event: InputEvent = slots[device]
var key := "%s.%s" % [action, device]
# An unbound override is written as an empty dict, NOT as null:
# ConfigFile.set_value() treats a null value as "erase this key", so
# storing null would drop the entry and the next load would fall
# back to the project default — silently rebinding something the
# player had deliberately cleared.
cfg.set_value("bindings", key, {} if event == null else event_to_dict(event))
cfg.save(SETTINGS_PATH)
# Rebuilds InputMap for every rebindable action from defaults + overrides. Runs
# wholesale rather than incrementally so there is exactly one code path that
# decides what an action is bound to, whatever route got us here.
func apply() -> void:
for entry in ACTIONS:
var action: String = entry["action"]
if not InputMap.has_action(action):
continue
InputMap.action_erase_events(action)
for device in [DEVICE_KEYBOARD, DEVICE_JOYPAD]:
var event := get_binding(action, device)
if event != null:
InputMap.action_add_event(action, event)
bindings_changed.emit()
func get_binding(action: String, device: String) -> InputEvent:
if _overrides.has(action) and _overrides[action].has(device):
return _overrides[action][device]
if _defaults.has(action):
return _defaults[action][device]
return null
func get_default_binding(action: String, device: String) -> InputEvent:
if not _defaults.has(action):
return null
return _defaults[action][device]
# Binds `event` to `action`, replacing whatever that action had for the event's
# own device kind. Returns the actions that were unbound to avoid a duplicate,
# so the caller can say so rather than leaving the player to discover it.
func set_binding(action: String, event: InputEvent) -> PackedStringArray:
var device := device_kind_of(event)
if device == "":
return PackedStringArray()
var displaced := find_conflicts(event, action)
for other in displaced:
_set_override(other, device, null)
_set_override(action, device, event)
apply()
return displaced
func clear_binding(action: String, device: String) -> void:
_set_override(action, device, null)
apply()
# Actions already bound to an equivalent event, excluding `except_action`.
# Compared by value rather than by object identity — the event coming out of a
# rebind capture is a different instance from the one in the map.
func find_conflicts(event: InputEvent, except_action: String = "") -> PackedStringArray:
var device := device_kind_of(event)
var out := PackedStringArray()
if device == "":
return out
for entry in ACTIONS:
var action: String = entry["action"]
if action == except_action:
continue
var bound := get_binding(action, device)
if bound != null and events_match(bound, event):
out.append(action)
return out
# Equality by the fields a binding is identified by. Deliberately not
# InputEvent.is_match(): for an axis that ignores axis_value, which would make
# "Right Stick Up" and "Right Stick Down" collide as the same binding.
static func events_match(a: InputEvent, b: InputEvent) -> bool:
if a is InputEventKey and b is InputEventKey:
return a.physical_keycode == b.physical_keycode
if a is InputEventJoypadButton and b is InputEventJoypadButton:
return a.button_index == b.button_index
if a is InputEventJoypadMotion and b is InputEventJoypadMotion:
return a.axis == b.axis and signf(a.axis_value) == signf(b.axis_value)
return false
func reset_action(action: String) -> void:
_overrides.erase(action)
apply()
func reset_all() -> void:
_overrides.clear()
invert_pitch = false
apply()
func has_override(action: String) -> bool:
return _overrides.has(action)
func pitch_sign() -> float:
return -1.0 if invert_pitch else 1.0
func _set_override(action: String, device: String, event: InputEvent) -> void:
if not _overrides.has(action):
_overrides[action] = {}
_overrides[action][device] = event
# ConfigFile stores Dictionary values natively, so bindings persist as plain
# data. Never the Object(...) literal Godot writes into project.godot — that
# form is only parsed by the engine's own project-file loader, and round-tripping
# it through user:// would be storing engine-internal syntax in a save file.
static func event_to_dict(event: InputEvent) -> Dictionary:
if event is InputEventKey:
return {"type": "key", "physical_keycode": int(event.physical_keycode)}
if event is InputEventJoypadButton:
return {"type": "joy_button", "button_index": int(event.button_index)}
if event is InputEventJoypadMotion:
return {"type": "joy_axis", "axis": int(event.axis), "value": float(signf(event.axis_value))}
return {}
# Returns null for anything unrecognised, so a save file from a newer build (or
# a hand-edited one) degrades to "this action is unbound" rather than crashing
# the game before the player can reach the Controls tab to fix it.
static func event_from_dict(data: Dictionary) -> InputEvent:
match data.get("type", ""):
"key":
var key := InputEventKey.new()
key.physical_keycode = int(data.get("physical_keycode", 0))
return key if key.physical_keycode != 0 else null
"joy_button":
var button := InputEventJoypadButton.new()
button.button_index = int(data.get("button_index", -1))
return button if button.button_index >= 0 else null
"joy_axis":
var motion := InputEventJoypadMotion.new()
motion.axis = int(data.get("axis", -1))
motion.axis_value = signf(float(data.get("value", 0.0)))
return motion if motion.axis >= 0 and motion.axis_value != 0.0 else null
return null
func event_to_text(event: InputEvent) -> String:
if event == null:
return "Unbound"
if event is InputEventKey:
# Physical keycodes throughout, so the label matches the key's position
# on a non-QWERTY layout the same way the binding itself does. The
# headless display server has no keyboard layout to consult and pushes
# an ERROR for the attempt — which the ENet smoke gate treats as a
# failure on sight — so fall back to the unmapped keycode there.
var keycode: int = event.physical_keycode
if DisplayServer.get_name() != "headless":
keycode = DisplayServer.keyboard_get_keycode_from_physical(keycode)
return OS.get_keycode_string(keycode)
if event is InputEventJoypadButton:
return JOY_BUTTON_NAMES.get(event.button_index, "Button %d" % event.button_index)
if event is InputEventJoypadMotion:
if JOY_AXIS_NAMES.has(event.axis):
return JOY_AXIS_NAMES[event.axis][0 if event.axis_value < 0.0 else 1]
return "Axis %d%s" % [event.axis, "-" if event.axis_value < 0.0 else "+"]
return event.as_text()
func binding_text(action: String, device: String) -> String:
return event_to_text(get_binding(action, device))
+1
View File
@@ -0,0 +1 @@
uid://bjtdsbem7kwdv
+128
View File
@@ -0,0 +1,128 @@
extends Control
# Lobby (task 1.5): roster list split by team, team swap, ready toggle,
# leave. Reads/writes MatchNet.roster — this scene owns no state of its
# own, it's a view over the autoload. Reached via main_menu.gd's Host/Join
# flow (task 1.7) calling change_scene_to_file("res://scenes/lobby.tscn")
# after NetworkManager.host()/join() succeeds — this scene must always be
# loaded that way (as the real current_scene), not instantiated as a child
# of something else: change_scene_to_file() operates on
# get_tree().current_scene, and _on_disconnected_from_server()/_leave()
# below call it themselves, which hangs if this scene isn't actually the
# tree's current_scene when that happens (see multiplayer-next.md §9
# gotcha 27 — found the hard way while building tests/lobby_smoke.gd).
@onready var _status_label: Label = %StatusLabel
@onready var _team0_list: VBoxContainer = %Team0List
@onready var _team1_list: VBoxContainer = %Team1List
@onready var _controls_row: HBoxContainer = %ControlsRow
@onready var _switch_team_button: Button = %SwitchTeamButton
@onready var _ready_button: CheckButton = %ReadyButton
@onready var _leave_button: Button = %LeaveButton
var _planned_server_shutdown := false
func _ready() -> void:
MatchNet.welcomed.connect(_on_welcomed)
MatchNet.player_joined.connect(_on_roster_changed)
MatchNet.player_left.connect(_on_roster_changed)
MatchNet.player_state_changed.connect(_on_roster_changed)
MatchNet.rejected.connect(_on_rejected)
MatchNet.server_shutdown.connect(_on_server_shutdown)
NetworkManager.disconnected_from_server.connect(_on_disconnected_from_server)
# The server process is never a roster member (§1.1 decision 2) — it
# gets a read-only view, no team/ready controls to operate on itself.
_controls_row.visible = NetworkManager.is_client
_refresh()
if not MatchNet.last_server_shutdown_reason.is_empty():
_planned_server_shutdown = true
_status_label.text = "Server closed: %s" % MatchNet.last_server_shutdown_reason
func _process(_delta: float) -> void:
NetworkManager.poll()
func _physics_process(_delta: float) -> void:
NetworkManager.poll()
func _unhandled_input(event: InputEvent) -> void:
if event.is_action_pressed("ui_cancel"):
_leave()
func _on_roster_changed(_a = null, _b = null, _c = null) -> void:
_refresh()
func _on_welcomed() -> void:
_refresh()
func _on_rejected(reason: String) -> void:
_status_label.text = "Connection rejected: %s" % reason
func _on_server_shutdown(reason: String) -> void:
_planned_server_shutdown = true
_status_label.text = "Server closed: %s" % reason
func _on_disconnected_from_server() -> void:
if _planned_server_shutdown:
return
get_tree().change_scene_to_file(ScenePaths.MAIN_MENU)
func _on_switch_team_pressed() -> void:
var my_id := multiplayer.get_unique_id()
var info: MatchNet.PlayerInfo = MatchNet.roster.get(my_id)
if info == null:
return
MatchNet.request_set_team((info.team + 1) % MatchNet.TEAM_COUNT)
func _on_ready_toggled(pressed: bool) -> void:
MatchNet.request_set_ready(pressed)
func _on_leave_pressed() -> void:
_leave()
func _leave() -> void:
NetworkManager.shutdown()
get_tree().change_scene_to_file(ScenePaths.MAIN_MENU)
func _refresh() -> void:
if NetworkManager.is_server:
_status_label.text = "Hosting — %d player(s) connected" % MatchNet.roster.size()
elif NetworkManager.is_client:
_status_label.text = "Connected" if not MatchNet.roster.is_empty() else "Connecting..."
else:
_status_label.text = "Not connected"
for child in _team0_list.get_children():
child.queue_free()
for child in _team1_list.get_children():
child.queue_free()
var my_id := multiplayer.get_unique_id()
var infos: Array = MatchNet.roster.values()
infos.sort_custom(func(a: MatchNet.PlayerInfo, b: MatchNet.PlayerInfo) -> bool: return a.peer_id < b.peer_id)
for info: MatchNet.PlayerInfo in infos:
var row := Label.new()
var marker := " (you)" if info.peer_id == my_id else ""
var ready_mark := "" if info.ready else ""
row.text = "%s %s%s" % [ready_mark, info.player_name, marker]
var target_list := _team0_list if info.team == 0 else _team1_list
target_list.add_child(row)
if NetworkManager.is_client:
var my_info: MatchNet.PlayerInfo = MatchNet.roster.get(my_id)
if my_info != null:
_ready_button.set_pressed_no_signal(my_info.ready)
+1
View File
@@ -0,0 +1 @@
uid://qd513s2cqls3
+78
View File
@@ -0,0 +1,78 @@
class_name LocalInputTimeline
extends RefCounted
# Client-only sequence/action timeline. It mirrors the stream the server's
# InputJitterBuffer will consume: an attack fills its deliberate sequence gap
# with repeat-last actions, while a release retransmits immutable data.
const ShipActionScript = preload("res://scripts/ship_action.gd")
const RETAINED_REDUNDANCY := 4
var latest_issued_seq := 0
var latest_applied_seq := -1
var configured := false
var _actions := {}
var _last_issued_action = ShipActionScript.new()
var _last_applied_action = ShipActionScript.new()
func configure_initial_delay(delay_ticks: int) -> void:
if configured:
return
latest_applied_seq = -maxi(delay_ticks, 1)
configured = true
func issue(delta: int, intent) -> int:
if delta <= 0:
# An already-issued sequence may be in flight or consumed. Never mutate
# it; carry current raw intent to the next unique command instead.
return latest_issued_seq
var from_seq := latest_issued_seq + 1
latest_issued_seq += delta
for seq in range(from_seq, latest_issued_seq):
_actions[seq] = _last_issued_action.copy()
_actions[latest_issued_seq] = intent.copy()
_last_issued_action = intent.copy()
_prune_consumed_actions()
return latest_issued_seq
func consume() -> Dictionary:
latest_applied_seq += 1
if _actions.has(latest_applied_seq):
_last_applied_action = _actions[latest_applied_seq].copy()
_prune_consumed_actions()
return {"seq": latest_applied_seq, "action": _last_applied_action.copy()}
# The action actually issued for a sequence, or null if it is no longer
# retained. Returns a copy: the timeline's stored actions are immutable once
# issued (see issue()), and handing out the live object would let a caller
# break that from the outside.
func action_for(seq: int):
if not _actions.has(seq):
return null
return _actions[seq].copy()
func packet_actions(max_count: int) -> Array:
var out: Array = []
for seq in range(latest_issued_seq, maxi(0, latest_issued_seq - max_count), -1):
if not _actions.has(seq):
break
out.append(_actions[seq].copy())
return out
func retained_action_count() -> int:
return _actions.size()
func _prune_consumed_actions() -> void:
# Preserve the local command needed for the server's redundancy window,
# then discard actions that are older than both consumption and backup use.
var keep_from := latest_issued_seq - RETAINED_REDUNDANCY + 1
for seq in _actions.keys():
if int(seq) < keep_from:
_actions.erase(seq)
+1
View File
@@ -0,0 +1 @@
uid://b8nwh3anyddm5
+27
View File
@@ -0,0 +1,27 @@
class_name LocalNetShipController
extends ShipController
const LocalInputTimeline = preload("res://scripts/local_input_timeline.gd")
var source: ShipController
var timeline: LocalInputTimeline
var last_applied_seq := -1
var last_sampled_intent: ShipAction
func _init(new_source: ShipController, new_timeline: LocalInputTimeline) -> void:
source = new_source
timeline = new_timeline
last_sampled_intent = ShipAction.new()
func get_action() -> ShipAction:
# Ship invokes this exactly once per local physics tick. Prediction must use
# the player's current intent immediately; the timeline is transmission and
# immutable-redundancy bookkeeping only. Advance its cursor solely to label
# this post-step state at the estimated server-consumption sequence; never
# use its queued action to delay local control.
last_sampled_intent = source.get_action().copy()
var label := timeline.consume()
last_applied_seq = int(label["seq"])
return last_sampled_intent.copy()
@@ -0,0 +1 @@
uid://dyaoxrjb006a8
+305
View File
@@ -0,0 +1,305 @@
class_name LocalPredictionHistory
extends RefCounted
const NetBodyState = preload("res://scripts/net_body_state.gd")
# Client-owned local-ship prediction history (MULTIPLAYER_SPEC.md §4.3).
# This is deliberately independent of NetworkedMatch and the scene tree so
# sequence/ring behaviour can be tested from scripted traces. Each entry is
# tagged with its full sequence number: an old value in a wrapped slot is
# never accepted as a prediction for a newer sequence.
#
# Acknowledge and record are separate producer/consumer clocks. The input
# sender can continue producing while snapshots stop arriving, so record()
# explicitly marks overflow once more than RING_SIZE unacknowledged sequence
# positions exist. It still retains the newest representable window, but
# callers can see that an authoritative resync is required instead of
# mistaking a wrapped overwrite for a valid comparison.
#
# resync_required is a live condition, NOT a latch: compare_authoritative()
# clears it again once acknowledgements have genuinely caught back up (see
# that method). This mirrors input_jitter_buffer.gd's `stalled`, which
# likewise drops back to false the moment a normal tick is consumed again.
# A latched flag would mean one transient ~2s stall anywhere in a match
# permanently pinned every later tick into "needs a hard resync", which is
# exactly the behaviour soft correction exists to avoid — and it would also
# cap overflow_count at 1 forever, since a second episode could never
# observe the flag going false again.
#
# Two things a "matched" result does NOT guarantee, flagged for whoever
# builds task 4.3's actual correction logic on top of this:
#
# 1. A "matched" result can still be reporting stale data. The slot-tag
# equality check in get_prediction() guarantees a match's payload
# genuinely belongs to the queried seq (never wrong-seq data mislabeled
# as right), but nothing in the "matched" status itself says HOW OLD
# that entry is. Under sparse recording (record() is not called with
# strictly consecutive seqs — see the record() comment below), an entry
# from well over RING_SIZE ticks ago can still report "matched" for a
# query landing on its untouched residue. resync_required correctly
# stays true in that case (the span guard below is exact), but the
# comparison payload itself carries no matched_stale/age distinction. A
# caller wanting to reject "matched but ancient" needs to separately
# check newest_recorded_seq - seq itself.
#
# 2. HISTORICAL, now fixed — kept because the reasoning still constrains
# callers. record() used to be called twice for the same seq with a
# DIFFERENT action on the release path (delta == 0), the later call
# silently overwriting the slot. That was wrong, not merely imprecise:
# LocalInputTimeline.issue() deliberately does NOT mutate _actions[seq]
# for an already-issued sequence ("may be in flight or consumed"), so
# the overwrite made this ring contradict the wire — it claimed an
# action for S that was never sent for S. networked_match.gd now skips
# recording entirely on a release tick, leaving the original (correct)
# predicted[S] in place. Callers must keep it that way: an already-
# recorded sequence's ACTION is immutable here, exactly as it is in the
# timeline. Only overwrite_state()/rebase_state_range() may revise an
# entry, and only its state.
#
# 3. A sequence can be ISSUED without ever being locally SIMULATED. The
# input_lead controller's attack path (delta > 1) skips sequence numbers
# to buy server-side buffer margin: those gap sequences are filled with
# repeat-last actions and sent, but the client took exactly ONE physics
# step that tick, so no post-step state exists for them. They are
# recorded via record_unsimulated() and report "unsimulated_gap" rather
# than "missing_not_recorded" — a routine consequence of this client's
# own lead control, NOT evidence of history loss, and specifically not a
# hard-snap condition. Distinguishing them matters: treating them as
# missing history teleported the ship and armed resync suppression
# several times a minute during ordinary play.
const RING_SIZE := 128
var _ring_seq: PackedInt32Array = PackedInt32Array()
var _ring_entry: Array = []
var _has_recorded := false
var _first_recorded_seq := -1
var newest_recorded_seq := -1
var last_acknowledged_seq := 0
var overflow_count := 0
var resync_required := false
func _init() -> void:
_ring_seq.resize(RING_SIZE)
_ring_entry.resize(RING_SIZE)
for i in RING_SIZE:
_ring_seq[i] = -1
# A reset starts a new authoritative epoch. Retained inputs/states describe
# the old world and must never be compared to the new kickoff state.
func begin_epoch() -> void:
for i in RING_SIZE:
_ring_seq[i] = -1
_ring_entry[i] = null
_has_recorded = false
_first_recorded_seq = -1
newest_recorded_seq = -1
last_acknowledged_seq = 0
resync_required = false
# Stores a private copy of both action and state. Returns true when this
# record crossed the unacknowledged-capacity boundary; the caller does not
# need that return today, but it makes the eviction event observable rather
# than silent when reconciliation starts applying corrections in Phase 4.3.
func record(seq: int, action: ShipAction, state: NetBodyState, contact_window: bool = false) -> bool:
var overflowed_now := false
if not _has_recorded or seq > newest_recorded_seq:
if not _has_recorded:
_first_recorded_seq = seq
if seq - last_acknowledged_seq > RING_SIZE:
# Only the LEADING edge of an episode counts: resync_required is
# still true for every subsequent tick of the same stall, and
# counting those would report one outage as hundreds. Because
# compare_authoritative() can now clear the flag, a genuinely
# separate later episode does increment this again.
overflowed_now = not resync_required
resync_required = true
if overflowed_now:
overflow_count += 1
newest_recorded_seq = seq
_has_recorded = true
var idx := posmod(seq, RING_SIZE)
_ring_seq[idx] = seq
_ring_entry[idx] = {
"action": action.copy(),
"state": state.copy(),
"contact_window": contact_window,
"unsimulated": false,
}
return overflowed_now
# Records a sequence that was issued and sent but never locally simulated —
# an attack's skipped sequence numbers (see note 3 in this file's header).
# It advances the same newest/overflow bookkeeping record() does, because the
# sequence genuinely is outstanding and the server will genuinely acknowledge
# it; only the post-step state is absent, because the client never computed
# one. Deliberately carries the action anyway: it is what went on the wire, so
# a caller diagnosing an acknowledgement still has the honest command, and
# nothing here has to invent a state to keep the ring dense.
func record_unsimulated(seq: int, action: ShipAction) -> bool:
var overflowed_now := false
if not _has_recorded or seq > newest_recorded_seq:
if not _has_recorded:
_first_recorded_seq = seq
if seq - last_acknowledged_seq > RING_SIZE:
overflowed_now = not resync_required
resync_required = true
if overflowed_now:
overflow_count += 1
newest_recorded_seq = seq
_has_recorded = true
var idx := posmod(seq, RING_SIZE)
_ring_seq[idx] = seq
_ring_entry[idx] = {
"action": action.copy(),
"state": null,
"contact_window": false,
"unsimulated": true,
}
return overflowed_now
# Returns independent copies so diagnostic/reconciliation consumers cannot
# mutate a retained prediction by accident.
func get_prediction(seq: int) -> Dictionary:
var idx := posmod(seq, RING_SIZE)
if _ring_seq[idx] != seq:
return {}
var entry: Dictionary = _ring_entry[idx]
if bool(entry.get("unsimulated", false)):
# No state to hand back — see note 3. Callers must check this flag
# before touching "state"; it is null, not a zeroed NetBodyState,
# specifically so a caller that forgets fails loudly instead of
# silently comparing against the origin.
return {
"seq": seq,
"action": (entry["action"] as ShipAction).copy(),
"state": null,
"contact_window": false,
"unsimulated": true,
}
return {
"seq": seq,
"action": (entry["action"] as ShipAction).copy(),
"state": (entry["state"] as NetBodyState).copy(),
"contact_window": bool(entry.get("contact_window", false)),
"unsimulated": false,
}
# Reconciliation changes the state paired with already-sent input, never the
# input itself. This is deliberately a no-op for an absent/skipped sequence:
# input-lead control permits sparse sequence numbers, so there is no honest
# action to invent for such a slot.
func overwrite_state(seq: int, state: NetBodyState) -> bool:
var idx := posmod(seq, RING_SIZE)
if _ring_seq[idx] != seq:
return false
var entry: Dictionary = _ring_entry[idx]
if bool(entry.get("unsimulated", false)):
# Writing a state here would manufacture a local prediction for a
# sequence this client never simulated, which is exactly the fabricated
# history §4.4 forbids. The slot stays stateless.
return false
entry["state"] = state.copy()
return true
func overwrite_state_range(from_seq: int, to_seq: int, state: NetBodyState) -> void:
for seq in range(from_seq, to_seq + 1):
overwrite_state(seq, state)
# Carries an authoritative same-sequence correction through the retained
# future. This is intentionally a transport operation, not a synthetic
# physics replay: the live Jolt body has already advanced through the real
# contact world, and a soft correction must not leave its later comparisons
# describing the old trajectory.
func rebase_state_range(from_seq: int, to_seq: int, position_delta: Vector3, rotation_delta: Quaternion, linear_velocity_delta: Vector3, angular_velocity_delta: Vector3) -> void:
for seq in range(from_seq, to_seq + 1):
var prediction := get_prediction(seq)
if prediction.is_empty() or bool(prediction.get("unsimulated", false)):
continue
var state: NetBodyState = prediction["state"]
state.position += position_delta
state.rotation = (rotation_delta * state.rotation).normalized()
state.linear_velocity += linear_velocity_delta
state.angular_velocity += angular_velocity_delta
overwrite_state(seq, state)
# Produces comparison data only. Applying a snap, teleport, velocity delta,
# or visual offset belongs to later Phase 4 tasks.
func compare_authoritative(seq: int, authoritative: NetBodyState) -> Dictionary:
if seq > last_acknowledged_seq:
last_acknowledged_seq = seq
var prediction := get_prediction(seq)
if prediction.is_empty():
return {
"status": _missing_status(seq),
"seq": seq,
"authoritative_state": authoritative.copy(),
}
# A successful match is the only evidence that the acknowledgement clock
# has genuinely caught back up, so it is the only thing allowed to clear
# resync_required — a "missing_evicted"/"missing_not_recorded" result
# proves the opposite, and must leave the flag alone.
#
# The extra span check is not redundant. record() is not guaranteed to be
# called with consecutive sequences: input_lead_controller.update() can
# return 0 or up to 1+3, so the client's seq can skip forward, leaving a
# ring slot holding a tag OLDER than newest_recorded_seq - RING_SIZE
# (its residue was simply never rewritten). get_prediction() would still
# report that as "matched", so matching alone does not imply the
# outstanding window is back within capacity. Gate on the exact inverse
# of record()'s own trip inequality instead, which holds regardless of
# how sparsely sequences were recorded.
if newest_recorded_seq - last_acknowledged_seq <= RING_SIZE:
resync_required = false
if bool(prediction.get("unsimulated", false)):
# Reaching this sequence at all proves the acknowledgement clock is
# healthy — the entry is present and correctly tagged — so the
# resync_required clear above still applies. There is simply nothing
# to compare, because the client never simulated this sequence.
return {
"status": "unsimulated_gap",
"seq": seq,
"action": prediction["action"],
"authoritative_state": authoritative.copy(),
}
var predicted_state: NetBodyState = prediction["state"]
var position_error := authoritative.position - predicted_state.position
var rotation_error_radians := predicted_state.rotation.angle_to(authoritative.rotation)
return {
"status": "matched",
"seq": seq,
"action": prediction["action"],
"predicted_state": predicted_state,
"authoritative_state": authoritative.copy(),
"position_error": position_error,
"position_error_magnitude": position_error.length(),
"rotation_error_radians": rotation_error_radians,
"rotation_error_degrees": rad_to_deg(rotation_error_radians),
"linear_velocity_error": authoritative.linear_velocity - predicted_state.linear_velocity,
"angular_velocity_error": authoritative.angular_velocity - predicted_state.angular_velocity,
"contact_window": bool(prediction.get("contact_window", false)),
}
func _missing_status(seq: int) -> String:
# The server starts its acknowledgement clock at sequence 0, while the
# first local post-step prediction is normally sequence 1. This is a normal
# startup boundary, not a lost ring entry and must not trigger a hard snap.
if not _has_recorded or seq < _first_recorded_seq:
return "warmup_not_recorded"
if _has_recorded and seq <= newest_recorded_seq - RING_SIZE:
return "missing_evicted"
return "missing_not_recorded"
@@ -0,0 +1 @@
uid://goarfpbthyf6
+142 -10
View File
@@ -13,16 +13,15 @@ const BOTS_DIR := "res://bots"
# Every tier runs its promoted checkpoint at full trained capability —
# difficulty is a genuinely different policy, never the same policy
# handicapped with reaction delay or action noise. Easy and Medium are now
# distinct models (medium.json beats easy.json 65-22-13 head-to-head); Hard
# still points at medium.json, the strongest promoted policy, and stays a
# label-only duplicate until a stronger one earns hard.json. Keep the tiers
# handicapped with reaction delay or action noise. All three tiers are now
# distinct models: medium.json beats easy.json 65-22-13, and hard.json (the
# generation-5 Stage-5 policy) beats medium.json 47-32-21. Keep the tiers
# monotonic: never leave a lower tier pointing at a stronger model than the
# one above it.
const DIFFICULTIES := [
{"name": "Easy", "model": "res://bots/promoted/easy.json", "reaction_ticks": 8, "action_noise": 0.0},
{"name": "Medium", "model": "res://bots/promoted/medium.json", "reaction_ticks": 8, "action_noise": 0.0},
{"name": "Hard", "model": "res://bots/promoted/medium.json", "reaction_ticks": 8, "action_noise": 0.0},
{"name": "Hard", "model": "res://bots/promoted/hard.json", "reaction_ticks": 8, "action_noise": 0.0},
]
@onready var difficulty_dropdown: OptionButton = %DifficultyDropdown
@@ -31,9 +30,18 @@ const DIFFICULTIES := [
@onready var dev_bot_dropdown: OptionButton = %DevBotDropdown
@onready var bot_a_dropdown: OptionButton = %BotADropdown
@onready var bot_b_dropdown: OptionButton = %BotBDropdown
@onready var join_address_edit: LineEdit = %JoinAddressEdit
@onready var multiplayer_error_label: Label = %MultiplayerErrorLabel
@onready var connecting_overlay: Control = %ConnectingOverlay
@onready var connecting_status_label: Label = %ConnectingStatusLabel
func _ready() -> void:
AudioManager.bind_tree_buttons(self)
# An idle menu has no reason to render past the display's own refresh
# rate; gameplay scenes are uncapped again by _leave_to_gameplay below.
var refresh_rate := DisplayServer.screen_get_refresh_rate()
Engine.max_fps = int(refresh_rate) if refresh_rate > 0 else 0
_populate_difficulty_dropdown()
_populate_arena_dropdown()
dev_section.visible = OS.is_debug_build()
@@ -42,7 +50,25 @@ func _ready() -> void:
_populate_dropdown(dev_bot_dropdown, bots, GameSettings.dev_bot_override_path, true)
_populate_dropdown(bot_a_dropdown, bots, GameSettings.spectate_bot_a_path)
_populate_dropdown(bot_b_dropdown, bots, GameSettings.spectate_bot_b_path)
$CenterContainer/VBoxContainer/FreePlayButton.grab_focus()
NetworkManager.connected_to_server.connect(_on_connected_to_server)
NetworkManager.connection_failed.connect(_on_connection_failed)
%FreePlayButton.grab_focus()
# main_menu.gd's first async flow (task 1.7): Host is synchronous
# (NetworkManager.host() either succeeds immediately or fails immediately),
# but Join is not — it can take anywhere from a clean local-network round
# trip to ENet's own ~5s connect timeout to resolve, so unlike every other
# handler in this file (GameSettings.x = y; change_scene_to_file(...)) it
# needs a loading state (ConnectingOverlay), a cancel path, and a failure
# path that returns the player to a sane, retryable menu state rather than
# just hanging with no feedback.
func _process(_delta: float) -> void:
NetworkManager.poll()
func _physics_process(_delta: float) -> void:
NetworkManager.poll()
func _populate_difficulty_dropdown() -> void:
@@ -94,6 +120,11 @@ func _list_bots() -> Array[String]:
# disk, else the newest (last) bot.
func _populate_dropdown(dropdown: OptionButton, bots: Array[String], preferred_path: String, include_none: bool = false) -> void:
dropdown.clear()
# These are filled from whatever checkpoints happen to be in res://bots, so
# a long filename would otherwise widen the OptionButton (size_flags_h =
# EXPAND_FILL) and drag the whole menu past its 420px minimum width.
dropdown.clip_text = true
dropdown.fit_to_longest_item = false
if include_none:
dropdown.add_item("(Use difficulty)")
dropdown.set_item_metadata(0, "")
@@ -115,10 +146,19 @@ func _selected_path(dropdown: OptionButton) -> String:
return ""
# The menu's own refresh-rate fps cap (see _ready) is a menu-only concern;
# gameplay scenes respect the player's own VideoSettings fps cap instead
# (task 0.17), which only actually caps anything when vsync is Disabled and a
# divisor is chosen — otherwise this uncaps exactly like the old hardcoded 0.
func _leave_to_gameplay(scene_path: String) -> void:
VideoSettings.apply_fps_cap()
get_tree().change_scene_to_file(scene_path)
func _on_free_play_pressed() -> void:
var chosen: Dictionary = ArenaRegistry.ARENAS[0] if arena_dropdown.selected < 0 else ArenaRegistry.ARENAS[arena_dropdown.selected]
GameSettings.selected_arena_path = chosen["path"]
get_tree().change_scene_to_file("res://scenes/free_play.tscn")
_leave_to_gameplay("res://scenes/free_play.tscn")
func _on_match_pressed() -> void:
@@ -134,14 +174,106 @@ func _on_match_pressed() -> void:
GameSettings.selected_bot_path = override_path
GameSettings.selected_bot_reaction_ticks = -1
GameSettings.selected_bot_action_noise = -1.0
get_tree().change_scene_to_file("res://scenes/match.tscn")
_leave_to_gameplay("res://scenes/match.tscn")
func _on_settings_pressed() -> void:
get_tree().change_scene_to_file("res://scenes/settings.tscn")
get_tree().change_scene_to_file(ScenePaths.SETTINGS)
func _on_spectate_pressed() -> void:
GameSettings.spectate_bot_a_path = _selected_path(bot_a_dropdown)
GameSettings.spectate_bot_b_path = _selected_path(bot_b_dropdown)
get_tree().change_scene_to_file("res://scenes/spectate.tscn")
_leave_to_gameplay("res://scenes/spectate.tscn")
func _on_host_pressed() -> void:
_clear_multiplayer_error()
var err := NetworkManager.host()
if err != OK:
_show_multiplayer_error("Could not host: %s" % error_string(err))
return
_leave_to_lobby()
func _on_find_match_pressed() -> void:
get_tree().change_scene_to_file("res://scenes/matchmaking.tscn")
func _on_join_pressed() -> void:
_start_join()
func _on_join_address_submitted(_new_text: String) -> void:
_start_join()
# ENet's own give-up-and-fire-connection_failed schedule is not bounded to
# anything a menu should make a player wait for — verified empirically
# (tests/main_menu_test_hooks.gd's join_refused case) against a genuinely
# refused loopback connection: connection_failed never fired within 14s.
# This timer is what actually guarantees "connection-refused reaches a sane
# UI state" rather than leaving the overlay up indefinitely.
const CONNECT_TIMEOUT_SECONDS := 6.0
var _connect_timeout_token := 0 # bumped on every new attempt/cancel/resolution so a stale timer callback is a no-op
func _start_join() -> void:
_clear_multiplayer_error()
var address := join_address_edit.text.strip_edges()
if address.is_empty():
_show_multiplayer_error("Enter an IP address to join")
return
var err := NetworkManager.join(address)
if err != OK:
_show_multiplayer_error("Could not join: %s" % error_string(err))
return
connecting_status_label.text = "Connecting to %s..." % address
connecting_overlay.visible = true
_connect_timeout_token += 1
var my_token := _connect_timeout_token
get_tree().create_timer(CONNECT_TIMEOUT_SECONDS).timeout.connect(func(): _on_connect_timeout(my_token))
func _on_connect_timeout(token: int) -> void:
if token != _connect_timeout_token or not connecting_overlay.visible:
return # a newer attempt (or Cancel, or a real success/failure) already resolved this
NetworkManager.shutdown()
connecting_overlay.visible = false
_show_multiplayer_error("Connection timed out — check the address and that a server is hosting on that port")
func _on_connecting_cancel_pressed() -> void:
_connect_timeout_token += 1
NetworkManager.shutdown()
connecting_overlay.visible = false
func _on_connected_to_server() -> void:
if not connecting_overlay.visible:
return # e.g. a stray/late signal after Cancel already shut the peer down
_connect_timeout_token += 1
connecting_overlay.visible = false
_leave_to_lobby()
func _on_connection_failed() -> void:
if not connecting_overlay.visible:
return
_connect_timeout_token += 1
connecting_overlay.visible = false
_show_multiplayer_error("Connection failed — check the address and that a server is hosting on that port")
func _leave_to_lobby() -> void:
get_tree().change_scene_to_file("res://scenes/lobby.tscn")
func _show_multiplayer_error(message: String) -> void:
multiplayer_error_label.text = message
multiplayer_error_label.visible = true
func _clear_multiplayer_error() -> void:
multiplayer_error_label.visible = false
+2
View File
@@ -122,6 +122,7 @@ func _run_kickoff_countdown() -> void:
_set_frozen(true)
for count in range(KICKOFF_COUNTDOWN_SECONDS, 0, -1):
kickoff_countdown.emit(count)
AudioManager.play_countdown(count)
# process_always=false: if full-time fires mid-countdown (see
# _on_match_timer_timeout's get_tree().paused = true), this stalls
# harmlessly in lockstep with the pause instead of ticking a
@@ -132,6 +133,7 @@ func _run_kickoff_countdown() -> void:
if _match_over:
return
kickoff_countdown.emit(0)
AudioManager.play_countdown(0)
_set_frozen(false)
+668
View File
@@ -0,0 +1,668 @@
extends Node
# Autoload (project.godot [autoload] MatchNet). Handshake + roster layer on
# top of NetworkManager's raw transport (§2.5, §1.3 of MULTIPLAYER_SPEC.md).
# hello/welcome, strict protocol_version and physics_ticks_per_second
# gating, player_joined/player_left, and — since lobby.tscn (task 1.5) needs
# somewhere durable to keep it across the lobby→match scene transition —
# each player's team and ready state. Slot assignment (fixed spawn index
# within a team) is NOT here; that's match spawn's job in Phase 2, derived
# from this roster's team field at spawn time, not stored redundantly here.
const NetCodec = preload("res://scripts/net_codec.gd")
const SimConstants = preload("res://scripts/sim_constants.gd")
const AssignmentState = preload("res://scripts/assignment_state.gd")
signal player_joined(peer_id: int, player_name: String)
signal player_left(peer_id: int)
signal player_state_changed(peer_id: int, team: int, ready: bool)
signal rejected(reason: String) # client-side only: the server refused our hello
signal welcomed() # client-side only: our hello was accepted
signal server_shutdown(reason: String) # client-side notification before planned close
signal result_submission_accepted
signal result_submission_retrying(http_code: int)
const TEAM_COUNT := 2
const RECONNECT_GRACE_SECONDS := 60.0
# player_name is the one client-supplied value in _hello that gets broadcast
# verbatim to every other peer (protocol_version/tick_hz are checked, never
# relayed). MAX_INPUT_LENGTH is a reject threshold, checked before touching
# the string at all — a legitimate client only ever sends local_player_name,
# which the UI already keeps short, so anything past this is a bug or an
# attacker, not a real name to truncate politely. Adversarial review found
# an unbounded name relayed to every peer head-of-line-blocks the reliable
# control channel hard enough that a concurrently-joining client's own
# _welcome never arrived — this is what closes that.
const MAX_INPUT_LENGTH := 256
const MAX_PLAYER_NAME_LENGTH := 24
class PlayerInfo:
var peer_id: int
var player_name: String
var player_identity: String
var team: int = 0
var spawn_index: int = -1
var ready: bool = false
func _init(p_peer_id: int, p_player_name: String, p_team: int = 0, p_ready: bool = false, p_player_identity: String = "") -> void:
peer_id = p_peer_id
player_name = p_player_name
player_identity = p_player_identity
team = p_team
ready = p_ready
var roster: Dictionary = {} # peer_id (int) -> PlayerInfo. Never contains peer 1 (the server; §1.1 decision 2 — dedicated servers are never a player).
var local_player_name := "Player"
var last_server_shutdown_reason := ""
# Set by the assignment connection path. Direct-IP/community-server joins keep
# this empty for backwards compatibility; allocated matches carry the opaque
# signed authorisation in hello rather than putting it in the endpoint URL.
var join_authorisation := ""
var require_join_authorisation := false
var admissions_open := true
var _allowed_join_authorisations: Dictionary = {}
var _active_join_peers: Dictionary = {} # opaque authorisation -> peer_id
var _join_history: Dictionary = {} # token -> {generation, lost_at}
var _join_authorisation_context: Dictionary = {}
# Key ID -> raw HMAC key. A set rather than a single key so a signing-key
# rotation does not invalidate authorisations already issued for in-flight
# matches: the allocator signs with the new key while servers still accept
# both, and the old key is dropped once no live match can reference it.
var _join_signing_keys := {}
var _connection_lease_claim := Callable()
var _connection_lease_disconnect := Callable()
var _result_submit := Callable()
# Test hook (tests/match_net_smoke.gd): set false before connecting to
# suppress the automatic real hello, so a test can send a deliberately
# mismatched one instead to exercise the rejection path.
var _auto_hello := true
func _ready() -> void:
NetworkManager.client_disconnected.connect(_on_peer_disconnected)
NetworkManager.connected_to_server.connect(_on_connected_to_server)
NetworkManager.disconnected_from_server.connect(_on_disconnected_from_server)
NetworkManager.shutting_down.connect(_on_shutting_down)
func _on_connected_to_server() -> void:
roster.clear()
last_server_shutdown_reason = ""
if _auto_hello:
_hello.rpc_id(1, NetCodec.PROTOCOL_VERSION, SimConstants.TICK_HZ, local_player_name, join_authorisation)
func _on_disconnected_from_server() -> void:
roster.clear()
# Covers the case _on_disconnected_from_server doesn't: a HOST calling
# NetworkManager.shutdown() itself (Leave, or hosting again after already
# hosting) never fires disconnected_from_server — that signal only fires
# from an incoming multiplayer.server_disconnected event, which a server
# never receives about itself. Without this, roster (and every peer's team/
# ready state in it) would persist forever across a host/re-host cycle in
# the same process.
func _on_shutting_down() -> void:
roster.clear()
_allowed_join_authorisations.clear()
_active_join_peers.clear()
_join_history.clear()
_join_authorisation_context.clear()
_join_signing_keys = {}
_connection_lease_claim = Callable()
_connection_lease_disconnect = Callable()
_result_submit = Callable()
require_join_authorisation = false
admissions_open = true
# signing_keys maps key ID to raw key bytes. An empty dictionary disables
# signature verification, which is only valid for local/direct-hosted play.
func configure_join_authorisations(tokens: Array, context: Dictionary, signing_keys: Dictionary = {}) -> bool:
var allowed := {}
for token in tokens:
if not token is String or String(token).is_empty():
return false
allowed[String(token)] = true
if allowed.is_empty() or not context.has("match_id") or not context["match_id"] is String or String(context["match_id"]).is_empty() or not context.has("server_id") or not context["server_id"] is String or String(context["server_id"]).is_empty() or not context.has("protocol_version") or not _valid_integer_claim(context["protocol_version"]) or int(context["protocol_version"]) < 1:
return false
_allowed_join_authorisations = allowed
_join_authorisation_context = context.duplicate(true)
_join_signing_keys = {}
for key_id in signing_keys:
var raw = signing_keys[key_id]
if not raw is PackedByteArray or PackedByteArray(raw).is_empty():
return false
_join_signing_keys[str(key_id)] = PackedByteArray(raw).duplicate()
require_join_authorisation = true
return true
func assigned_player_slots() -> Array:
var result: Array = []
var seen_identities := {}
var seen_slots := {}
for token in _allowed_join_authorisations.keys():
var claims := _join_claims(String(token))
if claims.is_empty():
return []
var identity := str(claims.get("PlayerID", ""))
var team := int(claims.get("Team", -1))
var slot := int(claims.get("Slot", -1))
if identity.is_empty() or team < 0 or team >= TEAM_COUNT or slot < 0 or slot > 5 or slot / 3 != team or seen_identities.has(identity) or seen_slots.has(slot):
return []
seen_identities[identity] = true
seen_slots[slot] = true
result.append({
"player_identity": identity,
"team": team,
"slot": slot,
})
result.sort_custom(func(a: Dictionary, b: Dictionary) -> bool: return int(a["slot"]) < int(b["slot"]))
return result
func player_identity(peer_id: int) -> String:
if not roster.has(peer_id):
return ""
return String((roster[peer_id] as PlayerInfo).player_identity)
static func reservation_identity_matches(slot_identity: String, incoming_identity: String, slot_name: String, incoming_name: String) -> bool:
# Authenticated allocations must never fall back to a client-chosen display
# name. The name fallback exists only for direct, unauthenticated servers.
if not slot_identity.is_empty() or not incoming_identity.is_empty():
return not slot_identity.is_empty() and slot_identity == incoming_identity
return slot_name == incoming_name
# Server only: a raw ENet disconnect (crash, timeout) that never sent a
# proper hello just needs its (possibly absent) roster entry cleaned up.
# The normal leave path also goes through here after the server erases it,
# guarded by roster.erase()'s own has-check below.
func _on_peer_disconnected(peer_id: int) -> void:
if not multiplayer.is_server():
return
_cleanup_disconnected_peer(peer_id)
func _cleanup_disconnected_peer(peer_id: int) -> void:
NetworkManager.invalidate_peer(peer_id)
_remove_player(peer_id)
func _remove_player(peer_id: int) -> void:
for token in _active_join_peers.keys():
if int(_active_join_peers[token]) == peer_id:
_active_join_peers.erase(token)
var history: Dictionary = _join_history.get(token, {})
history["lost_at"] = Time.get_unix_time_from_system()
_join_history[token] = history
if _connection_lease_disconnect.is_valid():
_connection_lease_disconnect.call(_join_identity(token), int(history.get("generation", 0)))
break
if not roster.has(peer_id):
return
roster.erase(peer_id)
player_left.emit(peer_id)
# rpc() broadcasts to every peer in multiplayer.get_peers() — including,
# transiently, the very peer that just disconnected: this fires from
# NetworkManager's client_disconnected signal, and empirically that
# peer's own ENetConnection can still be momentarily present in the
# broadcast's target set with its channels already torn down, which
# logs "Unable to send packet on channel 0, max channels: 0" on every
# single disconnect (found by a second adversarial review — harmless to
# the game, since the departing peer obviously doesn't need to hear
# about its own departure, but it meant "clean stderr" wasn't actually
# clean for any test in this project).
#
# A first attempt filtered the broadcast down to rpc_id() calls that
# explicitly skip `peer_id`. That's necessary but not sufficient: when
# two peers disconnect within the same poll() batch (both bots quitting
# at the end of a CI run land within the same tick), get_peers() here
# can still list the SECOND peer as connected while its own disconnect
# event just hasn't been dispatched yet in this same batch — sending to
# it hits the identical error, one hop later. Defer the whole
# notification to the next idle frame instead of sending synchronously
# from inside signal-handling: by then poll() has fully returned, every
# disconnect event in this batch has been dispatched, and get_peers()
# reflects the settled, genuinely-still-connected set.
if is_inside_tree():
call_deferred("_broadcast_player_left", peer_id)
func _broadcast_player_left(peer_id: int) -> void:
for other_peer_id in multiplayer.get_peers():
if other_peer_id != peer_id:
_player_left.rpc_id(other_peer_id, peer_id)
func broadcast_server_shutdown(reason: String) -> void:
if not multiplayer.is_server():
return
var safe_reason := _sanitize_shutdown_reason(reason)
for peer_id in multiplayer.get_peers():
_server_shutdown.rpc_id(peer_id, safe_reason)
static func _sanitize_shutdown_reason(raw: String) -> String:
var clean := ""
for c in raw:
var code := c.unicode_at(0)
if code >= 0x20 and code != 0x7F:
clean += c
clean = clean.strip_edges()
if clean.length() > 96:
clean = clean.substr(0, 96)
return clean if not clean.is_empty() else "server_shutdown"
static func admission_rejection(is_open: bool) -> String:
return "" if is_open else "server is draining"
# Balances a new joiner onto whichever team currently has fewer players
# (ties go to team 0). Server only.
func _pick_balanced_team() -> int:
var counts := []
counts.resize(TEAM_COUNT)
counts.fill(0)
for info: PlayerInfo in roster.values():
counts[info.team] += 1
var best_team := 0
for team in range(TEAM_COUNT):
if counts[team] < counts[best_team]:
best_team = team
return best_team
@rpc("any_peer", "call_remote", "reliable")
func _hello(protocol_version: int, tick_hz: int, player_name: String, supplied_join_authorisation: String = "") -> void:
if not multiplayer.is_server():
return
var peer_id := multiplayer.get_remote_sender_id()
if roster.has(peer_id):
return # duplicate hello from an already-accepted peer; ignore
var admission_error := admission_rejection(admissions_open)
if not admission_error.is_empty():
await _reject(peer_id, admission_error)
return
if protocol_version != NetCodec.PROTOCOL_VERSION:
await _reject(peer_id, "protocol version mismatch: server=%d client=%d" % [NetCodec.PROTOCOL_VERSION, protocol_version])
return
if tick_hz != SimConstants.TICK_HZ:
await _reject(peer_id, "physics tick rate mismatch: server=%d client=%d" % [SimConstants.TICK_HZ, tick_hz])
return
if require_join_authorisation and not _valid_join_authorisation(supplied_join_authorisation):
await _reject(peer_id, "join authorisation rejected")
return
if require_join_authorisation and _active_join_peers.has(supplied_join_authorisation):
await _reject(peer_id, "join authorisation already in use")
return
var join_generation := 1
if require_join_authorisation:
join_generation = await _claim_join_authorisation(supplied_join_authorisation, peer_id)
if join_generation < 0:
await _reject(peer_id, "join authorisation lease rejected")
return
if player_name.length() > MAX_INPUT_LENGTH:
await _reject(peer_id, "player name too long")
return
var clean_name := _sanitize_player_name(player_name)
var identity := _join_identity(supplied_join_authorisation) if require_join_authorisation else clean_name
if identity.is_empty():
await _reject(peer_id, "join authorisation rejected")
return
# Tell the new peer about everyone already here before anyone is told
# about them, so no client ever observes an unknown peer_id in a
# player_joined it didn't get a prior player_joined for.
for existing_id: int in roster.keys():
var existing: PlayerInfo = roster[existing_id]
_player_joined.rpc_id(peer_id, existing_id, existing.player_name, existing.team, existing.ready)
var team := _pick_balanced_team()
var spawn_index := -1
if require_join_authorisation:
var claims := _join_claims(supplied_join_authorisation)
var assigned_slot := int(claims.get("Slot", -1))
var assigned_team := int(claims.get("Team", -1))
if assigned_slot < 0 or assigned_slot > 5 or assigned_team < 0 or assigned_team >= TEAM_COUNT or assigned_slot / 3 != assigned_team:
await _reject(peer_id, "join authorisation rejected")
return
team = assigned_team
spawn_index = assigned_slot % 3
var info := PlayerInfo.new(peer_id, clean_name, team, false, identity)
info.spawn_index = spawn_index
roster[peer_id] = info
if require_join_authorisation:
# _reserve_join_authorisation already owns the active peer reservation;
# keeping the generation in the history makes fencing auditable without
# exposing it to the client.
_join_history[supplied_join_authorisation]["generation"] = join_generation
player_joined.emit(peer_id, clean_name) # local: the broadcast below is call_remote, never loops back to the server itself
_welcome.rpc_id(peer_id)
_player_joined.rpc(peer_id, clean_name, team, false) # broadcast, includes the new peer itself
func _valid_join_authorisation(token: String) -> bool:
if token.is_empty() or not _allowed_join_authorisations.has(token):
return false
var standard_token := token.replace("-", "+").replace("_", "/")
while standard_token.length() % 4 != 0:
standard_token += "="
var decoded := Marshalls.base64_to_raw(standard_token)
if decoded.is_empty():
return false
var envelope = JSON.parse_string(decoded.get_string_from_utf8())
if not envelope is Dictionary or not envelope.has("Authorisation") or not envelope.has("Signature") or str(envelope["Signature"]).is_empty():
return false
var claims = envelope["Authorisation"]
if not claims is Dictionary:
return false
for string_claim in ["MatchID", "ServerID", "PlayerID", "SteamID", "Protocol", "ExpiresAt"]:
if not claims.has(string_claim) or not claims[string_claim] is String or String(claims[string_claim]).is_empty():
return false
for integer_claim in ["Slot", "Team", "Generation"]:
if not claims.has(integer_claim) or not _valid_integer_claim(claims[integer_claim]):
return false
if not envelope["Signature"] is String or String(envelope["Signature"]).is_empty():
return false
var claimed_team := int(claims.get("Team", -1))
var claimed_slot := int(claims.get("Slot", -1))
if claimed_team < 0 or claimed_team >= TEAM_COUNT or claimed_slot < 0 or claimed_slot > 5 or claimed_slot / 3 != claimed_team:
return false
var protocol := str(claims.get("Protocol", ""))
var expires_at := str(claims.get("ExpiresAt", ""))
if not AssignmentState.is_valid_expiry_timestamp(expires_at):
return false
var expiry := Time.get_unix_time_from_datetime_string(expires_at)
if not _join_signing_keys.is_empty():
var signature_token := str(envelope["Signature"])
var signature := Marshalls.base64_to_raw(signature_token)
if signature.size() != 32:
return false
# The key ID selects which of the currently-valid keys signed this
# authorisation, so the allocator can rotate without invalidating
# authorisations already issued for in-flight matches. It is part of
# the signed bytes below, so pointing it at a different key simply
# fails verification rather than choosing a weaker key.
var key_id := str(claims.get("KeyID", ""))
if not _join_signing_keys.has(key_id):
return false
var signing_key: PackedByteArray = _join_signing_keys[key_id]
if signing_key.is_empty():
return false
var canonical := PackedByteArray()
# Must stay byte-identical to server/domain/join_auth.go's
# JoinAuthorisationBytes; the two change together or every join fails.
var fields := [
str(claims.get("MatchID", "")), str(claims.get("ServerID", "")),
str(claims.get("PlayerID", "")), str(claims.get("SteamID", "")),
str(int(claims.get("Slot", -1))), str(int(claims.get("Team", -1))), protocol,
str(int(claims.get("Generation", 0))), expires_at, key_id,
]
for index in fields.size():
canonical.append_array(String(fields[index]).to_utf8_buffer())
if index < fields.size() - 1:
canonical.append(0)
var hmac := HMACContext.new()
hmac.start(HashingContext.HASH_SHA256, signing_key)
hmac.update(canonical)
if hmac.finish() != signature:
return false
return str(claims.get("MatchID", "")) == str(_join_authorisation_context.get("match_id", "")) \
and str(claims.get("ServerID", "")) == str(_join_authorisation_context.get("server_id", "")) \
and protocol == str(_join_authorisation_context.get("protocol", "")) \
and int(claims.get("Slot", -1)) >= 0 and int(claims.get("Slot", -1)) <= 5 \
and expiry > Time.get_unix_time_from_system()
static func _valid_integer_claim(value: Variant) -> bool:
if value is int:
return int(value) >= 0
if value is float:
return is_finite(float(value)) and float(value) >= 0.0 and float(value) == floor(float(value))
return false
func _join_identity(token: String) -> String:
if token.is_empty():
return ""
var standard_token := token.replace("-", "+").replace("_", "/")
while standard_token.length() % 4 != 0:
standard_token += "="
var decoded := Marshalls.base64_to_raw(standard_token)
if decoded.is_empty():
return ""
var envelope = JSON.parse_string(decoded.get_string_from_utf8())
if not envelope is Dictionary or not envelope.has("Authorisation") or not envelope["Authorisation"] is Dictionary:
return ""
return str(envelope["Authorisation"].get("PlayerID", ""))
func _join_claims(token: String) -> Dictionary:
if token.is_empty():
return {}
var standard_token := token.replace("-", "+").replace("_", "/")
while standard_token.length() % 4 != 0:
standard_token += "="
var decoded := Marshalls.base64_to_raw(standard_token)
if decoded.is_empty():
return {}
var envelope = JSON.parse_string(decoded.get_string_from_utf8())
if not envelope is Dictionary or not envelope.has("Authorisation") or not envelope["Authorisation"] is Dictionary:
return {}
return envelope["Authorisation"]
func is_join_authorisation_active(token: String) -> bool:
return not token.is_empty() and _active_join_peers.has(token)
func configure_connection_lease_callbacks(claim: Callable, disconnect: Callable) -> void:
_connection_lease_claim = claim
_connection_lease_disconnect = disconnect
func configure_result_submission(callback: Callable) -> void:
_result_submit = callback
func submit_authoritative_result(score: Dictionary, integrity_state := "CERTIFIED") -> bool:
if not _result_submit.is_valid() or not score.has(0) or not score.has(1):
return false
_result_submit.call(int(score[0]), int(score[1]), integrity_state)
return true
func _claim_join_authorisation(token: String, peer_id: int) -> int:
var expected_generation := _available_join_generation(token)
if expected_generation < 0:
return -1
var generation := expected_generation + 1
if _connection_lease_claim.is_valid():
var response = await _connection_lease_claim.call(_join_identity(token), expected_generation)
generation = lease_claim_generation(response, expected_generation)
if generation < 0:
return -1
# The await above deliberately allows one bounded control-plane request.
# Re-evaluate every local fact that can change during that suspension before
# publishing the reservation. If a durable claim succeeded, close it again.
# A concurrent same-token hello can receive the same idempotent claim; its
# loser must not close the generation now owned by the local winner.
if _active_join_peers.has(token):
return -1
if not admissions_open or not _valid_join_authorisation(token) or peer_id not in multiplayer.get_peers():
if _connection_lease_disconnect.is_valid():
_connection_lease_disconnect.call(_join_identity(token), generation)
return -1
_join_history[token] = {"generation": generation, "lost_at": 0.0}
_active_join_peers[token] = peer_id
return generation
func _available_join_generation(token: String) -> int:
if token.is_empty() or _active_join_peers.has(token):
return -1
var now := Time.get_unix_time_from_system()
var history: Dictionary = _join_history.get(token, {})
var lost_at := float(history.get("lost_at", 0.0))
if lost_at > 0.0 and (now < lost_at or now - lost_at > RECONNECT_GRACE_SECONDS):
return -1
return int(history.get("generation", 0))
static func lease_claim_generation(response, expected_generation: int) -> int:
if not response is Dictionary or expected_generation < 0:
return -1
var status := String(response.get("status", ""))
if status not in ["claimed", "unavailable"] or not response.get("generation") is int:
return -1
var generation := int(response["generation"])
if status == "unavailable":
return generation if expected_generation > 0 and generation == expected_generation + 1 else -1
# A durable backend may return a later generation only to a fresh process
# recovering an already-disconnected lease. Locally known generations never
# skip, and outage fallback never invents a jump.
return generation if generation == expected_generation + 1 or (expected_generation == 0 and generation > 1) else -1
func _reserve_join_authorisation(token: String, peer_id: int) -> int:
var expected_generation := _available_join_generation(token)
if expected_generation < 0:
return -1
var generation := expected_generation + 1
_join_history[token] = {"generation": generation, "lost_at": 0.0}
_active_join_peers[token] = peer_id
return generation
# Strips control/formatting characters (so a name can't corrupt a log line
# or blow out UI layout with e.g. embedded newlines) and clamps to display
# length. Input is already bounded to MAX_INPUT_LENGTH by the caller before
# this runs, so this never iterates an attacker-sized string. static: pure
# function of its argument, doesn't touch roster/multiplayer — also lets
# tests/cases/test_match_net.gd call it with no Node instantiation.
static func _sanitize_player_name(raw: String) -> String:
var clean := ""
for c in raw:
var code := c.unicode_at(0)
if code >= 0x20 and code != 0x7F:
clean += c
clean = clean.strip_edges()
if clean.length() > MAX_PLAYER_NAME_LENGTH:
clean = clean.substr(0, MAX_PLAYER_NAME_LENGTH)
if clean.is_empty():
clean = "Player"
return clean
func _reject(peer_id: int, reason: String) -> void:
_rejected.rpc_id(peer_id, reason)
# §9 gotcha 26: a reliable RPC just queued still needs a beat of polling
# to actually reach the wire before we pull the connection out from
# under it.
await get_tree().create_timer(0.3).timeout
if multiplayer.multiplayer_peer is ENetMultiplayerPeer:
multiplayer.multiplayer_peer.disconnect_peer(peer_id)
# Client-callable requests. Both are fire-and-forget: the authoritative
# change comes back through _state_changed once the server applies it, same
# as everyone else's — a client never mutates its own roster entry directly.
func request_set_team(team: int) -> void:
_set_team.rpc_id(1, team)
func request_set_ready(ready: bool) -> void:
_set_ready.rpc_id(1, ready)
@rpc("any_peer", "call_remote", "reliable")
func _set_team(team: int) -> void:
if not multiplayer.is_server():
return
var peer_id := multiplayer.get_remote_sender_id()
if not _apply_team_change(peer_id, team):
return
var info: PlayerInfo = roster[peer_id]
player_state_changed.emit(peer_id, info.team, info.ready)
_state_changed.rpc(peer_id, info.team, info.ready)
func _apply_team_change(peer_id: int, team: int) -> bool:
# In allocated matches team and global slot are signed together. Changing
# only team would produce a roster that disagrees with the assignment and
# leave spawn_index anchored to the old team.
if require_join_authorisation:
return false
if not roster.has(peer_id) or team < 0 or team >= TEAM_COUNT:
return false
var info: PlayerInfo = roster[peer_id]
if info.team == team:
return false
info.team = team
info.ready = false # switching teams un-readies — the roster you were ready against just changed
return true
@rpc("any_peer", "call_remote", "reliable")
func _set_ready(ready: bool) -> void:
if not multiplayer.is_server():
return
var peer_id := multiplayer.get_remote_sender_id()
if not roster.has(peer_id):
return
var info: PlayerInfo = roster[peer_id]
if info.ready == ready:
return
info.ready = ready
player_state_changed.emit(peer_id, info.team, info.ready)
_state_changed.rpc(peer_id, info.team, info.ready)
@rpc("authority", "call_remote", "reliable")
func _state_changed(peer_id: int, team: int, ready: bool) -> void:
if not roster.has(peer_id):
return
var info: PlayerInfo = roster[peer_id]
info.team = team
info.ready = ready
player_state_changed.emit(peer_id, team, ready)
@rpc("authority", "call_remote", "reliable")
func _welcome() -> void:
welcomed.emit()
@rpc("authority", "call_remote", "reliable")
func _rejected(reason: String) -> void:
rejected.emit(reason)
@rpc("authority", "call_remote", "reliable")
func _server_shutdown(reason: String) -> void:
last_server_shutdown_reason = _sanitize_shutdown_reason(reason)
server_shutdown.emit(last_server_shutdown_reason)
@rpc("authority", "call_remote", "reliable")
func _player_joined(peer_id: int, player_name: String, team: int, ready: bool) -> void:
roster[peer_id] = PlayerInfo.new(peer_id, player_name, team, ready)
player_joined.emit(peer_id, player_name)
@rpc("authority", "call_remote", "reliable")
func _player_left(peer_id: int) -> void:
if not roster.has(peer_id):
return
roster.erase(peer_id)
player_left.emit(peer_id)
+1
View File
@@ -0,0 +1 @@
uid://b8300uu0s6jqt
+547
View File
@@ -0,0 +1,547 @@
extends Node
# Autoload (project.godot [autoload] MatchSim). Phase 2 simulation RPCs:
# match_config (server assigns arena + deterministic slot order from
# MatchNet.roster), input (client -> server, per-tick action), snapshot
# (server -> client, NetCodec-packed body state), and a small score_update
# for the HUD. Lives on an autoload per §1.3's derived decision ("All
# hot-path RPCs live on autoloads") even though these are scoped to
# whichever match happens to be running — a scene-node RPC target would
# need matching NodePaths across peers, which an autoload sidesteps
# entirely, and it's what lets NetworkedMatch itself stay a plain scene
# node with no networking-identity concerns of its own.
#
# Channel intent per §2.1: 0 reliable (match_config, score_update), 1
# unreliable-ordered (input), 2 unreliable-ordered (snapshot) — not yet
# verified against ENet's own reserved system channel offset (§2.1's own
# "verify empirically" hedge); if that turns out to matter these indices
# will need adjusting, not the RPC design itself.
const NetCodec = preload("res://scripts/net_codec.gd")
signal match_config_received(arena_path: String, peer_ids: PackedInt32Array, teams: PackedInt32Array, spawn_indices: PackedInt32Array)
signal input_received(peer_id: int, decoded: Dictionary) # decoded: see NetCodec.unpack_input
# Task 5.10. A packet this autoload dropped before it could ever reach a match,
# with the verbatim bytes — the replay log's whole reason to exist is the field
# report "my input did nothing", and an accepted-input-only log has thrown away
# exactly the evidence that would explain it. `reason` is an InputRejectReason;
# the transport layer deliberately does not know about the replay format's own
# record kinds, so the mapping lives at the listener.
signal input_rejected(peer_id: int, reason: int, bytes: PackedByteArray)
signal snapshot_received(decoded: Dictionary) # decoded: see NetCodec.unpack_snapshot
signal score_update_received(score: Dictionary)
signal state_change_received(state: int, at_tick: int) # §6.1 MatchState.State
# §6.2 step 6. positions/rotations are body-order: every slot in order, then
# the ball — the same order the snapshot uses, so one convention covers both.
# rotations is 4 floats per body (x, y, z, w).
signal kickoff_received(positions: PackedVector3Array, rotations: PackedFloat32Array, countdown_start_tick: int, reset_gen: int)
signal goal_scored_received(scoring_team: int, score: Dictionary, goal_tick: int, resume_tick: int)
signal clock_state_received(running: bool, end_tick: int, remaining_ticks: int, at_tick: int)
signal match_bootstrap_received(state: int, at_tick: int, score: Dictionary, end_tick: int, clock_running: bool, reset_gen: int, remaining_ticks: int)
# §6.3 task 5.8: a spectator has been given a vacated slot at a kickoff.
signal slot_assigned_received(peer_id: int, slot_index: int)
# Input validation (MULTIPLAYER_SPEC.md §3.1 steps 2-3; multiplayer-next.md task 3.4). Deliberately
# lives here rather than in NetworkedMatch: framing/rate abuse is a protocol-
# level concern independent of any particular match's roster/slot state, and
# this autoload already owns the RPC that receives the raw bytes.
#
# 60Hz * 1.5 + 20, per §3.1 step 2's own numbers.
const RATE_LIMIT_PACKETS_PER_SEC := 110
# "Same for a byte budget" (§3.1 step 2) — the worst-case legitimate packet
# is a full-redundancy input (INPUT_HEADER_SIZE + MAX_REDUNDANCY entries,
# the "40 B input" §2.3 sizes to), so the byte budget is just the packet
# budget scaled by that worst-case size — no separate constant to keep in
# sync by hand.
const RATE_LIMIT_BYTES_PER_SEC := RATE_LIMIT_PACKETS_PER_SEC * (NetCodec.INPUT_HEADER_SIZE + NetCodec.MAX_REDUNDANCY * NetCodec.INPUT_ENTRY_SIZE)
const RATE_LIMIT_WINDOW_MS := 1000
# Leaky-bucket excess tolerance, expressed in the same "N seconds' worth of
# budget" terms the original consecutive-streak design used. An adversarial
# review found that design — a streak counter that HARD-RESET to 0 on any
# single clean window — was trivially evaded by a duty-cycled flood (burst,
# then one clean window, repeat): reproduced sustaining ~33x the packet
# budget indefinitely with zero disconnect warnings. A leaky bucket doesn't
# care how the excess is distributed in time — see the window-roll logic
# below for how it accumulates and drains.
const RATE_LIMIT_EXCESS_PACKETS_TO_DISCONNECT := RATE_LIMIT_PACKETS_PER_SEC * 3
const RATE_LIMIT_EXCESS_BYTES_TO_DISCONNECT := RATE_LIMIT_BYTES_PER_SEC * 3
const MALFORMED_LIMIT_TO_DISCONNECT := 20
# Task 5.10: how many rejected packets per peer per rate-limit window are
# forwarded to `input_rejected`. Sized so an honest client — whose rejects are
# occasional by definition, since a client rejected every tick is a bug the log
# is meant to catch — is never sampled away, while a flood cannot turn the log
# into unbounded attacker-controlled disk writes.
const REJECTS_RECORDED_PER_WINDOW := 8
# Server-stall grace (found by task 5.10's own reject recording, which is the
# only reason it was visible at all).
#
# When the server stalls — a 2s SIGSTOP stands in for a GC/IO/scheduler hitch —
# the client keeps sending at 60Hz throughout, and ENet delivers that entire
# backlog in the first window after resume. Measured: 70 of an HONEST client's
# input packets rejected as "rate limit exceeded", against a limit the client
# never came close to violating on its own. Redundancy does not cover it: the
# dropped packets are CONTIGUOUS, so each one's redundancy window falls inside
# the same dropped run — 0 of 70 were rescued, and 82 of 923 sequences (8.88%,
# ~1.4s of that player's input) never reached the server at all, versus 0.00%
# missing on an otherwise identical run with no stall. Every prediction gate
# still passed, which is exactly why this needed the log to find.
#
# So: don't rate-limit a backlog the server itself caused. The grace is capped,
# expires after two windows, and is granted only to peers already being
# tracked, so it cannot be farmed by a peer that connects during the stall. An
# attacker who can induce server stalls to earn budget already has a strictly
# worse capability than sending extra input packets.
const STALL_DETECT_MS := 250
const MAX_STALL_GRACE_PACKETS := SimConstants.TICK_HZ * 4 # 4s of a 60Hz client's backlog
const STALL_GRACE_WINDOWS := 2
enum InputRejectReason {
MALFORMED = 0,
RATE_LIMIT = 1,
}
class _PeerInputState:
var window_start_ms := 0
var packets_this_window := 0
var bytes_this_window := 0
# Leaky bucket: grows by this window's actual total, drains by one
# window's worth of budget, every window — regardless of whether that
# window was itself over or under budget. A steady rate at or under
# budget nets to zero forever (never accumulates); any sustained AVERAGE
# above budget accumulates over time no matter how it's shaped into
# bursts, unlike a streak counter a clean gap can reset to 0.
var excess_packets := 0.0
var excess_bytes := 0.0
var malformed_count := 0
# Reject-recording budget for the current window. Without it the diagnostic
# is a remote disk-fill amplifier: the attacker chooses the flood rate, and
# every dropped packet would otherwise become a disk write. Capped per
# window, reset with the window itself, so an honest client's occasional
# reject is always captured while a flood contributes a bounded sample.
var rejects_recorded_this_window := 0
# Extra packets this peer may send before the limiter treats it as abuse,
# granted when the SERVER stalls and expiring shortly after.
var grace_packets := 0
var grace_windows_left := 0
var logged_rate_limit_this_window := false
var _peer_input_state: Dictionary = {} # peer_id -> _PeerInputState, server only
# Uncapped lifetime reject totals, so the sampled log can be read against the
# true figure — "8 rate-limit rejects recorded" means nothing on its own when
# the recorder itself stops at 8 per window. Deliberately NOT part of
# _PeerInputState, which is erased the moment a peer disconnects: a departed
# peer's reject history is exactly what the post-mortem wants, and the first
# version of this lost it (every summary printed an empty dictionary, because
# the client had always disconnected by the time the server tore the match
# down). peer_id -> {"malformed": int, "rate_limit": int}.
var _reject_totals: Dictionary = {}
var _last_physics_ms := 0
# Bandwidth (task 3.7's debug overlay): only the two 60Hz hot-path channels
# (input, snapshot) — match_config/score_update are low-frequency control
# messages, not what §2's byte-budget analysis or a live overlay cares
# about. Rolling per-second counters, recomputed opportunistically on each
# send/receive rather than on a timer — nothing needs the rate outside of
# an on-demand overlay read anyway. Use get_bytes_sent_per_sec() /
# get_bytes_received_per_sec() to READ these, not the raw fields directly
# — see those functions for why.
const BANDWIDTH_WINDOW_MS := 1000
var bytes_sent_per_sec := 0.0
var bytes_received_per_sec := 0.0
var _sent_window_start_ms := 0
var _sent_window_bytes := 0
var _received_window_start_ms := 0
var _received_window_bytes := 0
# An adversarial review found bytes_*_per_sec only ever gets recomputed
# INSIDE _track_sent()/_track_received() — i.e. only when traffic actually
# arrives — so if traffic stops entirely (right before a disconnect, or
# during exactly the kind of outage this overlay exists to diagnose), the
# last computed rate displays forever instead of decaying toward zero.
# Report zero once meaningfully more than one window has passed with
# nothing tracked, rather than trusting a stale field.
func get_bytes_sent_per_sec() -> float:
if Time.get_ticks_msec() - _sent_window_start_ms > BANDWIDTH_WINDOW_MS * 2:
return 0.0
return bytes_sent_per_sec
func get_bytes_received_per_sec() -> float:
if Time.get_ticks_msec() - _received_window_start_ms > BANDWIDTH_WINDOW_MS * 2:
return 0.0
return bytes_received_per_sec
func _ready() -> void:
NetworkManager.client_disconnected.connect(func(peer_id: int) -> void: _peer_input_state.erase(peer_id))
# Seeded here, not left at 0, so the first physics frame measures a frame
# gap rather than the whole process uptime.
_last_physics_ms = Time.get_ticks_msec()
# Server-side stall watchdog. A SIGSTOPped or hitching process doesn't run this
# either, so the first physics frame after the stall is the one that sees the
# whole wall-clock gap — which is precisely the size of the client backlog
# about to arrive. Grace is handed only to peers ALREADY sending input, so a
# peer that connects during the stall gets none of it.
func _physics_process(_delta: float) -> void:
var now := Time.get_ticks_msec()
var gap := now - _last_physics_ms
_last_physics_ms = now
# NetworkManager.shutdown() swaps in an OfflineMultiplayerPeer before the
# smoke harness's deferred quit runs. Querying MultiplayerAPI.is_server()
# during that hand-off can call get_unique_id() on an inactive ENet peer and
# emit errors every physics frame; the NetworkManager role flag is the safe
# lifecycle guard at this boundary.
if not NetworkManager.is_server or _peer_input_state.is_empty():
return
if gap < STALL_DETECT_MS:
return
var credit: int = mini(int(float(gap) * SimConstants.TICK_HZ / 1000.0), MAX_STALL_GRACE_PACKETS)
for peer_id in _peer_input_state:
var state: _PeerInputState = _peer_input_state[peer_id]
state.grace_packets = mini(state.grace_packets + credit, MAX_STALL_GRACE_PACKETS)
state.grace_windows_left = STALL_GRACE_WINDOWS
push_warning("MatchSim: server stalled %dms — granting %d packets of rate-limit grace to %d peer(s)" % [
gap, credit, _peer_input_state.size()
])
ServerLog.warn("server_stalled", {"gap_ms": gap, "grace_packets": credit, "peers": _peer_input_state.size()})
func _track_sent(n: int) -> void:
var now := Time.get_ticks_msec()
if now - _sent_window_start_ms >= BANDWIDTH_WINDOW_MS:
bytes_sent_per_sec = _sent_window_bytes * 1000.0 / maxf(1.0, float(now - _sent_window_start_ms))
_sent_window_start_ms = now
_sent_window_bytes = 0
_sent_window_bytes += n
func _track_received(n: int) -> void:
var now := Time.get_ticks_msec()
if now - _received_window_start_ms >= BANDWIDTH_WINDOW_MS:
bytes_received_per_sec = _received_window_bytes * 1000.0 / maxf(1.0, float(now - _received_window_start_ms))
_received_window_start_ms = now
_received_window_bytes = 0
_received_window_bytes += n
# Server only: the last match_config actually sent, so a client whose own
# scene load (and therefore its match_config_received listener) finishes
# AFTER the server already broadcast can still get it — a one-shot
# broadcast alone is racy against however long the client takes to reach
# the point where it's listening, and Godot signals never buffer for a
# late connection. request_match_config() closes that race by turning
# delivery into "ask until you get it" instead of "hope you were already
# listening." Also covers a late joiner mid-match (Phase 5 will still need
# to add live match *state*, not just this static config, for that case).
var _last_match_config: Dictionary = {}
func send_match_config(arena_path: String, peer_ids: PackedInt32Array, teams: PackedInt32Array, spawn_indices: PackedInt32Array) -> void:
_last_match_config = {
"arena_path": arena_path, "peer_ids": peer_ids, "teams": teams, "spawn_indices": spawn_indices,
}
_match_config.rpc(arena_path, peer_ids, teams, spawn_indices)
# Also the client's cue to ask for live match state — see
# NetworkedMatch._on_match_config_requested. A late joiner's bootstrap has the
# SAME race match_config has: the server sends it when the peer joins the
# roster, which is before that peer has loaded the match scene and connected
# its listeners, so a one-shot send is simply missed. Delivery has to be
# "ask until you get it" for both.
signal match_config_requested(peer_id: int)
func request_match_config() -> void:
_request_match_config.rpc_id(1)
func send_input(bytes: PackedByteArray) -> void:
_track_sent(bytes.size())
# bytes is already fully packed (any timestamps it carries are already
# fixed), so wrapping the dispatch itself is enough — task 2.8.
NetSim.send(func() -> void: _recv_input.rpc_id(1, bytes), 1)
func send_snapshot(peer_id: int, bytes: PackedByteArray) -> void:
# A server-side disconnect can leave peer_id in get_peers() until the
# current poll batch settles. Do not enter Godot's RPC path for that stale
# target; NetSim repeats this check at fire time for delayed sends.
if not NetworkManager.can_send_to_peer(peer_id):
return
_track_sent(bytes.size())
NetSim.send(func() -> void: _snapshot.rpc_id(peer_id, bytes), peer_id)
func send_score_update(score: Dictionary) -> void:
_score_update.rpc(score)
# §6.1 task 5.1. Reliable channel 0, and it carries the ABSOLUTE tick the
# transition happened on rather than a duration — §6.2's closing note: on a
# lossy link ENet's RTO can stretch a lifecycle burst to ~600ms, and a
# duration would then be applied from whenever it happened to arrive.
# The same state also rides every snapshot's match_state byte, so a client
# that misses this entirely still converges (see NetworkedMatch's own
# _on_snapshot_received) — this RPC exists to make the transition PROMPT and
# to carry `at_tick`, not to be the sole channel.
func send_state_change(state: int, at_tick: int) -> void:
_state_change.rpc(state, at_tick)
# §1's "seeded RNG for kickoff jitter" decision, enforced: the server sends the
# resulting TRANSFORMS, never a seed. Shared-seed determinism would require
# both sides to consume the RNG stream in identical order forever, and the
# first randf() anyone later adds to the reset path silently desyncs kickoff
# positions with no error message. A few hundred bytes once per kickoff cannot
# rot that way.
func send_kickoff(positions: PackedVector3Array, rotations: PackedFloat32Array, countdown_start_tick: int, reset_gen: int) -> void:
_kickoff.rpc(positions, rotations, countdown_start_tick, reset_gen)
func send_goal_scored(scoring_team: int, score: Dictionary, goal_tick: int, resume_tick: int) -> void:
_goal_scored.rpc(scoring_team, score, goal_tick, resume_tick)
# remaining_ticks is authoritative while `running` is false: a stopped clock
# cannot be derived from end_tick minus the current tick, or it drains through
# every goal pause and kickoff countdown.
func send_clock_state(running: bool, end_tick: int, remaining_ticks: int, at_tick: int) -> void:
_clock_state.rpc(running, end_tick, remaining_ticks, at_tick)
# §6.2 step 2 / §6.3: everything a peer needs to reconstruct the CURRENT match
# on arrival, sent to one peer rather than broadcast.
#
# match_config alone is not enough and never was: it carries arena and roster
# only, so a late joiner or a reconnecting player had no score, no clock, and
# no match state until the next goal or transition happened to fire. An
# adversarial review caught that; §6.2 step 2's `welcome` is specified to carry
# exactly this set, so this is that message under a name that does not clash
# with MatchNet's own lobby-level welcome.
func send_match_bootstrap(peer_id: int, state: int, at_tick: int, score: Dictionary, end_tick: int, clock_running: bool, reset_gen: int, remaining_ticks: int) -> void:
_match_bootstrap.rpc_id(peer_id, state, at_tick, score, end_tick, clock_running, reset_gen, remaining_ticks)
# §6.3's late-joiner promotion. BROADCAST, not addressed to the new owner
# alone: every client holds its own copy of the slot list, and a peer_id that
# only the promoted client learns about leaves everyone else's copy naming a
# player who is no longer in that seat. Reliable channel 0 — a client that
# misses this keeps flying somebody else's ship as a remote body forever, and
# unlike match_state there is no per-snapshot field that would re-converge it.
func send_slot_assigned(peer_id: int, slot_index: int) -> void:
_slot_assigned.rpc(peer_id, slot_index)
@rpc("authority", "call_remote", "reliable", 0)
func _match_config(arena_path: String, peer_ids: PackedInt32Array, teams: PackedInt32Array, spawn_indices: PackedInt32Array) -> void:
match_config_received.emit(arena_path, peer_ids, teams, spawn_indices)
@rpc("authority", "call_remote", "reliable", 0)
func _slot_assigned(peer_id: int, slot_index: int) -> void:
slot_assigned_received.emit(peer_id, slot_index)
@rpc("any_peer", "call_remote", "reliable", 0)
func _request_match_config() -> void:
if not multiplayer.is_server() or _last_match_config.is_empty():
return
var peer_id := multiplayer.get_remote_sender_id()
_match_config.rpc_id(
peer_id, _last_match_config["arena_path"], _last_match_config["peer_ids"],
_last_match_config["teams"], _last_match_config["spawn_indices"]
)
match_config_requested.emit(peer_id)
@rpc("any_peer", "call_remote", "unreliable_ordered", 1)
func _recv_input(bytes: PackedByteArray) -> void:
if not multiplayer.is_server():
return
_track_received(bytes.size())
var peer_id := multiplayer.get_remote_sender_id()
var state: _PeerInputState = _peer_input_state.get(peer_id)
if state == null:
state = _PeerInputState.new()
_peer_input_state[peer_id] = state
# Rolling 1s window (§3.1 step 2). Rolled over lazily on the first
# packet past the window boundary, not on a timer — this RPC only ever
# runs when a packet actually arrives, so there's nothing to roll over
# when nothing is arriving anyway.
var now_ms := Time.get_ticks_msec()
if now_ms - state.window_start_ms >= RATE_LIMIT_WINDOW_MS:
# The leaky bucket drains against the SAME budget the window itself was
# policed with, grace included — otherwise a server stall would still
# accumulate excess toward a disconnect for traffic the server just
# explicitly allowed.
state.excess_packets = maxf(0.0, state.excess_packets + float(state.packets_this_window) - float(_packet_budget(state)))
state.excess_bytes = maxf(0.0, state.excess_bytes + float(state.bytes_this_window) - float(_byte_budget(state)))
state.window_start_ms = now_ms
state.packets_this_window = 0
state.bytes_this_window = 0
state.rejects_recorded_this_window = 0
state.logged_rate_limit_this_window = false
if state.grace_windows_left > 0:
state.grace_windows_left -= 1
if state.grace_windows_left == 0:
state.grace_packets = 0
if state.excess_packets > RATE_LIMIT_EXCESS_PACKETS_TO_DISCONNECT or state.excess_bytes > RATE_LIMIT_EXCESS_BYTES_TO_DISCONNECT:
# Record before disconnecting, same reasoning as _count_malformed:
# the log should contain the packet that ended the connection, not
# stop one short of it.
_emit_reject(peer_id, state, InputRejectReason.RATE_LIMIT, bytes)
_disconnect_abusive_peer(peer_id, "input rate limit exceeded (excess_packets=%.0f excess_bytes=%.0f)" % [state.excess_packets, state.excess_bytes])
return
state.packets_this_window += 1
state.bytes_this_window += bytes.size()
if state.packets_this_window > _packet_budget(state) or state.bytes_this_window > _byte_budget(state):
# Over budget for the current window — drop, counted above at the next
# window roll.
if not state.logged_rate_limit_this_window:
# ONCE per window, not per packet: a flood is thousands of packets a
# second and the log line must not become the amplifier the replay
# recorder was capped to avoid being.
state.logged_rate_limit_this_window = true
ServerLog.warn("rate_limited", {
"peer_id": peer_id, "packets": state.packets_this_window,
"budget": _packet_budget(state), "grace": state.grace_packets,
})
_emit_reject(peer_id, state, InputRejectReason.RATE_LIMIT, bytes)
return
# Framing (§3.1 step 3), validated before decoding — unpack_input can't
# be trusted to catch this itself: StreamPeerBuffer silently zero-fills
# past EOF rather than erroring (found during Phase 2's adversarial
# review's hostile-client stress test), so a too-short or size-mismatched
# payload would otherwise decode "successfully" into garbage actions
# instead of being rejected.
if bytes.size() < NetCodec.INPUT_HEADER_SIZE:
_count_malformed(peer_id, state, bytes)
return
var count: int = bytes[5] # type_version(1) + seq(4) precede count — see pack_input's own layout
if count == 0 or count > NetCodec.MAX_REDUNDANCY or bytes.size() != NetCodec.INPUT_HEADER_SIZE + count * NetCodec.INPUT_ENTRY_SIZE:
_count_malformed(peer_id, state, bytes)
return
var decoded := NetCodec.unpack_input(bytes)
# Carry the verbatim wire bytes alongside the decode. Task 5.10's replay
# log stores exactly what arrived rather than a re-serialisation, which is
# the whole reason it can reproduce a reported snap: a re-encode would
# launder away precisely the malformed or edge-case payload being chased.
decoded["raw"] = bytes
input_received.emit(peer_id, decoded)
# The budget a peer is actually policed against right now: the standing limit
# plus any outstanding server-stall grace. Bytes scale with packets by the same
# worst-case-packet factor RATE_LIMIT_BYTES_PER_SEC itself is derived from, so
# the two budgets can never drift apart by hand.
func _packet_budget(state: _PeerInputState) -> int:
return RATE_LIMIT_PACKETS_PER_SEC + state.grace_packets
func _byte_budget(state: _PeerInputState) -> int:
return _packet_budget(state) * (NetCodec.INPUT_HEADER_SIZE + NetCodec.MAX_REDUNDANCY * NetCodec.INPUT_ENTRY_SIZE)
func _count_malformed(peer_id: int, state: _PeerInputState, bytes: PackedByteArray) -> void:
state.malformed_count += 1
# Emitted before the disconnect check so the packet that finally crossed
# the limit is itself in the log, not just the 19 before it.
_emit_reject(peer_id, state, InputRejectReason.MALFORMED, bytes)
if state.malformed_count >= MALFORMED_LIMIT_TO_DISCONNECT:
_disconnect_abusive_peer(peer_id, "too many malformed input packets (%d)" % state.malformed_count)
func _emit_reject(peer_id: int, state: _PeerInputState, reason: int, bytes: PackedByteArray) -> void:
var totals: Dictionary = _reject_totals.get(peer_id, {"malformed": 0, "rate_limit": 0})
var key := "rate_limit" if reason == InputRejectReason.RATE_LIMIT else "malformed"
totals[key] = int(totals[key]) + 1
_reject_totals[peer_id] = totals
if state.rejects_recorded_this_window >= REJECTS_RECORDED_PER_WINDOW:
return
state.rejects_recorded_this_window += 1
input_rejected.emit(peer_id, reason, bytes)
# Server-side, diagnostic. peer_id -> {"malformed": int, "rate_limit": int},
# uncapped and surviving the peer's disconnect. Peers with no rejects at all
# never appear, so an empty dictionary means a clean session.
func get_reject_totals() -> Dictionary:
return _reject_totals.duplicate(true)
func _disconnect_abusive_peer(peer_id: int, reason: String) -> void:
push_warning("MatchSim: disconnecting peer %d for abuse: %s" % [peer_id, reason])
# Task 6.4: the one server event an operator is most likely to be asked
# about ("why was I kicked?"), and it was previously only a push_warning —
# which does not carry the peer, the reason or a timestamp into the log
# stream a container actually captures.
ServerLog.warn("peer_kicked", {"peer_id": peer_id, "reason": reason})
NetworkManager.invalidate_peer(peer_id)
_peer_input_state.erase(peer_id)
if multiplayer.multiplayer_peer is ENetMultiplayerPeer:
multiplayer.multiplayer_peer.disconnect_peer(peer_id)
@rpc("authority", "call_remote", "unreliable_ordered", 2)
func _snapshot(bytes: PackedByteArray) -> void:
_track_received(bytes.size())
var decoded := NetCodec.unpack_snapshot(bytes)
snapshot_received.emit(decoded)
@rpc("authority", "call_remote", "reliable", 0)
func _state_change(state: int, at_tick: int) -> void:
# "authority" already means a forging client is rejected by Godot itself
# (verified for _match_config/_score_update/_snapshot during Phase 2), but
# an authoritative server sending a state this build doesn't know about is
# a real forward-compatibility case — drop it rather than driving the
# client into an undefined state.
if not MatchState.is_valid(state):
push_warning("MatchSim: ignoring unknown match_state %d from server" % state)
return
state_change_received.emit(state, at_tick)
@rpc("authority", "call_remote", "reliable", 0)
func _kickoff(positions: PackedVector3Array, rotations: PackedFloat32Array, countdown_start_tick: int, reset_gen: int) -> void:
# 4 quaternion floats per body. A mismatch means a corrupt or hostile
# payload; dropping it is safe because the snapshot stream still carries
# authoritative poses and the next kickoff will re-sync.
if rotations.size() != positions.size() * 4:
push_warning("MatchSim: kickoff payload mismatch (%d positions, %d rotation floats)" % [positions.size(), rotations.size()])
return
kickoff_received.emit(positions, rotations, countdown_start_tick, reset_gen)
@rpc("authority", "call_remote", "reliable", 0)
func _goal_scored(scoring_team: int, score: Dictionary, goal_tick: int, resume_tick: int) -> void:
goal_scored_received.emit(scoring_team, score, goal_tick, resume_tick)
@rpc("authority", "call_remote", "reliable", 0)
func _clock_state(running: bool, end_tick: int, remaining_ticks: int, at_tick: int) -> void:
clock_state_received.emit(running, end_tick, remaining_ticks, at_tick)
@rpc("authority", "call_remote", "reliable", 0)
func _match_bootstrap(state: int, at_tick: int, score: Dictionary, end_tick: int, clock_running: bool, reset_gen: int, remaining_ticks: int) -> void:
if not MatchState.is_valid(state):
push_warning("MatchSim: ignoring bootstrap with unknown match_state %d" % state)
return
match_bootstrap_received.emit(state, at_tick, score, end_tick, clock_running, reset_gen, remaining_ticks)
@rpc("authority", "call_remote", "reliable", 0)
func _score_update(score: Dictionary) -> void:
score_update_received.emit(score)
+1
View File
@@ -0,0 +1 @@
uid://bk81de78uwut
+88
View File
@@ -0,0 +1,88 @@
class_name MatchState
# Match lifecycle states (MULTIPLAYER_SPEC.md §6.1; multiplayer-next.md task 5.1).
#
# Pure data + a transition table, deliberately with no scene, RPC or
# NetworkedMatch dependency — same reason net_codec.gd and
# input_jitter_buffer.gd are standalone: the table can then be exhaustively
# unit-tested without a live match.
#
# The integer values ARE the wire format. `match_state` has been a u8 in the
# snapshot header since §2.4 (net_codec.gd's pack_snapshot_body_segment), so
# these numbers are protocol, not an implementation detail: never renumber an
# existing state, only append. LOBBY is 0 so a zeroed/placeholder snapshot
# body decodes to a state that is obviously "not in a match" rather than to
# something mid-play.
enum State {
LOBBY = 0,
LOADING = 1,
WARMUP = 2,
PLAYING = 3,
GOAL_PAUSE = 4,
FULL_TIME = 5,
OVERTIME_WARMUP = 6,
OVERTIME = 7,
RESULTS = 8,
}
# Legal successors, straight from §6.1's diagram. Enforced rather than
# documented: an illegal transition is a server logic bug, and the failure it
# otherwise produces (clients following the server into a state its own code
# never expected to broadcast) is exactly the kind that shows up as an
# unreproducible field report three phases later.
#
# LOBBY is reachable from ANY state and is handled separately in
# can_transition() rather than being listed nine times — §6.4's "if the last
# human leaves, abort to LOBBY" can fire at any point, including mid-goal.
const _SUCCESSORS := {
State.LOBBY: [State.LOADING],
State.LOADING: [State.WARMUP],
State.WARMUP: [State.PLAYING],
# A goal, or the clock running out. FULL_TIME is entered on the clock even
# if a goal is in flight — §6.2 step 9's clock is authoritative.
State.PLAYING: [State.GOAL_PAUSE, State.FULL_TIME],
# Back to a kickoff, or straight to results when the goal that caused the
# pause also ended the match (golden goal in overtime, or a goal on the
# final tick).
State.GOAL_PAUSE: [State.WARMUP, State.OVERTIME_WARMUP, State.RESULTS],
State.FULL_TIME: [State.OVERTIME_WARMUP, State.RESULTS],
State.OVERTIME_WARMUP: [State.OVERTIME],
State.OVERTIME: [State.GOAL_PAUSE, State.RESULTS],
State.RESULTS: [State.LOBBY],
}
# States in which the simulation is live and inputs drive ships. Everything
# else freezes bodies (§6.2 steps 6 and 8). Kept as a set here rather than as
# an `if state == PLAYING or state == OVERTIME` scattered through
# NetworkedMatch, so adding a future live state can't miss a site.
const _LIVE := [State.PLAYING, State.OVERTIME]
static func is_valid(state: int) -> bool:
return state in State.values()
static func is_live(state: int) -> bool:
return state in _LIVE
# True when the match is over and the clock should not advance. Distinct from
# `not is_live()`: a WARMUP is not live but the match is very much ongoing.
static func is_terminal(state: int) -> bool:
return state == State.RESULTS or state == State.LOBBY
static func can_transition(from_state: int, to_state: int) -> bool:
if not is_valid(from_state) or not is_valid(to_state):
return false
if to_state == State.LOBBY:
return from_state != State.LOBBY # §6.4 abort, from anywhere
return to_state in _SUCCESSORS.get(from_state, [])
static func to_name(state: int) -> String:
for key in State.keys():
if State[key] == state:
return key
return "UNKNOWN(%d)" % state
+1
View File
@@ -0,0 +1 @@
uid://b1etnxbdelq1p
+388
View File
@@ -0,0 +1,388 @@
extends Control
const CLIENT_BUILD := "dev"
const PROTOCOL_VERSION := 1
const HEARTBEAT_SECONDS := 10.0
const RECOVERY_POLL_SECONDS := 2.0
@onready var playlist_dropdown: OptionButton = %PlaylistDropdown
@onready var status_label: Label = %StatusLabel
@onready var detail_label: Label = %DetailLabel
@onready var ranked_profile_label: Label = %RankedProfileLabel
@onready var queue_button: Button = %QueueButton
@onready var cancel_button: Button = %CancelButton
@onready var accept_button: Button = %AcceptButton
@onready var decline_button: Button = %DeclineButton
@onready var back_button: Button = %BackButton
var _elapsed_seconds := 0.0
var _heartbeat_seconds := 0.0
var _recovery_poll_seconds := 0.0
# Regions still awaiting RTT evidence, and the queue request deferred until at
# least one lands. The matcher ignores a ticket with no predicted RTT, so
# queueing before probing produces a search that can never match.
var _pending_probe_regions: Array[String] = []
var _probed_regions: Array[String] = []
var _deferred_queue := {}
var _web_api_ticket_handle := 0
func _ready() -> void:
AudioManager.bind_tree_buttons(self)
playlist_dropdown.add_item("Casual")
playlist_dropdown.set_item_metadata(0, "casual")
playlist_dropdown.add_item("Ranked")
playlist_dropdown.set_item_metadata(1, "ranked")
playlist_dropdown.item_selected.connect(_on_playlist_selected)
ControlPlaneClient.state.changed.connect(_on_state_changed)
ControlPlaneClient.request_failed.connect(_on_request_failed)
ControlPlaneClient.request_succeeded.connect(_on_request_succeeded)
ControlPlaneClient.session_expired.connect(_on_session_expired)
ControlPlaneClient.probe_challenge_received.connect(_on_probe_challenge_received)
ControlPlaneClient.probe_recorded.connect(_on_probe_recorded)
_ensure_signed_in()
_refresh_ranked_profile()
_render(ControlPlaneClient.state.snapshot())
# Matchmaking previously opened with an empty token against a loopback default,
# so every request failed ERR_UNAUTHORIZED before reaching the network. Point
# the client at its configured endpoint and complete Steam sign-in first.
func _ensure_signed_in() -> void:
if ControlPlaneClient.has_session():
return
if not ControlPlaneClient.configure(ControlPlaneClient.configured_base_url(), ""):
_on_local_error("Matchmaking endpoint is not configured")
return
if not SteamBootstrap.supports_web_api_ticket():
# Deliberately explicit rather than silently presenting a search that
# can never start: online matchmaking requires a verified identity.
_on_local_error("Sign-in requires the Steam build: %s" % SteamBootstrap.unavailable_reason())
return
var steam := Engine.get_singleton("Steam")
if not steam.get_auth_ticket_for_web_api.is_connected(_on_web_api_ticket):
steam.get_auth_ticket_for_web_api.connect(_on_web_api_ticket)
_web_api_ticket_handle = SteamBootstrap.request_web_api_ticket()
if _web_api_ticket_handle <= 0:
_on_local_error("Could not request a Steam authentication ticket")
return
ControlPlaneClient.state.set_notice("Signing in...")
func _on_web_api_ticket(_handle: int, result: int, ticket: PackedByteArray) -> void:
# Steam reports k_EResultOK as 1; anything else means no usable ticket.
if result != 1 or ticket.is_empty():
_on_local_error("Steam declined to issue an authentication ticket")
return
var encoded := SteamBootstrap.encode_web_api_ticket(ticket)
if encoded.is_empty():
_on_local_error("Steam returned an unusable authentication ticket")
return
var err := ControlPlaneClient.login_steam(encoded)
if err != OK:
_on_local_error("Could not sign in: %s" % error_string(err))
func _exit_tree() -> void:
# The ticket handle is a Steam resource; releasing it avoids leaking one
# per visit to this screen.
if _web_api_ticket_handle > 0:
SteamBootstrap.cancel_web_api_ticket(_web_api_ticket_handle)
_web_api_ticket_handle = 0
func _process(delta: float) -> void:
if ControlPlaneClient.state.phase in [MatchmakingState.QUEUED, MatchmakingState.PROPOSED, MatchmakingState.ACCEPTED, MatchmakingState.ALLOCATING]:
_elapsed_seconds += delta
_heartbeat_seconds += delta
_recovery_poll_seconds += delta
if _recovery_poll_seconds >= RECOVERY_POLL_SECONDS:
_recovery_poll_seconds = 0.0
var recovery_err := ControlPlaneClient.recover_proposal(ControlPlaneClient.state.proposal_id) if ControlPlaneClient.state.has_open_proposal() else ControlPlaneClient.recover_queue(ControlPlaneClient.state.ticket_id)
if recovery_err != OK and recovery_err != ERR_BUSY:
_on_local_error("State recovery unavailable: %s" % error_string(recovery_err))
if ControlPlaneClient.state.phase == MatchmakingState.QUEUED and _heartbeat_seconds >= HEARTBEAT_SECONDS:
_heartbeat_seconds = 0.0
var err := ControlPlaneClient.heartbeat(ControlPlaneClient.state.ticket_id, ControlPlaneClient.state.revision)
if err != OK:
_on_local_error("Heartbeat unavailable: %s" % error_string(err))
_render(ControlPlaneClient.state.snapshot())
func _on_queue_pressed() -> void:
if not ControlPlaneClient.has_session():
# Queueing without a session would fail at the first request guard.
_ensure_signed_in()
return
if ControlPlaneClient.can_retry_queue_create():
var retry_err := ControlPlaneClient.retry_queue_create()
if retry_err != OK:
_on_local_error("Could not retry matchmaking: %s" % error_string(retry_err))
return
if ControlPlaneClient.can_retry_last_mutation():
var mutation_err := ControlPlaneClient.retry_last_mutation()
if mutation_err != OK:
_on_local_error("Could not retry matchmaking action: %s" % error_string(mutation_err))
return
if not _can_start_new_search(ControlPlaneClient.state.phase):
return
_elapsed_seconds = 0.0
_heartbeat_seconds = 0.0
_recovery_poll_seconds = 0.0
var playlist := String(playlist_dropdown.get_selected_metadata())
var ticket_id := "ticket-%s-%s" % [str(Time.get_ticks_usec()), str(randi())]
# A ticket with no regional RTT evidence is invisible to the matcher, so
# collect it first and queue once the first region reports.
if _probed_regions.is_empty():
_deferred_queue = {"ticket_id": ticket_id, "playlist": playlist}
_start_probe_collection()
return
var err := ControlPlaneClient.queue_create(ticket_id, playlist, CLIENT_BUILD, PROTOCOL_VERSION)
if err != OK:
_on_local_error("Could not start matchmaking: %s" % error_string(err))
func _start_probe_collection() -> void:
_pending_probe_regions = []
for region in ControlPlaneClient.PROBE_REGIONS:
_pending_probe_regions.append(String(region))
ControlPlaneClient.state.set_notice("Measuring connection quality...")
_request_next_probe()
# One request at a time: the client serialises HTTP through a single
# HTTPRequest, so a second call would return ERR_BUSY.
func _request_next_probe() -> void:
if _pending_probe_regions.is_empty():
_finish_probe_collection()
return
var region := _pending_probe_regions[0]
var err := ControlPlaneClient.request_probe_challenge(region)
if err != OK and err != ERR_BUSY:
# A region we cannot probe is not fatal; placement just uses the
# regions that did respond.
_pending_probe_regions.remove_at(0)
_request_next_probe()
func _on_probe_challenge_received(region: String, nonce_base64: String) -> void:
var err := ControlPlaneClient.submit_probe_answer(region, nonce_base64, ControlPlaneClient.opaque_location_payload())
if err != OK:
_drop_pending_probe(region)
func _on_probe_recorded(region: String, _server_rtt_ms: int) -> void:
if not _probed_regions.has(region):
_probed_regions.append(region)
_drop_pending_probe(region)
func _drop_pending_probe(region: String) -> void:
var index := _pending_probe_regions.find(region)
if index >= 0:
_pending_probe_regions.remove_at(index)
_request_next_probe()
func _finish_probe_collection() -> void:
if _deferred_queue.is_empty():
return
var queued := _deferred_queue
_deferred_queue = {}
if _probed_regions.is_empty():
# Queueing now would create a ticket the matcher can never select.
_on_local_error("Could not measure connection quality to any region; matchmaking is unavailable")
return
var err := ControlPlaneClient.queue_create(String(queued["ticket_id"]), String(queued["playlist"]), CLIENT_BUILD, PROTOCOL_VERSION)
if err != OK:
_on_local_error("Could not start matchmaking: %s" % error_string(err))
func _on_cancel_pressed() -> void:
if not ControlPlaneClient.state.can_cancel():
return
var err := ControlPlaneClient.cancel_queue(ControlPlaneClient.state.ticket_id, ControlPlaneClient.state.revision)
if err != OK:
_on_local_error("Could not cancel matchmaking: %s" % error_string(err))
func _on_accept_pressed() -> void:
var err := ControlPlaneClient.respond_to_proposal(ControlPlaneClient.state.proposal_id, true, ControlPlaneClient.state.proposal_revision)
if err != OK:
_on_local_error("Could not accept proposal: %s" % error_string(err))
func _on_decline_pressed() -> void:
var err := ControlPlaneClient.respond_to_proposal(ControlPlaneClient.state.proposal_id, false, ControlPlaneClient.state.proposal_revision)
if err != OK:
_on_local_error("Could not decline proposal: %s" % error_string(err))
func _on_playlist_selected(_index: int) -> void:
_refresh_ranked_profile()
func _refresh_ranked_profile() -> void:
var ranked := String(playlist_dropdown.get_selected_metadata()) == "ranked"
ranked_profile_label.visible = ranked
if not ranked:
return
var err := ControlPlaneClient.fetch_ranked_profile()
if err != OK and err != ERR_BUSY:
ranked_profile_label.text = "Ranked profile unavailable: %s" % error_string(err)
func _on_back_pressed() -> void:
if ControlPlaneClient.state.can_cancel():
status_label.text = "Cancel the active search before leaving"
return
get_tree().change_scene_to_file(ScenePaths.MAIN_MENU)
func _on_state_changed(snapshot: Dictionary) -> void:
_render(snapshot)
func _on_request_succeeded(_operation: String, _payload: Dictionary) -> void:
ranked_profile_label.text = ControlPlaneClient.ranked_profile.display_text()
_render(ControlPlaneClient.state.snapshot())
func _on_request_failed(_operation: String, _http_code: int, detail: String) -> void:
detail_label.text = detail
ranked_profile_label.text = ControlPlaneClient.ranked_profile.display_text()
_render(ControlPlaneClient.state.snapshot())
func _on_session_expired() -> void:
status_label.text = "Session expired"
detail_label.text = "Sign in again before searching for a match"
queue_button.disabled = true
func _on_local_error(detail: String) -> void:
detail_label.text = detail
static func phase_label(phase: String) -> String:
match phase:
MatchmakingState.IDLE:
return "Ready to search"
MatchmakingState.QUEUED:
return "Searching for players"
MatchmakingState.PROPOSED:
return "Match found — confirm"
MatchmakingState.ACCEPTED:
return "Match accepted — preparing server"
MatchmakingState.ALLOCATING:
return "Preparing match server"
MatchmakingState.PROCESS_READY:
return "Match server started"
MatchmakingState.ASSIGNMENT_READY:
return "Match assigned"
MatchmakingState.CONNECTING:
return "Connecting to match"
MatchmakingState.LIVE:
return "Match in progress"
MatchmakingState.RESULT_PENDING:
return "Recording match result"
MatchmakingState.COMPLETED:
return "Match complete"
MatchmakingState.ASSIGNED:
return "Match assigned"
MatchmakingState.CANCELLED:
return "Search cancelled"
MatchmakingState.EXPIRED:
return "Search expired"
MatchmakingState.FAILED:
return "Matchmaking unavailable"
_:
return "Recovering matchmaking state"
func _render(snapshot: Dictionary) -> void:
var phase := String(snapshot.get("phase", MatchmakingState.IDLE))
status_label.text = phase_label(phase)
if String(snapshot.get("message", "")) != "":
detail_label.text = String(snapshot["message"])
elif phase == MatchmakingState.QUEUED:
var waited := _elapsed_seconds
if int(snapshot.get("enqueued_at_unix", 0)) > 0:
waited = float(ControlPlaneClient.state.waited_seconds(int(Time.get_unix_time_from_system())))
detail_label.text = queue_wait_detail_text(int(waited), int(snapshot.get("revision", 0)))
elif phase == MatchmakingState.PROPOSED:
detail_label.text = proposal_countdown_text(int(snapshot.get("expires_at_unix", 0)), int(Time.get_unix_time_from_system()))
elif phase == MatchmakingState.ACCEPTED:
detail_label.text = phase_detail_label(phase)
elif phase in [MatchmakingState.ALLOCATING, MatchmakingState.PROCESS_READY, MatchmakingState.ASSIGNMENT_READY, MatchmakingState.ASSIGNED]:
detail_label.text = phase_detail_label(phase)
elif phase in [MatchmakingState.CONNECTING, MatchmakingState.LIVE]:
detail_label.text = "%s · %s" % [phase_detail_label(phase), latency_detail_text(NetworkManager.rtt_ms)]
elif phase == MatchmakingState.RESULT_PENDING:
detail_label.text = "The server is confirming the final result"
elif phase == MatchmakingState.COMPLETED:
detail_label.text = "The match result has been recorded"
elif phase == MatchmakingState.IDLE:
detail_label.text = "Choose a playlist to begin"
cancel_button.visible = ControlPlaneClient.state.can_cancel()
accept_button.visible = phase == MatchmakingState.PROPOSED
decline_button.visible = phase == MatchmakingState.PROPOSED
var retry_search := ControlPlaneClient.can_retry_queue_create()
var retry_mutation := ControlPlaneClient.can_retry_last_mutation()
queue_button.disabled = ControlPlaneClient.auth_expired or not (_can_start_new_search(phase) or retry_search or retry_mutation)
queue_button.text = "Retry Search" if retry_search else ("Retry Request" if retry_mutation else "Search")
static func _is_terminal(phase: String) -> bool:
return phase in [MatchmakingState.CANCELLED, MatchmakingState.EXPIRED, MatchmakingState.FAILED, MatchmakingState.LIVE, MatchmakingState.COMPLETED]
static func phase_detail_label(phase: String) -> String:
match phase:
MatchmakingState.ACCEPTED:
return "All players accepted; preparing the match server"
MatchmakingState.ALLOCATING:
return "Finding a dedicated match server"
MatchmakingState.PROCESS_READY:
return "Match server started; preparing player assignments"
MatchmakingState.ASSIGNMENT_READY:
return "Player assignments are ready"
MatchmakingState.ASSIGNED:
return "Your match server is ready"
MatchmakingState.CONNECTING:
return "Connecting to the match server"
MatchmakingState.LIVE:
return "Match in progress"
_:
return ""
static func proposal_countdown_text(expires_at_unix: int, now_unix: int) -> String:
if expires_at_unix <= 0:
return "Review the proposal before the countdown expires"
return "Review proposal · %ds remaining" % maxi(0, expires_at_unix - now_unix)
static func queue_wait_detail_text(waited_seconds: int, revision: int) -> String:
var waited := maxi(0, waited_seconds)
var suffix := "looking for compatible players"
if waited >= 30:
suffix = "widening skill range while keeping latency limits"
elif waited >= 10:
suffix = "matching nearby skill and latency"
return "Waiting %ds · %s · revision %d" % [waited, suffix, maxi(0, revision)]
static func latency_detail_text(rtt_ms: float) -> String:
if not is_finite(rtt_ms) or rtt_ms < 0.0:
return "Latency: measuring"
var rounded := int(round(rtt_ms))
if rtt_ms <= 50.0:
return "Latency: %dms · excellent" % rounded
if rtt_ms <= 100.0:
return "Latency: %dms · good" % rounded
return "Latency: %dms · high" % rounded
static func _can_start_new_search(phase: String) -> bool:
return phase == MatchmakingState.IDLE or phase in [MatchmakingState.CANCELLED, MatchmakingState.EXPIRED, MatchmakingState.FAILED, MatchmakingState.COMPLETED]
+392
View File
@@ -0,0 +1,392 @@
class_name MatchmakingState
extends RefCounted
# Client-side projection of the authenticated control-plane lifecycle. The
# server remains authoritative; this object only decides what the UI may show
# and refuses stale, gapped, or conflicting revisions instead of guessing.
signal changed(snapshot: Dictionary)
signal resync_required(resource_id: String)
const IDLE := "IDLE"
const QUEUED := "QUEUED"
const PROPOSED := "PROPOSED"
const ACCEPTED := "ACCEPTED"
const ALLOCATING := "ALLOCATING"
const PROCESS_READY := "PROCESS_READY"
const ASSIGNMENT_READY := "ASSIGNMENT_READY"
const CONNECTING := "CONNECTING"
const LIVE := "LIVE"
const ASSIGNED := "ASSIGNED"
const RESULT_PENDING := "RESULT_PENDING"
const COMPLETED := "COMPLETED"
const CANCELLED := "CANCELLED"
const EXPIRED := "EXPIRED"
const FAILED := "FAILED"
var phase := IDLE
var ticket_id := ""
var playlist := ""
var revision := 0
var enqueued_at_unix := 0
var expires_at_unix := 0
var proposal_id := ""
var proposal_revision := 0
var proposal_state := ""
var message := ""
var needs_resync := false
func begin_queue(new_ticket_id: String, new_playlist: String) -> bool:
if new_ticket_id.is_empty() or (new_playlist != "casual" and new_playlist != "ranked"):
return false
_reset()
ticket_id = new_ticket_id
playlist = new_playlist
phase = QUEUED
_emit_changed()
return true
func apply_ticket_update(update: Dictionary, authoritative_snapshot: bool = false) -> bool:
if not _has_string(update, "ticket_id") or not update.has("revision") or not _valid_revision(update["revision"]) or not update.has("state"):
return _request_resync(self.ticket_id)
if update.has("playlist") and not _valid_playlist(String(update["playlist"])):
return _request_resync(self.ticket_id)
if update.has("enqueued_at_unix") and not _valid_epoch(update["enqueued_at_unix"]):
return _request_resync(self.ticket_id)
if update.has("expires_at_unix") and not _valid_epoch(update["expires_at_unix"]):
return _request_resync(self.ticket_id)
if ticket_id.is_empty() or String(update["ticket_id"]) != ticket_id:
return _request_resync(self.ticket_id)
var incoming_revision := int(update["revision"])
if incoming_revision < revision:
return false
if incoming_revision == revision:
if _ticket_differs(update):
return _request_resync(self.ticket_id)
# expires_at_unix is deliberately not part of _ticket_differs' conflict
# check (see its own comment) but is still adopted here: begin_queue()
# has no way to know the server-assigned expiry in advance, so the
# very first same-revision confirmation is the only place a freshly
# queued ticket's expiry is ever set at all.
if update.has("expires_at_unix"):
expires_at_unix = int(update["expires_at_unix"])
if update.has("enqueued_at_unix"):
enqueued_at_unix = maxi(0, int(update["enqueued_at_unix"]))
return true
if incoming_revision > revision + 1 and not authoritative_snapshot:
return _request_resync(self.ticket_id)
var incoming_state := String(update["state"])
if not _is_ticket_state(incoming_state):
return _request_resync(self.ticket_id)
if authoritative_snapshot:
if not _can_reach_ticket_state(phase, incoming_state):
return _request_resync(self.ticket_id)
elif not _is_legal_ticket_transition(phase, incoming_state):
return _request_resync(self.ticket_id)
revision = incoming_revision
phase = incoming_state
if update.has("playlist"):
playlist = String(update["playlist"])
if update.has("expires_at_unix"):
expires_at_unix = int(update["expires_at_unix"])
if update.has("enqueued_at_unix"):
enqueued_at_unix = maxi(0, int(update["enqueued_at_unix"]))
if update.has("message"):
message = String(update["message"])
else:
message = ""
needs_resync = false
_emit_changed()
return true
func apply_proposal_update(update: Dictionary) -> bool:
if not _has_string(update, "proposal_id") or not update.has("revision") or not _valid_revision(update["revision"]) or not update.has("state"):
return _request_resync(proposal_id)
if update.has("expires_at_unix") and not _valid_epoch(update["expires_at_unix"]):
return _request_resync(proposal_id)
var incoming_id := String(update["proposal_id"])
if proposal_id.is_empty():
proposal_id = incoming_id
elif proposal_id != incoming_id:
return _request_resync(proposal_id)
var incoming_revision := int(update["revision"])
if incoming_revision < proposal_revision:
return false
if incoming_revision == proposal_revision and not proposal_state.is_empty():
if String(update["state"]) != proposal_state:
return _request_resync(proposal_id)
return true
if not proposal_state.is_empty() and incoming_revision > proposal_revision + 1:
return _request_resync(proposal_id)
var incoming_proposal_state := String(update["state"])
if incoming_proposal_state == "OPEN":
if not _is_legal_proposal_transition(proposal_state, incoming_proposal_state):
return _request_resync(proposal_id)
phase = PROPOSED
elif incoming_proposal_state == "ACCEPTED":
if not _is_legal_proposal_transition(proposal_state, incoming_proposal_state):
return _request_resync(proposal_id)
phase = ALLOCATING
elif incoming_proposal_state == "DECLINED":
if not _is_legal_proposal_transition(proposal_state, incoming_proposal_state):
return _request_resync(proposal_id)
if phase == PROPOSED:
phase = QUEUED
message = "A player declined the match proposal"
elif incoming_proposal_state == "EXPIRED":
if not _is_legal_proposal_transition(proposal_state, incoming_proposal_state):
return _request_resync(proposal_id)
if phase == PROPOSED:
phase = QUEUED
message = "The match proposal expired"
elif incoming_proposal_state == "CANCELLED":
if not _is_legal_proposal_transition(proposal_state, incoming_proposal_state):
return _request_resync(proposal_id)
if phase == PROPOSED:
phase = QUEUED
message = "The match proposal was cancelled"
else:
return _request_resync(proposal_id)
proposal_revision = incoming_revision
proposal_state = incoming_proposal_state
needs_resync = false
if incoming_proposal_state == "OPEN" or incoming_proposal_state == "ACCEPTED":
message = ""
if update.has("expires_at_unix"):
expires_at_unix = int(update["expires_at_unix"])
_emit_changed()
return true
func prepare_proposal_recovery(new_proposal_id: String) -> bool:
if not _valid_opaque_id(new_proposal_id):
return false
if proposal_id == new_proposal_id:
return true
if proposal_state not in ["", "DECLINED", "EXPIRED", "CANCELLED"]:
return false
proposal_id = new_proposal_id
proposal_revision = 0
proposal_state = ""
return true
func mark_assignment_ready() -> void:
phase = ASSIGNMENT_READY
message = "Match server is ready"
_emit_changed()
func mark_connecting() -> void:
phase = CONNECTING
message = "Connecting to match server"
_emit_changed()
func mark_live() -> void:
phase = LIVE
message = "Match in progress"
_emit_changed()
func fail(reason: String) -> void:
phase = FAILED
message = reason if not reason.is_empty() else "Matchmaking failed"
_emit_changed()
func expire(reason: String = "Matchmaking expired") -> void:
phase = EXPIRED
message = reason
_emit_changed()
func set_notice(notice: String) -> void:
message = notice
_emit_changed()
func restore_snapshot(saved: Dictionary) -> bool:
_reset()
if saved.is_empty():
return true
if saved.has("phase") and not saved["phase"] is String:
return false
if saved.has("ticket_id") and not saved["ticket_id"] is String:
return false
if saved.has("playlist") and not saved["playlist"] is String:
return false
if saved.has("proposal_id") and not saved["proposal_id"] is String:
return false
if saved.has("proposal_state") and not saved["proposal_state"] is String:
return false
if saved.has("message") and not saved["message"] is String:
return false
if saved.has("revision") and not _valid_revision(saved["revision"]):
return false
for epoch_key in ["enqueued_at_unix", "expires_at_unix"]:
if saved.has(epoch_key) and not _valid_epoch(saved[epoch_key]):
return false
if saved.has("proposal_revision") and not _valid_revision(saved["proposal_revision"]):
return false
var saved_phase := String(saved.get("phase", IDLE))
var saved_ticket_id := String(saved.get("ticket_id", ""))
if not _valid_opaque_id(saved_ticket_id) or not _is_ticket_state(saved_phase):
return false
var saved_playlist := String(saved.get("playlist", ""))
if saved_playlist != "casual" and saved_playlist != "ranked":
return false
var saved_proposal_id := String(saved.get("proposal_id", ""))
var saved_proposal_state := String(saved.get("proposal_state", ""))
if saved_proposal_state not in ["", "OPEN", "ACCEPTED", "DECLINED", "EXPIRED", "CANCELLED"] or (not saved_proposal_state.is_empty() and not _valid_opaque_id(saved_proposal_id)) or (saved_proposal_state.is_empty() and not saved_proposal_id.is_empty() and not _valid_opaque_id(saved_proposal_id)):
return false
ticket_id = saved_ticket_id
playlist = saved_playlist
phase = saved_phase
revision = maxi(0, int(saved.get("revision", 0)))
enqueued_at_unix = maxi(0, int(saved.get("enqueued_at_unix", 0)))
expires_at_unix = maxi(0, int(saved.get("expires_at_unix", 0)))
proposal_id = saved_proposal_id
proposal_revision = maxi(0, int(saved.get("proposal_revision", 0)))
proposal_state = saved_proposal_state
message = "Recovering authoritative matchmaking state"
needs_resync = phase != CANCELLED and phase != EXPIRED and phase != FAILED and phase != COMPLETED
_emit_changed()
return true
func can_cancel() -> bool:
return phase == QUEUED or phase == PROPOSED or phase == ALLOCATING
func has_open_proposal() -> bool:
return not proposal_id.is_empty() and proposal_state == "OPEN"
func waited_seconds(now_unix: int) -> int:
if enqueued_at_unix <= 0:
return 0
return maxi(0, now_unix - enqueued_at_unix)
func snapshot() -> Dictionary:
return {"phase": phase, "ticket_id": ticket_id, "playlist": playlist, "revision": revision, "enqueued_at_unix": enqueued_at_unix, "expires_at_unix": expires_at_unix, "proposal_id": proposal_id, "proposal_revision": proposal_revision, "proposal_state": proposal_state, "message": message, "needs_resync": needs_resync}
func _ticket_differs(update: Dictionary) -> bool:
# expires_at_unix is excluded on purpose: begin_queue()'s optimistic local
# state has no way to know the server-assigned expiry before the first
# real response arrives, so comparing it here made the very first
# same-revision confirmation after every begin_queue() look like a
# conflict, unconditionally -- found by an actual client hitting a real
# server: apply_ticket_update() kept requesting a resync, whose own
# response hit exactly the same false mismatch, forever, which
# control_plane_smoke.gd (a live end-to-end test, not a mock) surfaced as
# a request that legitimately never terminates. It's still kept current
# via the direct assignment below, just not treated as a conflict signal.
return String(update["state"]) != phase or (update.has("playlist") and String(update["playlist"]) != playlist)
func _request_resync(resource_id: String) -> bool:
needs_resync = true
resync_required.emit(resource_id)
return false
func _emit_changed() -> void:
changed.emit(snapshot())
func _reset() -> void:
phase = IDLE
playlist = ""
revision = 0
enqueued_at_unix = 0
expires_at_unix = 0
proposal_id = ""
proposal_revision = 0
proposal_state = ""
message = ""
needs_resync = false
func _is_ticket_state(value: String) -> bool:
return value in [QUEUED, PROPOSED, ACCEPTED, ALLOCATING, PROCESS_READY, ASSIGNMENT_READY, ASSIGNED, CONNECTING, LIVE, RESULT_PENDING, COMPLETED, CANCELLED, EXPIRED, FAILED]
func _is_legal_ticket_transition(from: String, to: String) -> bool:
if from == to:
return true
var transitions := {
QUEUED: [PROPOSED, CANCELLED, EXPIRED],
PROPOSED: [QUEUED, ACCEPTED, CANCELLED, EXPIRED],
ACCEPTED: [QUEUED, ALLOCATING, CANCELLED, FAILED],
ALLOCATING: [PROCESS_READY, FAILED, CANCELLED],
PROCESS_READY: [ASSIGNMENT_READY, FAILED, CANCELLED],
ASSIGNMENT_READY: [ASSIGNED, FAILED, CANCELLED],
ASSIGNED: [CONNECTING, FAILED, CANCELLED],
CONNECTING: [LIVE, FAILED, EXPIRED],
LIVE: [RESULT_PENDING, FAILED],
RESULT_PENDING: [COMPLETED, FAILED],
}
return transitions.has(from) and to in transitions[from]
func _can_reach_ticket_state(from: String, to: String) -> bool:
if from == to:
return true
var pending: Array[String] = [from]
var visited := {}
visited[from] = true
while not pending.is_empty():
var current: String = pending.pop_front()
for candidate in [QUEUED, PROPOSED, ACCEPTED, ALLOCATING, PROCESS_READY, ASSIGNMENT_READY, ASSIGNED, CONNECTING, LIVE, RESULT_PENDING, COMPLETED, CANCELLED, EXPIRED, FAILED]:
if visited.has(candidate) or not _is_legal_ticket_transition(current, candidate):
continue
if candidate == to:
return true
visited[candidate] = true
pending.append(candidate)
return false
func _is_legal_proposal_transition(from: String, to: String) -> bool:
if from.is_empty():
return to == "OPEN"
if from == to:
return true
return from == "OPEN" and to in ["ACCEPTED", "DECLINED", "EXPIRED", "CANCELLED"]
func _has_string(value: Dictionary, key: String) -> bool:
return value.has(key) and value[key] is String and not String(value[key]).is_empty()
func _valid_revision(value: Variant) -> bool:
if value is int:
return int(value) >= 0
if value is float:
return is_finite(float(value)) and float(value) >= 0.0 and float(value) == floor(float(value))
return false
func _valid_playlist(value: String) -> bool:
return value == "casual" or value == "ranked"
func _valid_epoch(value: Variant) -> bool:
if value is int:
return int(value) >= 0
if value is float:
return is_finite(float(value)) and float(value) >= 0.0 and float(value) == floor(float(value))
return false
func _valid_opaque_id(value: String) -> bool:
if value.length() < 16 or value.length() > 128:
return false
var resource_pattern := RegEx.create_from_string("^[A-Za-z0-9_-]+$")
return resource_pattern.search(value) != null
+47
View File
@@ -0,0 +1,47 @@
extends RefCounted
# Plain data holder for one body's snapshot state (§2.4 of MULTIPLAYER_SPEC.md).
# Deliberately not Ship/Ball themselves, and deliberately not a scene-tree
# node — NetCodec's pack/unpack must stay callable from pure-function tests
# with no live scene. Phase 2's snapshot writer fills one of these per body
# per tick from the real RigidBody3D state; Phase 2's interpolator does the
# reverse.
#
# avel_range must match what the sender quantised with (SHIP_AVEL_RANGE vs
# BALL_AVEL_RANGE in net_codec.gd) — it is not carried on the wire, because
# slot order already tells both peers which body is which (§1.3: "entities
# are addressed by integer slot, never by path").
var position := Vector3.ZERO
var rotation := Quaternion.IDENTITY
var linear_velocity := Vector3.ZERO
var angular_velocity := Vector3.ZERO
var frozen := false
var turbo := false
var thrust_z := 0.0 # -1..1; re-quantised to a 3-bit bin on the wire
var stalled := false
var avel_range := 4.0 # NetCodec.SHIP_AVEL_RANGE; set to BALL_AVEL_RANGE for the ball
# Self-referential preload, not get_script().new() — this file deliberately
# has no class_name (same cache-timing reason as test_case.gd and other
# path-`extends`d files in this project), and get_script().new() throws
# "Nonexistent function 'new' in base 'GDScript'" from within the script's
# own body in this Godot version.
const _NetBodyState = preload("res://scripts/net_body_state.gd")
# Same contract as ShipAction.copy() (see its own comment): a distinct
# instance with equal fields, for callers that hold onto a state past the
# tick/comparison it was returned in.
func copy() -> RefCounted:
var c := _NetBodyState.new()
c.position = position
c.rotation = rotation
c.linear_velocity = linear_velocity
c.angular_velocity = angular_velocity
c.frozen = frozen
c.turbo = turbo
c.thrust_z = thrust_z
c.stalled = stalled
c.avel_range = avel_range
return c
+1
View File
@@ -0,0 +1 @@
uid://bc1r0cqvtbqec
+295
View File
@@ -0,0 +1,295 @@
class_name NetCodec
# Wire-format constants, quantisers, and pack/unpack for the two hot-path
# packets (§2 of MULTIPLAYER_SPEC.md). Pure functions only — no networking,
# no autoload state — so they're testable head-on by tests/test_runner.tscn
# without a live connection.
#
# Referenced from elsewhere via preload(), not the bare class_name, per the
# same global-script-class-cache caveat documented in tests/test_case.gd and
# sim_constants.gd.
const SimConstants = preload("res://scripts/sim_constants.gd")
const ShipAction = preload("res://scripts/ship_action.gd")
const NetBodyState = preload("res://scripts/net_body_state.gd")
# --- Protocol ---
const PROTOCOL_VERSION := 1
const TICK_HZ: int = SimConstants.TICK_HZ
# --- Channels (logical intent; NetworkManager may need to offset these on
# top of ENet's own reserved channels — verify empirically, see §2.1) ---
const CHANNEL_CONTROL := 0
const CHANNEL_INPUT := 1
const CHANNEL_SNAPSHOT := 2
# --- Packet type/version byte: high nibble = type, low nibble = protocol version ---
enum PacketType { INPUT = 0, SNAPSHOT = 1 }
# --- Input packet (§2.3) ---
const MAX_REDUNDANCY := 4
# type_version u8 + seq u32 + count u8 + ack_snapshot_tick u32 + client_send_ms u16
const INPUT_HEADER_SIZE := 12
const INPUT_ENTRY_SIZE := 7 # thrust i8x3 + rotation i8x3 + flags u8
const INPUT_FLAG_TURBO := 1 << 0
# --- Snapshot packet (§2.4) ---
# last_input_seq u32 + input_buffer_depth i8 + echo_client_send_ms u16
const SNAPSHOT_CLIENT_HEADER_SIZE := 7
# type_version u8 + server_tick u32 + match_state u8 + reset_gen u8 + body_count u8
const SNAPSHOT_BODY_HEADER_SIZE := 8
const SNAPSHOT_BODY_SIZE := 22
const BODY_FLAG_FROZEN := 1 << 0
const BODY_FLAG_TURBO := 1 << 1
const BODY_FLAG_THRUST_Z_SHIFT := 2
const BODY_FLAG_THRUST_Z_MASK := 0x1C # bits 2-4
const BODY_FLAG_STALLED := 1 << 5
const BODY_FLAG_QUAT_W_SIGN := 1 << 6
# --- Quantisation ranges (§2.4 — derived from arena/gameplay constants, not
# restated prose; see MULTIPLAYER_SPEC.md for the ArenaBoundary/Ship/Ball
# constants these are sized against) ---
const POS_RANGE := 64.0 # metres, ±
const VEL_RANGE := 64.0 # m/s, ±
const QUAT_COMPONENT_RANGE := 1.0
const SHIP_AVEL_RANGE := 4.0 # rad/s, ±
const BALL_AVEL_RANGE := 32.0 # rad/s, ±
const I16_MAX := 32767
const I8_MAX := 127
const THRUST_Z_BIN_MAX := 7 # 3 bits
# ============================================================
# Quantisers — pure, reusable, independently testable.
# ============================================================
static func quantize_i16(value: float, range_max: float) -> int:
var scaled := clampf(value / range_max, -1.0, 1.0) * I16_MAX
return clampi(roundi(scaled), -I16_MAX, I16_MAX)
static func dequantize_i16(raw: int, range_max: float) -> float:
return (float(raw) / I16_MAX) * range_max
static func quantize_i8(value: float, range_max: float) -> int:
var scaled := clampf(value / range_max, -1.0, 1.0) * I8_MAX
return clampi(roundi(scaled), -I8_MAX, I8_MAX)
static func dequantize_i8(raw: int, range_max: float) -> float:
return (float(raw) / I8_MAX) * range_max
static func quantize_thrust_z_bin(thrust_z: float) -> int:
var t := clampf((thrust_z + 1.0) * 0.5, 0.0, 1.0)
return clampi(roundi(t * THRUST_Z_BIN_MAX), 0, THRUST_Z_BIN_MAX)
static func dequantize_thrust_z_bin(bin_value: int) -> float:
return (float(bin_value) / THRUST_Z_BIN_MAX) * 2.0 - 1.0
static func type_version_byte(type: PacketType) -> int:
return ((int(type) & 0x0F) << 4) | (PROTOCOL_VERSION & 0x0F)
static func packet_type_of(type_version: int) -> int:
return (type_version >> 4) & 0x0F
static func protocol_version_of(type_version: int) -> int:
return type_version & 0x0F
# ============================================================
# Input packet — client -> server, channel 1 (§2.3)
# ============================================================
# actions: newest-first, 1..MAX_REDUNDANCY ShipAction instances.
static func pack_input(seq: int, ack_snapshot_tick: int, client_send_ms: int, actions: Array) -> PackedByteArray:
var count: int = clampi(actions.size(), 1, MAX_REDUNDANCY)
var buf := StreamPeerBuffer.new()
buf.put_u8(type_version_byte(PacketType.INPUT))
buf.put_u32(seq)
buf.put_u8(count)
buf.put_u32(ack_snapshot_tick)
buf.put_u16(client_send_ms & 0xFFFF)
for i in count:
var action: ShipAction = actions[i]
buf.put_8(quantize_i8(action.thrust.x, 1.0))
buf.put_8(quantize_i8(action.thrust.y, 1.0))
buf.put_8(quantize_i8(action.thrust.z, 1.0))
buf.put_8(quantize_i8(action.rotation.x, 1.0))
buf.put_8(quantize_i8(action.rotation.y, 1.0))
buf.put_8(quantize_i8(action.rotation.z, 1.0))
var flags := 0
if action.turbo:
flags |= INPUT_FLAG_TURBO
buf.put_u8(flags)
return buf.data_array
# Returns a Dictionary: type_version, seq, count, ack_snapshot_tick,
# client_send_ms, actions (Array[ShipAction], newest first).
static func unpack_input(bytes: PackedByteArray) -> Dictionary:
var buf := StreamPeerBuffer.new()
buf.data_array = bytes
var type_version := buf.get_u8()
var seq := buf.get_u32()
var count := buf.get_u8()
var ack_snapshot_tick := buf.get_u32()
var client_send_ms := buf.get_u16()
var actions: Array[ShipAction] = []
for i in count:
var a := ShipAction.new()
a.thrust = Vector3(
dequantize_i8(buf.get_8(), 1.0),
dequantize_i8(buf.get_8(), 1.0),
dequantize_i8(buf.get_8(), 1.0)
)
a.rotation = Vector3(
dequantize_i8(buf.get_8(), 1.0),
dequantize_i8(buf.get_8(), 1.0),
dequantize_i8(buf.get_8(), 1.0)
)
var flags := buf.get_u8()
a.turbo = (flags & INPUT_FLAG_TURBO) != 0
actions.append(a)
return {
"type_version": type_version,
"seq": seq,
"count": count,
"ack_snapshot_tick": ack_snapshot_tick,
"client_send_ms": client_send_ms,
"actions": actions,
}
# ============================================================
# Snapshot packet — server -> client, channel 2 (§2.4)
# ============================================================
# Shared across every peer this tick — build once, reuse (§2.4's stated
# intent). Returns type_version + server_tick + match_state + reset_gen +
# body_count + body_count * SNAPSHOT_BODY_SIZE bytes.
static func pack_snapshot_body_segment(server_tick: int, match_state: int, reset_gen: int, bodies: Array) -> PackedByteArray:
var buf := StreamPeerBuffer.new()
buf.put_u8(type_version_byte(PacketType.SNAPSHOT))
buf.put_u32(server_tick)
buf.put_u8(match_state & 0xFF)
buf.put_u8(reset_gen & 0xFF)
buf.put_u8(bodies.size())
for body in bodies:
var b: NetBodyState = body
buf.put_16(quantize_i16(b.position.x, POS_RANGE))
buf.put_16(quantize_i16(b.position.y, POS_RANGE))
buf.put_16(quantize_i16(b.position.z, POS_RANGE))
buf.put_16(quantize_i16(b.rotation.x, QUAT_COMPONENT_RANGE))
buf.put_16(quantize_i16(b.rotation.y, QUAT_COMPONENT_RANGE))
buf.put_16(quantize_i16(b.rotation.z, QUAT_COMPONENT_RANGE))
buf.put_16(quantize_i16(b.linear_velocity.x, VEL_RANGE))
buf.put_16(quantize_i16(b.linear_velocity.y, VEL_RANGE))
buf.put_16(quantize_i16(b.linear_velocity.z, VEL_RANGE))
buf.put_8(quantize_i8(b.angular_velocity.x, b.avel_range))
buf.put_8(quantize_i8(b.angular_velocity.y, b.avel_range))
buf.put_8(quantize_i8(b.angular_velocity.z, b.avel_range))
var flags := 0
if b.frozen:
flags |= BODY_FLAG_FROZEN
if b.turbo:
flags |= BODY_FLAG_TURBO
flags |= (quantize_thrust_z_bin(b.thrust_z) << BODY_FLAG_THRUST_Z_SHIFT) & BODY_FLAG_THRUST_Z_MASK
if b.stalled:
flags |= BODY_FLAG_STALLED
if b.rotation.w < 0.0:
flags |= BODY_FLAG_QUAT_W_SIGN
buf.put_u8(flags)
return buf.data_array
static func pack_snapshot_client_header(last_input_seq: int, input_buffer_depth: int, echo_client_send_ms: int) -> PackedByteArray:
var buf := StreamPeerBuffer.new()
buf.put_u32(last_input_seq)
buf.put_8(clampi(input_buffer_depth, -128, 127))
buf.put_u16(echo_client_send_ms & 0xFFFF)
return buf.data_array
# Convenience: one full per-client packet = per-client header + shared body segment.
static func pack_snapshot(last_input_seq: int, input_buffer_depth: int, echo_client_send_ms: int, body_segment: PackedByteArray) -> PackedByteArray:
var header := pack_snapshot_client_header(last_input_seq, input_buffer_depth, echo_client_send_ms)
var out := PackedByteArray()
out.append_array(header)
out.append_array(body_segment)
return out
# Returns a Dictionary: last_input_seq, input_buffer_depth, echo_client_send_ms,
# type_version, server_tick, match_state, reset_gen, bodies (Array[NetBodyState]).
static func unpack_snapshot(bytes: PackedByteArray) -> Dictionary:
var buf := StreamPeerBuffer.new()
buf.data_array = bytes
var last_input_seq := buf.get_u32()
var input_buffer_depth := buf.get_8()
var echo_client_send_ms := buf.get_u16()
var type_version := buf.get_u8()
var server_tick := buf.get_u32()
var match_state := buf.get_u8()
var reset_gen := buf.get_u8()
var body_count := buf.get_u8()
var bodies: Array[NetBodyState] = []
for i in body_count:
var b := NetBodyState.new()
b.position = Vector3(
dequantize_i16(buf.get_16(), POS_RANGE),
dequantize_i16(buf.get_16(), POS_RANGE),
dequantize_i16(buf.get_16(), POS_RANGE)
)
var qx := dequantize_i16(buf.get_16(), QUAT_COMPONENT_RANGE)
var qy := dequantize_i16(buf.get_16(), QUAT_COMPONENT_RANGE)
var qz := dequantize_i16(buf.get_16(), QUAT_COMPONENT_RANGE)
b.linear_velocity = Vector3(
dequantize_i16(buf.get_16(), VEL_RANGE),
dequantize_i16(buf.get_16(), VEL_RANGE),
dequantize_i16(buf.get_16(), VEL_RANGE)
)
# avel_range is unknown to the codec at this point (it isn't on the
# wire — see net_body_state.gd) — decode at SHIP_AVEL_RANGE and let
# the caller, which knows this slot's body kind, rescale if it's the
# ball's slot. Storing the raw i8 would avoid this, but every other
# field in this struct is already physical units; consistency wins.
b.angular_velocity = Vector3(
dequantize_i8(buf.get_8(), SHIP_AVEL_RANGE),
dequantize_i8(buf.get_8(), SHIP_AVEL_RANGE),
dequantize_i8(buf.get_8(), SHIP_AVEL_RANGE)
)
var flags := buf.get_u8()
b.frozen = (flags & BODY_FLAG_FROZEN) != 0
b.turbo = (flags & BODY_FLAG_TURBO) != 0
var bin_value := (flags & BODY_FLAG_THRUST_Z_MASK) >> BODY_FLAG_THRUST_Z_SHIFT
b.thrust_z = dequantize_thrust_z_bin(bin_value)
b.stalled = (flags & BODY_FLAG_STALLED) != 0
var w_sq := 1.0 - qx * qx - qy * qy - qz * qz
var w := sqrt(maxf(w_sq, 0.0))
if (flags & BODY_FLAG_QUAT_W_SIGN) != 0:
w = -w
b.rotation = Quaternion(qx, qy, qz, w)
bodies.append(b)
return {
"last_input_seq": last_input_seq,
"input_buffer_depth": input_buffer_depth,
"echo_client_send_ms": echo_client_send_ms,
"type_version": type_version,
"server_tick": server_tick,
"match_state": match_state,
"reset_gen": reset_gen,
"bodies": bodies,
}
# Rescales an already-decoded body's angular_velocity from the SHIP_AVEL_RANGE
# assumption unpack_snapshot() decoded it with to the range it was actually
# quantised at (BALL_AVEL_RANGE for the ball). Call once per non-ship body
# immediately after unpack_snapshot(), using slot order to know which.
static func rescale_avel(body: NetBodyState, actual_range: float) -> void:
if is_equal_approx(actual_range, SHIP_AVEL_RANGE):
body.avel_range = actual_range
return
body.angular_velocity = (body.angular_velocity / SHIP_AVEL_RANGE) * actual_range
body.avel_range = actual_range
+1
View File
@@ -0,0 +1 @@
uid://bbb72h1ue0hdp
+87
View File
@@ -0,0 +1,87 @@
extends CanvasLayer
# Autoload: toggleable network debug overlay (F4 by default — see
# toggle_net_overlay in project.godot's [input]). Read-only against
# NetworkManager's clock state (task 1.8). Mirrors perf_overlay.gd's pattern
# — headless-guarded, hidden by default, no gameplay-state writes.
var _label: Label
func _ready() -> void:
if DisplayServer.get_name() == "headless":
set_process(false)
return
layer = 100
_label = Label.new()
_label.add_theme_font_size_override("font_size", 14)
_label.add_theme_color_override("font_color", Color(0.5, 0.8, 1.0))
_label.add_theme_color_override("font_shadow_color", Color(0, 0, 0, 0.85))
_label.add_theme_constant_override("shadow_offset_x", 1)
_label.add_theme_constant_override("shadow_offset_y", 1)
_label.position = Vector2(12, 90)
_label.visible = false
add_child(_label)
func _unhandled_input(event: InputEvent) -> void:
if event.is_action_pressed("toggle_net_overlay") and _label:
_label.visible = not _label.visible
return
if not _label or not _label.visible or not (event is InputEventKey) or not event.pressed or event.echo:
return
var game := get_tree().get_first_node_in_group("game")
if game == null or not game.has_method("adjust_prediction_tuning"):
return
# Client-only live tuning: [/] threshold, -/= visual decay, ,/. visual
# offset, P present-time A/B. Deliberately no project input actions: these
# diagnostics never enter ShipAction or server/controller code.
match event.keycode:
KEY_BRACKETLEFT: game.adjust_prediction_tuning(-0.1)
KEY_BRACKETRIGHT: game.adjust_prediction_tuning(0.1)
KEY_MINUS: game.adjust_prediction_tuning(0.0, -0.01)
KEY_EQUAL: game.adjust_prediction_tuning(0.0, 0.01)
KEY_COMMA: game.adjust_prediction_tuning(0.0, 0.0, -0.05)
KEY_PERIOD: game.adjust_prediction_tuning(0.0, 0.0, 0.05)
KEY_P: game.adjust_prediction_tuning(0.0, 0.0, 0.0, true)
func _process(_delta: float) -> void:
if not _label or not _label.visible:
return
if NetworkManager.is_server:
_label.text = "NET: server, %d peer(s) out %s in %s" % [
MatchNet.roster.size(), _format_kbps(MatchSim.get_bytes_sent_per_sec()), _format_kbps(MatchSim.get_bytes_received_per_sec()),
]
elif NetworkManager.is_client:
if NetworkManager.rtt_ms < 0.0:
_label.text = "NET: client, connecting (no clock sample yet)"
else:
# task 3.7: RTT, jitter, loss, buffer depth, snapshot age,
# bandwidth all live here now. Prediction error is intentionally
# absent — there is no client-side prediction until Phase 4, so
# there is nothing honest to show for it yet. STALLED shows the
# server's own InputJitterBuffer.stalled bit for this client's
# slot, round-tripped through the wire.
var stats := {}
var game := get_tree().get_first_node_in_group("game")
if game and game.has_method("get_net_debug_stats"):
stats = game.get_net_debug_stats()
var stalled_suffix := " STALLED" if stats.get("server_stalled", false) else ""
var prediction: Dictionary = stats.get("prediction", {})
_label.text = "NET: client RTT %.1fms jitter %.1fms offset %.1fms\nbuf depth %s (target %s) lead %s loss %.1f%% snap age %.1fms%s\npred pos p50/p95/p99 %.3f / %.3f / %.3fm\npred rot p50/p95/p99 %.2f / %.2f / %.2fdeg snaps %.2f/min\nremote residual p99 %.3fm / %.2fdeg A/B present=%s\ntune [/] pos %.2f -/= decay ,/. offset %.2f P toggle\nout %s in %s" % [
NetworkManager.rtt_ms, NetworkManager.jitter_ms, NetworkManager.clock_offset_ms,
str(stats.get("input_buffer_depth", -1)), str(stats.get("input_target_depth", "-")), str(stats.get("input_lead", "-")),
stats.get("snapshot_loss_pct", 0.0), stats.get("snapshot_age_ms", 0.0), stalled_suffix,
prediction.get("position_error_p50", 0.0), prediction.get("position_error_p95", 0.0), prediction.get("position_error_p99", 0.0),
prediction.get("rotation_error_p50", 0.0), prediction.get("rotation_error_p95", 0.0), prediction.get("rotation_error_p99", 0.0), prediction.get("hard_snap_rate_per_min", 0.0),
stats.get("remote_residual_position_p99", 0.0), stats.get("remote_residual_rotation_p99", 0.0), str(game.remote_visual_present_time_enabled if game else false),
prediction.get("position_threshold", 0.0), prediction.get("max_visual_offset", 0.0),
_format_kbps(MatchSim.get_bytes_sent_per_sec()), _format_kbps(MatchSim.get_bytes_received_per_sec()),
]
else:
_label.text = "NET: offline"
func _format_kbps(bytes_per_sec: float) -> String:
return "%.2f KB/s" % (bytes_per_sec / 1000.0)
+1
View File
@@ -0,0 +1 @@
uid://cn2rdmwfo7phi
+126
View File
@@ -0,0 +1,126 @@
class_name NetInterpolator
extends RefCounted
# Buffers recent snapshot samples for ONE remote body and produces
# interpolated states at any requested (possibly fractional) server tick —
# used twice per body (MULTIPLAYER_SPEC.md §4.1/§4.6, "dual-time remote
# entities"): once at the present-time estimate for the collider, once
# further back at present-minus-INTERP_DELAY for $Visual.
#
# server_tick (Engine.get_physics_frames() at send time) maps to an
# estimated server wall-clock time via TICK_HZ without any extra
# synchronization: both Engine.get_physics_frames() and Time.get_ticks_msec()
# count from the same process-start epoch, and physics has been running at
# a steady TICK_HZ the whole time, so tick_ms_of(tick) = tick * (1000/TICK_HZ)
# is a valid estimate of "what Time.get_ticks_msec() read on the server when
# it sent that tick." Callers convert a NetworkManager.get_server_time_estimate_ms()
# reading into the same tick-space with to_tick(ms) before calling sample_at().
const NetBodyState = preload("res://scripts/net_body_state.gd")
const SimConstants = preload("res://scripts/sim_constants.gd")
const MAX_SAMPLES := 16
# §4.6: "never extrapolate indefinitely — a stuck ship reads better than one
# flying through a wall."
const MAX_EXTRAPOLATION_MS := 150.0
const TICK_MS := 1000.0 / SimConstants.TICK_HZ
var _samples: Array[Dictionary] = [] # [{tick:int, state:NetBodyState}], oldest first
var reset_gen := -1 # -1: no sample yet, so the first real sample is never treated as a mid-flight reset
static func to_tick(server_time_ms: float) -> float:
return server_time_ms / TICK_MS
# Returns true if this sample's reset_gen differs from the last one seen —
# the caller's cue to hard-snap instead of interpolating across a
# server-authoritative teleport (kickoff, goal reset) rather than sliding
# across the arena. Clears buffered history on a reset so a stale
# pre-reset sample can never bracket a post-reset one.
func add_sample(server_tick: int, state: NetBodyState, sample_reset_gen: int) -> bool:
# Never let a stale unreliable snapshot rewrite the epoch. The previous
# ordering cleared samples on its reset byte before checking tick order,
# so a delayed pre-reset packet could alternately flip generations and
# repeatedly cancel an active local ball handoff.
if not _samples.is_empty() and server_tick <= _samples.back()["tick"]:
return false
var is_reset := reset_gen != -1 and sample_reset_gen != reset_gen
if is_reset:
_samples.clear()
reset_gen = sample_reset_gen
_samples.append({"tick": server_tick, "state": state})
if _samples.size() > MAX_SAMPLES:
_samples.pop_front()
return is_reset
func has_samples() -> bool:
return not _samples.is_empty()
func accepts_tick(server_tick: int) -> bool:
return _samples.is_empty() or server_tick > int(_samples.back()["tick"])
func latest() -> NetBodyState:
return _samples.back()["state"] if not _samples.is_empty() else null
# target_tick may be fractional (a point in time between two integer ticks).
func sample_at(target_tick: float) -> NetBodyState:
if _samples.is_empty():
return null
if _samples.size() == 1:
return _samples[0]["state"]
if target_tick <= _samples[0]["tick"]:
return _samples[0]["state"]
var newest: Dictionary = _samples.back()
if target_tick >= newest["tick"]:
return _extrapolate(newest, target_tick)
for i in range(_samples.size() - 1):
var a: Dictionary = _samples[i]
var b: Dictionary = _samples[i + 1]
if a["tick"] <= target_tick and target_tick <= b["tick"]:
var a_tick: float = a["tick"]
var b_tick: float = b["tick"]
var span := b_tick - a_tick
var t: float = (target_tick - a_tick) / span if span > 0.0 else 0.0
return _lerp_state(a["state"], b["state"], t)
return newest["state"]
func _lerp_state(a: NetBodyState, b: NetBodyState, t: float) -> NetBodyState:
var out := NetBodyState.new()
out.position = a.position.lerp(b.position, t)
out.rotation = a.rotation.slerp(b.rotation, t)
out.linear_velocity = a.linear_velocity.lerp(b.linear_velocity, t)
out.angular_velocity = a.angular_velocity.lerp(b.angular_velocity, t)
out.frozen = b.frozen
out.turbo = b.turbo
out.thrust_z = b.thrust_z
out.stalled = b.stalled
out.avel_range = b.avel_range
return out
func _extrapolate(newest: Dictionary, target_tick: float) -> NetBodyState:
var state: NetBodyState = newest["state"]
var ticks_ahead: float = target_tick - float(newest["tick"])
var ms_ahead := ticks_ahead * TICK_MS
var clamped_ms := clampf(ms_ahead, 0.0, MAX_EXTRAPOLATION_MS)
var out := NetBodyState.new()
out.position = state.position + state.linear_velocity * (clamped_ms / 1000.0)
var angular_speed := state.angular_velocity.length()
if angular_speed > 0.00001:
out.rotation = (Quaternion(state.angular_velocity / angular_speed, angular_speed * (clamped_ms / 1000.0)) * state.rotation).normalized()
else:
out.rotation = state.rotation
out.linear_velocity = state.linear_velocity
out.angular_velocity = state.angular_velocity
out.frozen = state.frozen
out.turbo = state.turbo
out.thrust_z = state.thrust_z
out.stalled = state.stalled
out.avel_range = state.avel_range
return out
+1
View File
@@ -0,0 +1 @@
uid://cgb1vcapxami7

Some files were not shown because too many files have changed in this diff Show More