diff --git a/.changeset/netcode-events-across-saves.md b/.changeset/netcode-events-across-saves.md new file mode 100644 index 00000000..feceae0c --- /dev/null +++ b/.changeset/netcode-events-across-saves.md @@ -0,0 +1,21 @@ +--- +"@typeonce/ritmo-netcode": minor +--- + +**`session.events` confirms the ticks a save makes final.** A save (the match's start, `resync()`, a page seated again after it loaded again, a hidden page back under `"resync-on-return"`) is the host's world as it ran, guesses of other seats' input included. Until now every peer, the host too, withdrew the ticks it had run before the save but not confirmed yet, and never confirmed them: their events were gone without a word. Under rollback that is up to `maxRollback` ticks on every page at each save: a page that reloads mid-match lets the others run on guesses of its seat until it is back, so a lap, a checkpoint, or a sound of that stretch never reached any page. The page the save seated was not affected: it confirms every tick from the save on, as before. + +- The host confirms every tick it ran before its save. +- The save carries the inputs each of its last ticks ran with on the host. Every other peer confirms the ticks it ran with the same inputs, from a tick both confirmed; what `predicted()` handed out of them stands. +- The ticks before the save that a peer ran otherwise, confirmed otherwise (it had an input the host's world never got), or did not run at all, are reported by `lost()` with the new reason `"save"`, and what was predicted of them is withdrawn. A page the save seats for its first match (one that loaded again) is told nothing of the ticks before it: the save's world holds them. +- Fixed: a peer ahead of the host can confirm the save's own tick and the `inputDelay` ticks after it; `lost()` reported one tick fewer when a resync ran them again with other events. + +The sync message carries the inputs (protocol version 6, with this release's other session changes): every page of a match runs this release. + +**Breaking (types only):** `EventsLost["reason"]` is `"unread" | "resync" | "save"`. A `switch` over it adds a case; ticks reported `"save"` are ones whose events this peer cannot tell, like `"resync"`: + +```ts +const lost = hits.lost() +if (lost !== undefined && lost.reason !== "unread") { + // "resync" or "save": the match ran ticks lost.from to lost.to otherwise than this page acted on +} +``` diff --git a/.changeset/netcode-one-message-per-frame.md b/.changeset/netcode-one-message-per-frame.md index 12b55cca..02f2695e 100644 --- a/.changeset/netcode-one-message-per-frame.md +++ b/.changeset/netcode-one-message-per-frame.md @@ -10,7 +10,7 @@ Over 120 ms with 60 ms of jitter and 5% loss, on pages at 60 Hz that sometimes run two or three steps in a frame: 2 peers went from 139 messages and 62 KiB a second to 97 and 16 to 23 KiB; 8 peers from 728 and 290 KiB to 387 and 73 to 103 KiB (the lower figure for input held 20 frames, the higher for input that changes nearly every frame). -**Breaking: every page of a match must run this version.** The session protocol changed (version 5): a peer on 0.26 or older ends with `ProtocolMismatch`. +**Breaking: every page of a match must run this version.** The session protocol changed (version 6): a peer on 0.26 or older ends with `ProtocolMismatch`. **Breaking: the function `session.update(...)` returns takes the loop's two arguments.** Passed to `FixedLoop.start` as it is, nothing changes. Called from the game's own `update`, pass them through, so the session knows the frame's last step: diff --git a/integration/netcode/match.ts b/integration/netcode/match.ts index d29fdf1f..15f50726 100644 --- a/integration/netcode/match.ts +++ b/integration/netcode/match.ts @@ -19,6 +19,8 @@ export interface Peer { readonly heard: Array> /** Hits on screen as a flash: started when predicted, taken down when withdrawn, by tick. */ readonly flashes: Map> + /** Ticks before a resync's save that this peer ran on a guess the host's world did not share: their hits are not known here. */ + readonly lost: Array } type HitValue = { readonly seat: number; readonly shot: number } @@ -55,7 +57,7 @@ export const match = (options: MatchOptions): readonly [Peer, Peer] => { const shared = { simulate, seats: seats.value, seat, links: [links.value[seat]!], hostClock, step } const session = options.mode === "rollback" ? Netcode.rollback(runtime, shared) : Netcode.lockstep(runtime, shared) if (!session.ok) return fail("session", session.error) - return { runtime, screen, session: session.value, recorded: new Map(), heard: [], flashes: new Map() } + return { runtime, screen, session: session.value, recorded: new Map(), heard: [], flashes: new Map(), lost: [] } } const peers = [peer(0), peer(1)] as const // The host's effects read the simulation's hits through the session: one reader each. @@ -76,7 +78,9 @@ export const match = (options: MatchOptions): readonly [Peer, Peer] => { for (const { tick } of reader.withdrawn()) flashes.delete(tick) for (const { tick, value } of reader.predicted()) flashes.set(tick, [...flashes.get(tick) ?? [], value]) const lost = reader.lost() - if (lost !== undefined) fail(`seat ${seat} lost hits`, lost) + // A save can make final ticks this peer ran otherwise than the host: said, never silent. Nothing else is lost. + if (lost !== undefined && lost.reason === "save") peers[seat]!.lost.push(lost) + else if (lost !== undefined) fail(`seat ${seat} lost hits`, lost) } if (!hostClock.adjust(stepMS).ok) fail("clock", frame) } diff --git a/integration/netcode/test/netcode.test.ts b/integration/netcode/test/netcode.test.ts index 856e57be..108dd544 100644 --- a/integration/netcode/test/netcode.test.ts +++ b/integration/netcode/test/netcode.test.ts @@ -92,6 +92,9 @@ describe("two peers play the shooter over a slow, reordering network", () => { expect(status.verified).toBeGreaterThan(400) } expect(world(peers[0].runtime)).toBe(world(peers[1].runtime)) + // The host's saves are its world: it confirms every tick it ran. The other seat may not tell a few ticks before each save, and says so. + expect(peers[0].lost).toEqual([]) + for (const lost of peers[1].lost) expect(lost.to - lost.from).toBeLessThanOrEqual(8) }) }) diff --git a/packages/netcode/README.md b/packages/netcode/README.md index 4955fc51..d691c226 100644 --- a/packages/netcode/README.md +++ b/packages/netcode/README.md @@ -84,13 +84,14 @@ const hits = session.events(Hit) // an event of the runtime's schema; one reader for (const { tick } of hits.withdrawn()) particles.cancel(tick) // a rollback undid this tick's hits for (const { tick, value } of hits.predicted()) particles.burst(tick, value.at) // may still be undone for (const { value } of hits.confirmed()) sounds.play(value.kind) // exactly once per hit -const lost = hits.lost() // EventsLost: a reader that stopped reading, or a resync that replaced confirmed ticks; never silent +const lost = hits.lost() // EventsLost: a reader that stopped reading, a resync that replaced confirmed ticks, or ticks a save made final that this peer did not run as the host did; never silent ``` - `confirmed()` hands out each event once, when its tick can no longer run again within the epoch. A lockstep session confirms every tick it runs. A peer ahead of seat 0 can confirm a tick or two that seat 0's next save makes idle: when the resync runs them again with other events, `lost()` reports them with `reason: "resync"`, and the new run is not handed out again. - `predicted()` hands out events of ticks that may still be rolled back. A tick a rollback runs again keeps what was handed out when it publishes the same events (plain data, compared by value); otherwise it is withdrawn and its new events are predicted again. -- `withdrawn()` names those ticks, so the host cancels what it started. A resync withdraws every predicted tick. A tick waiting to be withdrawn is held back from `predicted()` until `withdrawn()` named it, so a cancel never undoes the new run. -- A reader that does not call `confirmed()` for more than `Netcode.eventWindow` ticks loses the oldest: `lost()` reports them as `EventsLost` with `reason: "unread"`. One report per call, a `"resync"` one first. +- A save (the match's start, a resync, a seat seated again after a reload or a hidden tab) makes every tick before it final as the host's world went through it, guesses included. Each peer confirms the ticks it ran with the same inputs as the host (the save carries them), and the host confirms every tick it ran. The ticks before the save that a peer ran otherwise, or did not run, are reported by `lost()` with `reason: "save"`, and what was predicted of them is withdrawn. A page the save seats for its first match (one that loaded again) is told nothing of the ticks before it: the save's world holds them. From the save's tick on, every peer confirms each tick once. +- `withdrawn()` names those ticks, so the host cancels what it started. A save withdraws every predicted tick from its own tick on, which runs again. A tick waiting to be withdrawn is held back from `predicted()` until `withdrawn()` named it, so a cancel never undoes the new run. +- A reader that does not call `confirmed()` for more than `Netcode.eventWindow` ticks loses the oldest: `lost()` reports them as `EventsLost` with `reason: "unread"`. One report per call: a `"resync"` one first, then `"save"`, then `"unread"`. When checksums differ, `advance` fails with `Desynced` until `resync()`. With `keepSnapshots: true` it carries this peer's save of that tick; `Desync.compare(mine, theirs)` from [`@typeonce/ritmo-devtools`](https://github.com/typeonce-dev/ritmo/blob/main/packages/devtools/README.md) lists what differs. diff --git a/packages/netcode/dtslint/Netcode.tst.ts b/packages/netcode/dtslint/Netcode.tst.ts index 932adedc..6733bc94 100644 --- a/packages/netcode/dtslint/Netcode.tst.ts +++ b/packages/netcode/dtslint/Netcode.tst.ts @@ -118,7 +118,7 @@ describe("session.events", () => { expect(hits.lost()).type.toBe() const lost = hits.lost() if (lost !== undefined) { - expect(lost.reason).type.toBe<"unread" | "resync">() + expect(lost.reason).type.toBe<"unread" | "resync" | "save">() // @ts-expect-error and '"rollback"' have no overlap if (lost.reason === "rollback") throw new Error("not a reason") } diff --git a/packages/netcode/src/Netcode.ts b/packages/netcode/src/Netcode.ts index b99607ab..31f551cc 100644 --- a/packages/netcode/src/Netcode.ts +++ b/packages/netcode/src/Netcode.ts @@ -430,8 +430,15 @@ export interface EventsLost { * ticks that the host's save makes idle). The new run's events are not * handed out; undo or ignore what the old ones started if it matters * (a score sent to a server). + * - `"save"`: a save made these ticks final, and this peer cannot tell + * their events as the match ran them: it ran them on a guess of another + * seat's input that the host's world did not share (the host saves its + * world as it ran, guesses included), or it confirmed them and the + * host's world went through them otherwise. What `predicted()` handed + * out of them is withdrawn. The ticks this peer ran as the host did are + * confirmed, and the host's own runs always are. */ - readonly reason: "unread" | "resync" + readonly reason: "unread" | "resync" | "save" } /** How many confirmed ticks of events a reader of `session.events(...)` that stopped reading keeps; older ones are {@link EventsLost}. */ @@ -450,15 +457,21 @@ export const eventWindow: number = EventsInternal.window * rollback runs again keeps what `predicted()` handed out when it publishes * the same events (plain data compared by value; a class instance or a map * counts as changed); otherwise it is withdrawn, and its new events are - * predicted again. A resync withdraws every predicted tick. A reader sees - * the ticks run from when it was made. + * predicted again. A save (the match's start, a resync, a page seated + * again) makes every tick before it final: the ticks this peer ran as the + * host's world did are confirmed, the others reported through `lost()`, + * and every predicted tick from the save on is withdrawn and runs again. + * Ticks before the save that this peer never ran are in the save's world, + * and no reader is told their events. A reader sees the ticks run from when + * it was made. */ export interface EventStreams { /** * Events of ticks that will not run again, each handed out once: a * rolled-back tick is handed out only as it finally ran. A lockstep * session confirms every tick it runs. Final within one epoch: a resync - * can replace ticks it handed out, which `lost()` reports. + * can replace ticks it handed out, which `lost()` reports. A save confirms + * the ticks before it that this peer ran as the host did. */ readonly confirmed: () => ReadonlyArray> /** @@ -475,8 +488,8 @@ export interface EventStreams { readonly withdrawn: () => ReadonlyArray /** * Confirmed events lost since the previous report: `undefined` when none. - * One report per call: when both reasons are pending, a `"resync"` one - * comes first and the `"unread"` one on the next call. + * One report per call: when several reasons are pending, a `"resync"` one + * comes first, then `"save"`, then `"unread"`, one on each call. */ readonly lost: () => EventsLost | undefined } diff --git a/packages/netcode/src/internal/events.ts b/packages/netcode/src/internal/events.ts index 5a8bcf52..96b8047e 100644 --- a/packages/netcode/src/internal/events.ts +++ b/packages/netcode/src/internal/events.ts @@ -21,6 +21,13 @@ * out for them; a tick that runs again with other events is reported * through `lost()` with the reason `"resync"`, and its new run is not * handed out as confirmed a second time. + * + * A save makes every tick before it final, as the host's world went through + * it, though this peer may have run the last of them only on a guess. The + * session tells the ledger how far this peer's runs were the host's + * (`save`): those ticks are handed out as confirmed; the ones after, up to + * the save, are reported through `lost()` with the reason `"save"`, whether + * this peer ran them otherwise, confirmed them otherwise, or never ran them. */ import * as Inspector from "@typeonce/ritmo/Inspector" import * as System from "@typeonce/ritmo/System" @@ -39,8 +46,8 @@ interface Reader { readonly delivered: Map> /** Ticks a rewind undid after `predicted()` handed out their records, not read yet. */ readonly withdrawn: Set - /** Confirmed events dropped unread, and confirmed ticks a resync ran again with other events: reported apart. */ - readonly lost: { unread: Range | undefined; resync: Range | undefined } + /** Confirmed events dropped unread, confirmed ticks a resync ran again with other events, and ticks a save made final that this peer did not run as the host did: reported apart. */ + readonly lost: { unread: Range | undefined; resync: Range | undefined; save: Range | undefined } } interface Range { @@ -57,8 +64,15 @@ export interface Ledger { readonly rewind: (from: number) => void /** After a rollback ran again: withdraws what readers saw of ticks that did not run again. */ readonly resolve: () => void - /** Every unsettled tick is gone: a resync. Withdraws everything predicted. */ - readonly reset: () => void + /** + * A save at tick `at`, restored: every tick before it is final. This + * peer's runs before `final` were the host's: their records are handed out + * as confirmed. The ticks from `final` up to `at` are lost (`"save"`): + * this peer ran them otherwise, confirmed them otherwise, or never ran + * them. Every unsettled tick from `at` on is gone, and what was predicted + * of it withdrawn. + */ + readonly save: (at: number, final: number) => void /** Every tick before `settled` will not run again: hands its records to the readers' confirmed queues once. */ readonly settle: (previous: number, settled: number) => void /** A new reader, from tick `from` on. */ @@ -71,7 +85,7 @@ export interface LedgerHost { readonly inspect: (inspector: unknown) => unknown /** The ticks before this one are settled. */ readonly settled: () => number - /** How many ticks before `settled()` a resync can run again: the idle ticks after a save. */ + /** How many ticks before `settled()` a resync can run again: the save's tick and the idle ones after it. */ readonly resyncReach: number } @@ -160,9 +174,23 @@ export const make = (host: LedgerHost, descriptor: { readonly name: string }): L resolve: () => { for (const reader of readers) for (const tick of reader.delivered.keys()) if (!log.has(tick)) withdraw(reader, tick) }, - reset: () => { + save: (at, final) => { + const before = [...log.keys()].filter((tick) => tick < at).sort(byTick) + for (const reader of readers) { + // Not as the host's world went through them: run otherwise, confirmed otherwise, or not run here at all. + const from = Math.max(final, reader.from) + if (from < at) lose(reader, "save", from, at) + for (const tick of before) { + if (tick < reader.from) continue + if (tick < final) { + // Run as the host ran it: what `predicted()` handed out of it stands. + for (const value of log.get(tick)!) reader.confirmed.push({ tick, value }) + reader.delivered.delete(tick) + } else if (reader.delivered.has(tick)) withdraw(reader, tick) + } + for (const tick of reader.delivered.keys()) withdraw(reader, tick) + } log.clear() - for (const reader of readers) for (const tick of reader.delivered.keys()) withdraw(reader, tick) }, settle: (previous, settled) => { const ticks = [...log.keys()].filter((tick) => tick < settled).sort(byTick) @@ -200,7 +228,7 @@ export const make = (host: LedgerHost, descriptor: { readonly name: string }): L for (const tick of handedOut.keys()) if (tick < settled - host.resyncReach) handedOut.delete(tick) }, reader: (from) => { - const reader: Reader = { from, confirmed: [], delivered: new Map(), withdrawn: new Set(), lost: { unread: undefined, resync: undefined } } + const reader: Reader = { from, confirmed: [], delivered: new Map(), withdrawn: new Set(), lost: { unread: undefined, resync: undefined, save: undefined } } readers.push(reader) return { confirmed: () => { @@ -226,8 +254,8 @@ export const make = (host: LedgerHost, descriptor: { readonly name: string }): L return ticks }, lost: (): EventsLost | undefined => { - // One report per call, a resync's first: it replaced events the host may have acted on. - const reason = reader.lost.resync !== undefined ? "resync" : "unread" + // One report per call, a resync's first: it replaced events the host may have acted on; then a save's. + const reason = reader.lost.resync !== undefined ? "resync" : reader.lost.save !== undefined ? "save" : "unread" const lost = reader.lost[reason] if (lost === undefined) return undefined reader.lost[reason] = undefined diff --git a/packages/netcode/src/internal/session.ts b/packages/netcode/src/internal/session.ts index 424e1e25..39eae2b0 100644 --- a/packages/netcode/src/internal/session.ts +++ b/packages/netcode/src/internal/session.ts @@ -234,6 +234,13 @@ export const make = (mode: Mode, runtime: Driven, options: MakeOptions): Result. const contiguous: Array = Array.from({ length: count }, () => -1) /** Per seat, the key of the input each tick ran with. */ const used: Array> = Array.from({ length: count }, () => new Map()) + /** + * Per tick, the keys of every seat's input it last ran with, in seat order, + * as one JSON array: a save carries the host's (`Wire.Sync.ran`), so a + * peer that ran those ticks on a guess knows which of its runs were the + * host's. + */ + const ranKeys = new Map() let wrong: number | undefined /** Ticks a rise of the delay skipped, filled idle by the next `record`. */ let raised = 0 @@ -544,6 +551,14 @@ export const make = (mode: Mode, runtime: Driven, options: MakeOptions): Result. } } + /** + * How far back `ranKeys` reaches: past every tick a save's `ran` can name. + * A save names its host's ticks from `maxRollback` before its settled + * ones, which are at most `maxRollback` before its next tick; a peer runs + * up to `furthestAhead` past that. + */ + const ranReach = furthestAhead + 2 * maxRollback + /** Ticks `tick` with the input of every seat, after its checksum and checkpoint. */ const runTick = (tick: number): boolean => { if ((tick - syncTick) % every === 0) { @@ -558,12 +573,20 @@ export const make = (mode: Mode, runtime: Driven, options: MakeOptions): Result. // After a rollback the checkpoint it rewound to is still held and is this tick's: taking another would spend a slot of the runtime's window for nothing. if (mode === "rollback" && !history.has(tick)) history.set(tick, runtime.checkpoint(options.simulate)) const current: Array = [] + // Each key is the canonical JSON of an input, so the list is a JSON array: two runs with other inputs never share it. Lockstep runs nothing on a guess, and a save names none of its ticks. + let ran = "[" for (let other = 0; other < count; other++) { const input = inputFor(other, tick) current.push(input) - if (other !== seat) used[other]!.set(tick, keyOf(input)) + const key = other !== seat || mode === "rollback" ? keyOf(input) : "" + if (other !== seat) used[other]!.set(tick, key) + if (mode === "rollback") ran += other === 0 ? key : `,${key}` } seatsState.current = current + if (mode === "rollback") { + ranKeys.set(tick, `${ran}]`) + ranKeys.delete(tick - ranReach) + } for (const ledger of ledgers.values()) ledger.skip() const ticked = runtime.tick(options.simulate) if (ticked.ok) for (const ledger of ledgers.values()) ledger.record(tick) @@ -594,6 +617,26 @@ export const make = (mode: Mode, runtime: Driven, options: MakeOptions): Result. return ran } + /** + * The tick up to which this peer's runs before `message`'s save were the + * host's: from a tick both confirmed with every seat's real input, each + * tick ran with the same inputs as the host's (`ran`), so the world went + * through it the same way. The ticks after it, up to the save, are lost + * to this peer's readers. The host's own save is its world: every tick + * it ran. A session the save seats for its first match has no ticks + * before it to lose. + */ + const ranAsSaved = (message: Wire.Sync): number => { + if (message.from === seat || epoch === 0) return message.tick + // Another history than the save's: a save between missed, or ticks run while out of the match. + if (message.epoch !== epoch + 1 || out !== undefined) return settled + // The host's ticks before `ranFrom` ran with real inputs, as this peer's settled ones did: the worlds agree up to the first of either. + if (message.ranFrom > settled) return settled + const until = Math.min(message.tick, next) + for (let at = message.ranFrom; at < until; at++) if (ranKeys.get(at) !== message.ran[at - message.ranFrom]) return at + return until + } + /** Restores a save every peer restores at its tick, takes its roster, and runs again up to where this peer was. */ const applySync = (message: Wire.Sync): void => { const restored = runtime.restore(message.save) @@ -603,8 +646,15 @@ export const make = (mode: Mode, runtime: Driven, options: MakeOptions): Result. } const tick = message.tick const previous = next - // Every unsettled tick is gone: the save replaces them. - for (const ledger of ledgers.values()) ledger.reset() + // The ticks before the save are final, as the host's world went through them: the ones this peer ran as the host did are confirmed. + const final = ranAsSaved(message) + for (const ledger of ledgers.values()) { + // Ticks a resync ran again before this save, and not settled yet: compared with what was handed out of them. + ledger.settle(settled, settled) + ledger.save(tick, final) + } + settled = Math.max(settled, tick) + ranKeys.clear() epoch = message.epoch syncFrom = message.from syncTick = tick @@ -711,7 +761,13 @@ export const make = (mode: Mode, runtime: Driven, options: MakeOptions): Result. for (let at = next + saveDelay; at <= last && known.has(at) && ahead[other]!.length < Wire.maxInputsAhead; at++) ahead[other]!.push(known.get(at)) } } - syncMessage = { k: "sync", from: seat, epoch: epoch + 1, tick: next, save, returned: tracker.shown.slice(), sessions: named, roster: roster + (seated > 0 ? 1 : 0), left, ahead } + // What this world went through before the save, from `maxRollback` before the ticks it settled (a peer may have settled fewer): the inputs of every tick a peer may have run on a guess. Lockstep runs none on a guess. + let ranFrom = next + const lowest = mode === "rollback" ? Math.max(syncTick, settled - maxRollback) : next + while (ranFrom > lowest && ranKeys.has(ranFrom - 1)) ranFrom -= 1 + const ran: Array = [] + for (let at = ranFrom; at < next; at++) ran.push(ranKeys.get(at)!) + syncMessage = { k: "sync", from: seat, epoch: epoch + 1, tick: next, save, returned: tracker.shown.slice(), sessions: named, roster: roster + (seated > 0 ? 1 : 0), left, ahead, ranFrom, ran } applySync(syncMessage) broadcast(syncMessage) syncSentAt.fill(clock.now()) @@ -1632,7 +1688,8 @@ export const make = (mode: Mode, runtime: Driven, options: MakeOptions): Result. }), events: (descriptor) => { let ledger = ledgers.get(descriptor) - if (ledger === undefined) ledgers.set(descriptor, ledger = Events.make({ schema: runtime.schema, inspect: runtime.inspect, settled: () => settled, resyncReach: saveDelay }, descriptor)) + // A peer ahead of the host settles up to the host's own inputs, which reach `saveDelay` past the tick it saves at: a resync runs that tick and the `saveDelay` after it again (`resyncReach`). + if (ledger === undefined) ledgers.set(descriptor, ledger = Events.make({ schema: runtime.schema, inspect: runtime.inspect, settled: () => settled, resyncReach: saveDelay + 1 }, descriptor)) return ledger.reader(next) as never } } diff --git a/packages/netcode/src/internal/wire.ts b/packages/netcode/src/internal/wire.ts index 921ece07..e5829be1 100644 --- a/packages/netcode/src/internal/wire.ts +++ b/packages/netcode/src/internal/wire.ts @@ -11,7 +11,7 @@ */ /** Bumped when a message changes shape; peers on another version fail with `ProtocolMismatch`. */ -export const version = 5 +export const version = 6 /** * Why a seat is out of the match: it sent nothing for too long, its link @@ -60,6 +60,12 @@ export interface Hello extends Base { * seat, the inputs the host holds for the ticks after the save's idle ones, * when the save seats a session: the seats stopped sending those every * earlier session acknowledged, and a new one has none of them. + * + * `ran` is what the host's world went through before the save: from tick + * `ranFrom` up to `tick`, the inputs of every seat each tick ran with, one + * string a tick (a JSON array of their canonical forms, in seat order). A peer that ran a tick of it + * on a guess, with the same inputs from a tick both had confirmed, ran it as + * the save did: its events are the match's, and it confirms them. */ export interface Sync extends Base { readonly k: "sync" @@ -70,6 +76,8 @@ export interface Sync extends Base { readonly roster: number readonly left: ReadonlyArray readonly ahead: ReadonlyArray> + readonly ranFrom: number + readonly ran: ReadonlyArray } /** Asks seat 0 for a new save. */ @@ -381,7 +389,10 @@ const parseOne = (raw: unknown, from: number, bundleEpoch: number, seats: number if (!isCount(value["roster"]) || !Array.isArray(left) || left.length !== seats || !left.every((why) => why === null || isWhy(why))) return undefined const ahead = value["ahead"] if (!Array.isArray(ahead) || ahead.length !== seats || !ahead.every((inputs) => Array.isArray(inputs) && inputs.length <= maxInputsAhead)) return undefined - return { k: "sync", from, epoch, tick: value["tick"], save: value["save"], returned, sessions, roster: value["roster"], left, ahead } + const ran = value["ran"] + if (!isTick(value["ranFrom"]) || value["ranFrom"] < 0 || !Array.isArray(ran) || ran.length > maxInputsAhead || !ran.every((key) => typeof key === "string")) return undefined + if (value["ranFrom"] + ran.length !== value["tick"]) return undefined + return { k: "sync", from, epoch, tick: value["tick"], save: value["save"], returned, sessions, roster: value["roster"], left, ahead, ranFrom: value["ranFrom"], ran } } case "inputs": { const inputs = readInputs(value, maxInputsPerMessage) diff --git a/packages/netcode/test/Events.test.ts b/packages/netcode/test/Events.test.ts index cc8672fb..7701a524 100644 --- a/packages/netcode/test/Events.test.ts +++ b/packages/netcode/test/Events.test.ts @@ -97,11 +97,11 @@ describe("session.events", () => { expect(steps.filter((line) => line.includes("withdrawn"))).toEqual([]) }) - it("withdraws every predicted tick on a resync", () => { + it("on a resync, confirms the predicted ticks before the save that ran as the host's did, and withdraws the rest", () => { const match = setUpMatch({ mode: "rollback", latencyMS: 100, jitterMS: 0, inputDelay: 0 }) const [host] = match.peers const watchers = match.peers.map(watch) - // Both seats hold fire: every tick has events, and every guess is right, so only the resync withdraws. + // Both seats hold fire: every tick has events, and every guess is right, so every tick before the save ran as the host's did. const firing = (): PlayerInput => ({ dx: 0, fire: true }) const resyncs = [0, 0] for (let at = 0; at < 300; at++) { @@ -110,14 +110,25 @@ describe("session.events", () => { const before = watchers.map((watcher) => new Set(watcher.outstanding)) frame(match, at, firing) for (const [seat, peer] of match.peers.entries()) { - const { withdrawn } = watchers[seat]!.read() + const watcher = watchers[seat]! + const { withdrawn } = watcher.read() if (epochs[seat] === 0 || peer.session.status().epoch === epochs[seat]) continue resyncs[seat]! += 1 expect(before[seat]!.size).toBeGreaterThan(0) - for (const tick of before[seat]!) expect(withdrawn).toContain(tick) + // Each tick predicted before the save is now confirmed, or withdrawn; the confirmed ones come before the save, the withdrawn ones from it on. + const kept = [...before[seat]!].filter((tick) => watcher.history.get(tick)?.at(-1) === "confirmed") + const undone = [...before[seat]!].filter((tick) => withdrawn.includes(tick)) + expect(kept.length + undone.length).toBe(before[seat]!.size) + if (undone.length > 0) expect(Math.max(...kept)).toBeLessThan(Math.min(...undone)) + // The host's save is its world: it ran every tick before it, and withdraws none. + if (seat === 0) { + expect(kept.length).toBeGreaterThan(0) + expect(undone).toEqual([]) + } } } expect(resyncs).toEqual([1, 1]) + for (const watcher of watchers) expect(watcher.reader.lost()).toBeUndefined() }) it("under lockstep, confirms every event once and predicts nothing", () => { diff --git a/packages/netcode/test/Netcode.test.ts b/packages/netcode/test/Netcode.test.ts index 971f5921..0ef0596f 100644 --- a/packages/netcode/test/Netcode.test.ts +++ b/packages/netcode/test/Netcode.test.ts @@ -231,7 +231,7 @@ describe("Netcode.rollback", () => { const link: NetworkLink.NetworkLink = { send: () => {}, receive: () => inbox.splice(0), status: () => NetworkLink.open } const peer = makePeer() const session = valueOf(Netcode.rollback(peer.runtime, { simulate, seats: peer.seats, seat: 0, links: [link], hostClock, step })) - inbox.push("not json", JSON.stringify({ v: 5, from: 7, epoch: 0, m: [{ k: "hello", session: 1 }] })) + inbox.push("not json", JSON.stringify({ v: 6, from: 7, epoch: 0, m: [{ k: "hello", session: 1 }] })) expect(session.advance(idle).ok).toBe(true) expect(session.status().dropped).toBe(2) inbox.push(JSON.stringify({ v: 1, k: "hello", from: 1, epoch: 0 })) diff --git a/packages/netcode/test/Saved.test.ts b/packages/netcode/test/Saved.test.ts new file mode 100644 index 00000000..ff4ead23 --- /dev/null +++ b/packages/netcode/test/Saved.test.ts @@ -0,0 +1,247 @@ +/** + * `session.events` across a save that seats a peer again mid-match: a page + * that loads again, and a page that was hidden under `"resync-on-return"`. + * + * Every seat fires on every tick it presses, so every tick of the match + * publishes events except the save's idle ones. The host's run of a tick is + * the match's (every save is its world), so its confirmed events are the + * reference: it must confirm every tick it ran, the save's ticks before it + * included. Every other peer confirms each tick once, as the host ran it, + * or says through `lost()` that it cannot; the peer the save seats confirms + * every tick from the save on. + */ +import { describe, expect, it } from "vitest" +import { Random } from "@typeonce/ritmo" +import { Netcode, type NetworkLink } from "@typeonce/ritmo-netcode" + +import { Fired, type PlayerInput } from "./game.ts" +import { playOn, reload, setUpMatch, settleOn, stepMS, type MatchPeer } from "./match.ts" + +const firing = (seat: number, at: number): PlayerInput => ({ dx: ((at + seat) % 3) - 1, fire: true }) + +/** A reader on `peer` that keeps every record and report, and checks each read against the streams' rules. */ +const watch = (peer: MatchPeer) => { + const reader = peer.session.events(Fired) + const from = peer.session.status().tick + /** Confirmed records as `tick:seat:x`, by tick. */ + const confirmed = new Map>() + const lost: Array = [] + const outstanding = new Set() + const read = () => { + for (const { tick } of reader.withdrawn()) { + expect(outstanding.has(tick)).toBe(true) + outstanding.delete(tick) + } + for (const { tick } of reader.predicted()) { + expect(confirmed.has(tick)).toBe(false) + outstanding.add(tick) + } + const records = reader.confirmed() + const ticks = new Set() + for (const { tick, value } of records) { + // Each tick once: never one confirmed by an earlier read. + expect(confirmed.has(tick) && !ticks.has(tick)).toBe(false) + ticks.add(tick) + const values = confirmed.get(tick) ?? [] + values.push(`${tick}:${value.seat}:${value.x}`) + confirmed.set(tick, values) + outstanding.delete(tick) + } + for (let report = reader.lost(); report !== undefined; report = reader.lost()) lost.push(report) + } + const isLost = (tick: number): boolean => lost.some((report) => tick >= report.from && tick < report.to) + return { from, confirmed, lost, outstanding, read, isLost } +} + +type Watcher = ReturnType + +/** Every save's tick, as each seat sent or heard it. */ +const saves = () => { + const ticks = new Set() + const wrap = (_seat: number, link: NetworkLink.NetworkLink): NetworkLink.NetworkLink => { + const note = (text: string) => { + // One bundle a frame: its messages in `m`. + const bundle = JSON.parse(text) as { readonly m: ReadonlyArray<{ readonly k: string; readonly tick?: number }> } + for (const message of bundle.m) if (message.k === "sync") ticks.add(message.tick!) + } + return { + send: (text) => { + note(text) + link.send(text) + }, + receive: () => { + const arrived = link.receive() + for (const text of arrived) note(text) + return arrived + }, + status: link.status + } + } + return { ticks, wrap } +} + +/** + * The checks after a match. `seated` is the seat the last save seated again, + * and `at` that save's tick; `fresh`, when the save seated a new session (a + * page that loaded again), which is told nothing of the ticks before it. + */ +const expectExact = (match: ReturnType, watchers: ReadonlyArray, saved: ReadonlySet, seated: number, at: number, fresh: boolean, delay = 4) => { + // Up to the last tick any seat fired on: the idle frames that settle the match publish nothing. + const fired = Math.max(...match.peers.flatMap((peer) => [...peer.recorded].filter(([, input]) => input.fire).map(([tick]) => tick))) + const end = Math.min(fired + 1, ...match.peers.map((peer) => Math.min(peer.session.status().confirmed, peer.session.status().tick))) + const idleTick = (tick: number): boolean => [...saved].some((save) => tick >= save && tick < save + delay) + const [host] = watchers as [Watcher] + // The host confirms every tick of the match it ran, a save's ticks before it included. + const unconfirmed: Array = [] + for (let tick = 0; tick < end; tick++) if (!idleTick(tick) && !host.confirmed.has(tick)) unconfirmed.push(tick) + expect(unconfirmed).toEqual([]) + expect(host.lost).toEqual([]) + for (const [seat, watcher] of watchers.entries()) { + // From the save that seated it, the seated page confirms every tick, with nothing lost. + const start = seat === seated && fresh ? at : watcher.from + const wrong: Array = [] + for (let tick = start; tick < end; tick++) { + const theirs = host.confirmed.get(tick) + const mine = watcher.confirmed.get(tick) + const same = JSON.stringify(mine) === JSON.stringify(theirs) + // Not as the host ran it: only where `lost()` said so, and never on the seated page from its save on. + if (!same && ((seat === seated && tick >= at) || !watcher.isLost(tick))) wrong.push(`${tick}: ${mine?.join(" ") ?? "missing"} / ${theirs?.join(" ") ?? "none"}`) + } + expect({ seat, wrong }).toEqual({ seat, wrong: [] }) + if (seat === seated) expect(watcher.lost.filter((report) => report.to > at)).toEqual([]) + expect(watcher.outstanding.size).toBe(0) + } +} + +describe("session.events across a save that seats a peer", () => { + for (const mode of ["rollback", "lockstep"] as const) { + for (const count of mode === "rollback" ? [2, 3, 8] : [2, 3]) { + it(`a page that loads again: every peer confirms each tick once, as the host ran it (${mode}, ${count} seats)`, () => { + const { ticks: saved, wrap } = saves() + const match = setUpMatch({ mode, count, seed: 4, latencyMS: 60, jitterMS: 30, loss: 0.05, inputDelay: 4, maxRollback: 24, checkpoints: 24, checksumEvery: 10, wrap }) + const watchers = match.peers.map(watch) + const readAll = () => watchers.forEach((watcher) => watcher.read()) + for (let at = 0; at < 120; at++) { + playOn(match, 1, { input: (seat) => firing(seat, at) }) + readAll() + } + const seated = count - 1 + const before = new Set(saved) + reload(match, seated) + watchers[seated] = watch(match.peers[seated]!) + for (let at = 120; at < 360; at++) { + playOn(match, 1, { input: (seat) => firing(seat, at) }) + readAll() + } + settleOn(match) + readAll() + expect(match.halts).toEqual([]) + const at = Math.max(...[...saved].filter((tick) => !before.has(tick))) + expect(match.peers[0]!.session.status().epoch).toBe(2) + expectExact(match, watchers, saved, seated, at, true) + }) + + it(`a page hidden under "resync-on-return": every peer confirms each tick once, as the host ran it (${mode}, ${count} seats)`, () => { + const { ticks: saved, wrap } = saves() + const match = setUpMatch({ mode, count, seed: 5, latencyMS: 60, jitterMS: 30, loss: 0.05, inputDelay: 4, maxRollback: 24, checkpoints: 24, checksumEvery: 10, hidden: { afterMS: 30_000, then: "resync-on-return" }, wrap }) + const watchers = match.peers.map(watch) + const readAll = () => watchers.forEach((watcher, seat) => { + if (!match.peers[seat]!.visibility.hidden()) watcher.read() + }) + const seated = count - 1 + for (let at = 0; at < 120; at++) { + playOn(match, 1, { input: (seat) => firing(seat, at) }) + readAll() + } + match.peers[seated]!.visibility.hide() + for (let at = 120; at < 200; at++) { + playOn(match, 1, { input: (seat) => firing(seat, at) }) + readAll() + } + const before = new Set(saved) + match.peers[seated]!.visibility.show() + for (let at = 200; at < 400; at++) { + playOn(match, 1, { input: (seat) => firing(seat, at) }) + readAll() + } + settleOn(match) + readAll() + expect(match.halts).toEqual([]) + const at = Math.max(...[...saved].filter((tick) => !before.has(tick))) + expect(match.peers[0]!.session.status().epoch).toBe(2) + expectExact(match, watchers, saved, seated, at, false) + }) + } + } + + /** + * Seeded matches with hitches (a page that draws nothing for a while, then + * runs every step it owes in one frame, as `FixedLoop` does) and an + * adaptive delay. The seeds are ones that failed before: under lockstep, a + * peer ahead of the host confirms up to the host's own inputs, one tick + * further than the ledger kept, so `lost()` missed the save's own tick. + */ + describe("with hitches and an adaptive delay", () => { + const cases = [ + { path: "hidden", mode: "lockstep", count: 3, seed: 3 }, + { path: "hidden", mode: "lockstep", count: 4, seed: 6 }, + { path: "hidden", mode: "lockstep", count: 4, seed: 7 }, + { path: "reload", mode: "rollback", count: 4, seed: 5 }, + { path: "hidden", mode: "rollback", count: 3, seed: 8 } + ] as const + for (const { path, mode, count, seed } of cases) { + it(`${path === "reload" ? "a page that loads again" : "a hidden page"} (${mode}, ${count} seats, seed ${seed})`, () => { + const { ticks: saved, wrap } = saves() + const latencyMS = 30 + (seed % 4) * 25 + const random = Random.make(seed * 7919) + const match = setUpMatch({ mode, count, seed, latencyMS, jitterMS: latencyMS / 2, loss: 0.05, checksumEvery: 10, timeoutMS: 3000, adaptiveDelay: { min: 2, max: 6 }, maxRollback: 48, checkpoints: 48, wrap, ...(path === "hidden" ? { hidden: { afterMS: 30_000, then: "resync-on-return" as const } } : {}) }) + const watchers = match.peers.map(watch) + const seated = 1 + (seed % (count - 1)) + const owed = match.peers.map(() => 0) + let at = 0 + const play = (frames: number) => { + for (let n = 0; n < frames; n++, at++) { + for (const [seat, peer] of match.peers.entries()) { + if (peer.visibility.hidden()) continue + owed[seat]! += 1 + // A hitch: this page draws nothing for a while, then catches up in one frame. + if (random.next() < 0.08) continue + if (random.next() < 0.02) { + owed[seat]! += random.integer(0, 24) + continue + } + const steps = Math.min(30, owed[seat]!) + owed[seat] = 0 + for (let step = 0; step < steps; step++) { + const input = firing(seat, at) + const advanced = peer.session.advance(input) + if (!advanced.ok) match.halts.push(`seat ${seat}: ${advanced.error._tag}`) + else if (advanced.value._tag !== "Waiting" && advanced.value.input !== undefined) peer.recorded.set(advanced.value.input, input) + } + watchers[seat]!.read() + } + match.hostClock.adjust(stepMS) + } + } + play(100 + seed * 7) + const before = new Set(saved) + if (path === "reload") { + reload(match, seated) + watchers[seated] = watch(match.peers[seated]!) + } else { + match.peers[seated]!.visibility.hide() + play(30 + seed * 5) + match.peers[seated]!.visibility.show() + } + play(300) + settleOn(match) + for (const watcher of watchers) watcher.read() + expect(match.halts).toEqual([]) + const after = [...saved].filter((tick) => !before.has(tick)) + expect(after.length).toBeGreaterThan(0) + expectExact(match, watchers, saved, seated, Math.max(...after), path === "reload", 6) + }) + } + }) +}) + diff --git a/packages/netcode/test/match.ts b/packages/netcode/test/match.ts index 91cf085e..762226a9 100644 --- a/packages/netcode/test/match.ts +++ b/packages/netcode/test/match.ts @@ -277,5 +277,5 @@ export const wire = (message: { readonly from: number; readonly epoch: number; r const { from, epoch, inputs, ...rest } = message const acks = rest["k"] === "inputs" ? { acks: (rest["acks"] as ReadonlyArray).map((ack) => (rest["next"] as number) - ack) } : {} const written = { ...rest, ...acks, ...(inputs === undefined ? {} : { d: inputs, i: inputs.map((_, index) => index) }) } - return JSON.stringify({ v: 5, from, epoch, m: [written] }) + return JSON.stringify({ v: 6, from, epoch, m: [written] }) }