commit 98bbf09521e4e0771d7f6b01faad728e5ae2216c
parent ee8d392804cd77954680a8f7ab7fe4871655b4e1
Author: anon <anon@example.com>
Date: Tue, 27 Oct 2026 19:56:32 +0000
Persist mission world assignments with accepted contracts
Diffstat:
8 files changed, 452 insertions(+), 10 deletions(-)
diff --git a/TODO.md b/TODO.md
@@ -1510,6 +1510,13 @@ client rendering fixes and checks are in [nano damage](docs/nano-damage.md).
Introduce explicit instance isolation across movement/terrain, visibility,
combat, nanos, loot, inspection, trading and vicinity chat. Persist assignment/return
transitions immediately; ordinary periodic position checkpoints are insufficient.
+ Accepted missions now save an independently allocated runtime world ID and
+ the exact native generator bytes in the key/inventory transaction. A durable
+ counter prevents ID reuse after retirement; failed allocation, ignored writes,
+ commit failure and concurrent owners are covered. Cold reload preserves the
+ assignment, and a published-WASM replay of an actual saved assignment loads
+ world65536, traverses both rooms and jumps/lands on its raised mesh. This is
+ assignment persistence, not a working entrance or durable entry/return flow.
Include private-instance retirement on abandonment/expiry without affecting
another owner's assignment or admitting holders of revoked key bindings.
Original 14.9.1 generator serialization now preserves variable room lists;
diff --git a/docs/mission-interiors.md b/docs/mission-interiors.md
@@ -490,3 +490,62 @@ with logs `mission-movement-full-server-tests.json`,
The final mission-fixture cleanup recheck passes 31 results in
`mission-movement-final-fixture-tests.json`; those fixtures close their SQLite
world handles as well as their original-resource files.
+
+## Persistent mission assignments
+
+Acceptance now allocates a runtime world identity independently of the mission
+key's item identity. The world row retains a monotonic `last_playfield_id`
+counter, starting after the original 16-bit public-resource namespace. The
+mission row stores that world ID and its exact generator blob, committing them
+with the contract, key and inventory ownership. Retirement deletes the contract
+and assignment while retaining the counter, so a stale world identity cannot be
+reassigned to a later mission.
+
+The native version 3 generator codec is shared by storage and playfield packets:
+unsigned dimensions, library ID, ambient values and the ordered six-byte room
+records have one encoder. The reader rejects malformed framing, invalid fields
+and unsupported generator versions. Version 3 is the original client protocol,
+not a compatibility format for earlier server schemas. Existing development
+databases need a fresh schema; there is no migration or legacy reader. The
+shared preview has not been reset or restarted for this change.
+
+Allocation participates in the inventory transaction and is verified again
+before commit. Tests cover aborted/ignored/rewound allocation, a later world-row
+rewrite, deferred commit failure and retry, concurrent owners, cold reload,
+retirement/expiry, counter exhaustion and corrupt layout rejection. Existing
+acceptance-failure tests now also check that the world counter rolled back.
+The saved layout remains independent of later generator-code or catalog edits.
+
+An owned published-WASM fixture 297 loads a packet constructed from a real
+accepted mission after SQLite reload. Its runtime world is 65536, the native
+object identity is 40016/65536, and the two generated rooms match the expected
+anchors within 0.00005 units. The native room link has an empty door identity.
+The client crosses into the chamber, returns, jumps and lands on the entrance's
+raised biological mesh. Go reproduces the captured settled mesh contact near
+[15.027545,2.160428,21.828888] within 0.002 units. Screenshots were reviewed on the
+GPU. No page exception or adapter failure occurred; two browser console 404s
+remain in the capture. The owned browser closes before builds and race tests.
+
+This replay changes only the owned client's incoming world stream. It does not
+exercise a server entrance, key admission, durable character entry/return,
+private-world loading during ordinary reconnect, cross-system isolation,
+occupant evacuation or mission rewards. Those remain required before enabling
+mission entry. No client source or published WASM artifact changes.
+
+Evidence in `local/mission-interior/` includes
+`persistent-instance-entry.json`/`.bin`, `persistent-instance-packet.log`,
+`persisted-entry-overlay.json`, `tmp_persisted_entry_test.go`,
+`tmp_native_persisted_instance.mjs`, `runtime-persisted-instance/`,
+`persistent-instance-native-verification.json` and
+`persistent-raised-mesh-test.log`. The saved generator is
+`000300040006000a0000014b64646400000002000000010302002500010100`;
+the native packet SHA256 is
+`47a032014534b636e3e1311345cff9439fed3349f609418c85594206f51aabbc`.
+
+Focused mission regressions pass 66 root tests/592 results. The broader
+mission/inventory/database race run passes 82 roots/629 results against the same
+production code; the final focused run additionally includes the alternate
+saved-layout preservation case. Build and vet pass. Logs are
+`persistent-instance-final-tests.json` and `persistent-instance-race-tests.json`;
+`persistent-instance-verification.json` records their counts. These are fresh
+SQLite fixtures. No backward-compatibility path or extra preview server is added.
diff --git a/server/item_database.go b/server/item_database.go
@@ -225,6 +225,11 @@ func (server *server) persistItems_locked(store itemStore) error {
store.LastID, server.nextCharacter, server.nextNPC, server.gameSeconds, started.UTC().Format(time.RFC3339Nano)).Scan(&savedID); err != nil {
return fmt.Errorf("world inventory allocation was not saved: %w", err)
}
+ if store.mission != nil {
+ if err := tx.QueryRow("SELECT id FROM world WHERE id=1 AND last_playfield_id=?", store.mission.world).Scan(&savedID); err != nil {
+ return fmt.Errorf("mission world allocation was not saved: %w", err)
+ }
+ }
if err := tx.Commit(); err != nil {
return err
}
diff --git a/server/mission_geometry.go b/server/mission_geometry.go
@@ -35,7 +35,8 @@ func (layout missionLayout) validate() error {
}
func missionPlayfieldPacket(player *character, layout missionLayout) ([]byte, error) {
- if err := layout.validate(); err != nil {
+ generator, err := layout.blob()
+ if err != nil {
return nil, err
}
@@ -53,6 +54,19 @@ func missionPlayfieldPacket(player *character, layout missionLayout) ([]byte, er
for _, value := range []uint32{51103, player.playfield, 0} {
body = binary.BigEndian.AppendUint32(body, value)
}
+ body = append(body, generator...)
+ // KKR PlayfieldAnarchyFIIR 0x10145f00 reads two origins; conversion removes the legacy empty name.
+ for _, value := range []uint32{0, 0, 0} {
+ body = binary.BigEndian.AppendUint32(body, value)
+ }
+ return n3Packet(0x5f4b1a39, 40016, player.playfield, body), nil
+}
+
+func (layout missionLayout) blob() ([]byte, error) {
+ if err := layout.validate(); err != nil {
+ return nil, err
+ }
+ var body []byte
for _, value := range []uint16{3, layout.width, layout.depth, layout.floorHeight} {
body = binary.BigEndian.AppendUint16(body, value)
}
@@ -63,9 +77,32 @@ func missionPlayfieldPacket(player *character, layout missionLayout) ([]byte, er
body = binary.BigEndian.AppendUint16(body, room.template)
body = append(body, byte(room.floor), room.x, room.z, room.rotation)
}
- // KKR PlayfieldAnarchyFIIR 0x10145f00 reads two origins; conversion removes the legacy empty name.
- for _, value := range []uint32{0, 0, 0} {
- body = binary.BigEndian.AppendUint32(body, value)
+ return body, nil
+}
+
+func decodeMissionLayout(blob []byte) (missionLayout, error) {
+ // The database retains the same current generator blob used by the native packet.
+ if len(blob) < 19 || binary.BigEndian.Uint16(blob) != 3 {
+ return missionLayout{}, fmt.Errorf("invalid mission generator header")
}
- return n3Packet(0x5f4b1a39, 40016, player.playfield, body), nil
+ count := binary.BigEndian.Uint32(blob[15:19])
+ if count == 0 || count > 10000 || uint64(len(blob)) != 19+6*uint64(count) {
+ return missionLayout{}, fmt.Errorf("invalid mission generator room framing")
+ }
+ layout := missionLayout{width: binary.BigEndian.Uint16(blob[2:4]), depth: binary.BigEndian.Uint16(blob[4:6]),
+ floorHeight: binary.BigEndian.Uint16(blob[6:8]), template: binary.BigEndian.Uint32(blob[8:12]),
+ ambient: [3]byte(blob[12:15]), rooms: make([]missionRoom, count)}
+ for index := range layout.rooms {
+ data := blob[19+6*index : 25+6*index]
+ layout.rooms[index] = missionRoom{template: binary.BigEndian.Uint16(data), floor: int8(data[2]), x: data[3], z: data[4], rotation: data[5]}
+ }
+ if err := layout.validate(); err != nil {
+ return missionLayout{}, err
+ }
+ return layout, nil
+}
+
+func starterMissionLayout() missionLayout {
+ return missionLayout{template: 331, width: 4, depth: 6, floorHeight: 10, ambient: [3]byte{100, 100, 100},
+ rooms: []missionRoom{{template: 0, x: 1, z: 3, rotation: 2}, {template: 37, x: 1, z: 1}}}
}
diff --git a/server/mission_instance_test.go b/server/mission_instance_test.go
@@ -0,0 +1,313 @@
+package main
+
+import (
+ "ao/server/gamedata"
+ "bytes"
+ "encoding/binary"
+ "reflect"
+ "sync"
+ "testing"
+ "time"
+)
+
+func TestMissionAssignmentPersistsDistinctWorldAndExactGenerator(t *testing.T) {
+ world, _ := newAcceptedMissionWorld(t)
+ t.Cleanup(func() { world.db.Close() })
+ mission := world.characters[1].missions[0]
+ for identity := range gamedata.Playfields {
+ if identity >= 65536 {
+ t.Fatal("public catalog overlaps the reserved private namespace", identity)
+ }
+ }
+
+ cold := newTestInventoryServer(t)
+ restored := cold.characters[1].missions[0]
+ layout, err := decodeMissionLayout(restored.layout)
+ if err != nil {
+ t.Fatal(err)
+ }
+ geometry := missionGeometryFixture(t)
+ if err := geometry.addMission(restored.world, layout); err != nil {
+ t.Fatal(err)
+ }
+ packet, err := missionPlayfieldPacket(&character{playfield: restored.world}, layout)
+ if err != nil {
+ t.Fatal(err)
+ }
+ var counter uint32
+ if err := cold.db.QueryRow("SELECT last_playfield_id FROM world WHERE id=1").Scan(&counter); err != nil {
+ t.Fatal(err)
+ }
+
+ if mission.world != 65536 || mission.world == mission.id || counter != 65536 || !reflect.DeepEqual(mission, restored) {
+ t.Fatal("assignment identity, generator or contract changed on restart", mission, restored, counter)
+ }
+ if layout.template != 331 || layout.width != 4 || layout.depth != 6 || layout.floorHeight != 10 || layout.ambient != [3]byte{100, 100, 100} ||
+ !reflect.DeepEqual(layout.rooms, []missionRoom{{template: 0, x: 1, z: 3, rotation: 2}, {template: 37, x: 1, z: 1}}) {
+ t.Fatal("persisted starter layout lost its reviewed room placements", layout)
+ }
+ if !bytes.Equal(packet[89:89+len(restored.layout)], restored.layout) || !geometry.physical(65536) {
+ t.Fatal("saved layout bytes differ from the native generator or cannot register")
+ }
+}
+
+func TestMissionWorldAllocationRollsBackAllWritesAndRetries(t *testing.T) {
+ for _, scenario := range []struct{ name, sql string }{
+ {"abort", "CREATE TRIGGER reject_world BEFORE UPDATE OF last_playfield_id ON world BEGIN SELECT RAISE(ABORT, 'world allocation'); END"},
+ {"ignored", "CREATE TRIGGER reject_world BEFORE UPDATE OF last_playfield_id ON world BEGIN SELECT RAISE(IGNORE); END"},
+ {"rewound", "CREATE TRIGGER reject_world AFTER UPDATE OF last_playfield_id ON world BEGIN UPDATE world SET last_playfield_id=65535 WHERE id=1; END"},
+ {"late rewrite", "CREATE TRIGGER reject_world BEFORE UPDATE OF last_item_id ON world BEGIN UPDATE world SET last_playfield_id=65535 WHERE id=1; END"},
+ {"commit", "CREATE TABLE pending_world (id INTEGER REFERENCES players(id) DEFERRABLE INITIALLY DEFERRED); CREATE TRIGGER reject_world AFTER UPDATE OF last_playfield_id ON world BEGIN INSERT INTO pending_world VALUES (999999); END"},
+ } {
+ t.Run(scenario.name, func(t *testing.T) {
+ world, output := newMissionOfferWorld(t)
+ t.Cleanup(func() { world.db.Close() })
+ client, player := world.clients[1], world.characters[1]
+ if err := world.handleMissionOffers(client, missionOffersRequest()); err != nil {
+ t.Fatal(err)
+ }
+ request := missionAcceptanceRequest(*client.missionOffer)
+ output.packets = nil
+ if _, err := world.db.Exec(scenario.sql); err != nil {
+ t.Fatal(err)
+ }
+
+ failure := world.handleMissionAcceptance(client, request)
+ cold := newTestInventoryServer(t)
+ var counter uint32
+ if err := cold.db.QueryRow("SELECT last_playfield_id FROM world WHERE id=1").Scan(&counter); err != nil {
+ t.Fatal(err)
+ }
+
+ if failure == nil || counter != 65535 || len(player.missions) != 0 || len(cold.characters[1].missions) != 0 || len(player.inventory.Items) != 1 ||
+ len(cold.characters[1].inventory.Items) != 1 || world.nextItem != 1 || client.missionOffer == nil || len(output.packets) != 0 {
+ t.Fatal("failed world allocation leaked state or consumed the offer", failure, counter)
+ }
+
+ if _, err := world.db.Exec("DROP TRIGGER reject_world"); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleMissionAcceptance(client, request); err != nil {
+ t.Fatal(err)
+ }
+
+ if len(player.missions) != 1 || player.missions[0].world != 65536 || len(output.packets) != 2 {
+ t.Fatal("retry did not reuse the rolled-back identity exactly once", player.missions)
+ }
+ })
+ }
+}
+
+func TestMissionReloadPreservesAnAlternateSavedLayout(t *testing.T) {
+ world, _ := newAcceptedMissionWorld(t)
+ t.Cleanup(func() { world.db.Close() })
+ layout := missionLayout{template: 331, width: 6, depth: 4, floorHeight: 10, ambient: [3]byte{11, 22, 33},
+ rooms: []missionRoom{{template: 0, x: 1, z: 1, rotation: 3}, {template: 37, x: 3, z: 1, rotation: 1}}}
+ blob, err := layout.blob()
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := world.db.Exec("UPDATE missions SET layout=? WHERE id=2", blob); err != nil {
+ t.Fatal(err)
+ }
+
+ cold := newTestInventoryServer(t)
+ mission := cold.characters[1].missions[0]
+ restored, err := decodeMissionLayout(mission.layout)
+
+ if err != nil || mission.world != 65536 || !bytes.Equal(mission.layout, blob) || !reflect.DeepEqual(restored, layout) {
+ t.Fatal("cold loading substituted the current starter layout for a saved assignment", restored, err)
+ }
+}
+
+func TestRetiredMissionWorldIdentityIsNeverReused(t *testing.T) {
+ world, _ := newAcceptedMissionWorld(t)
+ t.Cleanup(func() { world.db.Close() })
+ first := world.characters[1].missions[0]
+
+ if err := world.handleMissionRemoval(world.clients[1], missionRemovalPacket(1, first.id)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleMissionOffers(world.clients[1], missionOffersRequest()); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleMissionAcceptance(world.clients[1], missionAcceptanceRequest(*world.clients[1].missionOffer)); err != nil {
+ t.Fatal(err)
+ }
+ cold := newTestInventoryServer(t)
+ second := cold.characters[1].missions[0]
+
+ if first.world != 65536 || second.world != 65537 || second.id == first.id || !bytes.Equal(first.layout, second.layout) {
+ t.Fatal("retirement reused a world identity or changed the fixed generator", first, second)
+ }
+}
+
+func TestMissionWorldAllocatorHandlesFinalIdentityAndRejectsExhaustion(t *testing.T) {
+ world, _ := newMissionOfferWorld(t)
+ t.Cleanup(func() { world.db.Close() })
+ if _, err := world.db.Exec("UPDATE world SET last_playfield_id=4294967294 WHERE id=1"); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleMissionOffers(world.clients[1], missionOffersRequest()); err != nil {
+ t.Fatal(err)
+ }
+
+ if err := world.handleMissionAcceptance(world.clients[1], missionAcceptanceRequest(*world.clients[1].missionOffer)); err != nil {
+ t.Fatal(err)
+ }
+ last := world.characters[1].missions[0]
+ if err := world.handleMissionRemoval(world.clients[1], missionRemovalPacket(1, last.id)[20:]); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.handleMissionOffers(world.clients[1], missionOffersRequest()); err != nil {
+ t.Fatal(err)
+ }
+ failure := world.handleMissionAcceptance(world.clients[1], missionAcceptanceRequest(*world.clients[1].missionOffer))
+ cold := newTestInventoryServer(t)
+
+ if last.world != 4294967295 || failure == nil || len(cold.characters[1].missions) != 0 || len(cold.characters[1].inventory.Items) != 1 || world.clients[1].missionOffer == nil {
+ t.Fatal("exhausted allocator wrapped into public identities or lost the pending offer", last.world, failure)
+ }
+}
+
+func TestMissionAssignmentsIsolateConcurrentOwners(t *testing.T) {
+ world, _ := newMissionOfferWorld(t)
+ t.Cleanup(func() { world.db.Close() })
+ data := world.characters[1].userData()
+ data.ID, data.Name = 2, "Other owner"
+ other := data.character()
+ other.inventory.Credits = 5
+ world.characters[2] = other
+ world.clients[2] = &worldClient{id: 2, target: true, ready: true, conn: &combatTestConn{}}
+ if err := world.saveUser_locked(other); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.saveInventory_locked(other, other.inventory); err != nil {
+ t.Fatal(err)
+ }
+ requests := make(map[uint32][]byte)
+ for _, id := range []uint32{1, 2} {
+ request := missionOffersRequest()
+ binary.BigEndian.PutUint32(request[8:12], id)
+ if err := world.handleMissionOffers(world.clients[id], request); err != nil {
+ t.Fatal(err)
+ }
+ requests[id] = missionAcceptanceRequest(*world.clients[id].missionOffer)
+ binary.BigEndian.PutUint32(requests[id][8:12], id)
+ }
+ var pending sync.WaitGroup
+ failures := make(chan error, 2)
+
+ for _, id := range []uint32{1, 2} {
+ pending.Go(func() { failures <- world.handleMissionAcceptance(world.clients[id], requests[id]) })
+ }
+ pending.Wait()
+ close(failures)
+ cold := newTestInventoryServer(t)
+
+ for err := range failures {
+ if err != nil {
+ t.Fatal(err)
+ }
+ }
+ first, second := cold.characters[1].missions[0], cold.characters[2].missions[0]
+ if first.owner != 1 || second.owner != 2 || first.world == second.world || first.world < 65536 || second.world < 65536 ||
+ first.world+second.world != 131073 || first.id == second.id || !bytes.Equal(first.layout, second.layout) {
+ t.Fatal("concurrent owners shared an assignment, identity or key binding", first, second)
+ }
+}
+
+func TestMissionLoadRejectsCorruptGeneratorWithoutSubstitutingDefaults(t *testing.T) {
+ world, _ := newAcceptedMissionWorld(t)
+ t.Cleanup(func() { world.db.Close() })
+ if _, err := world.db.Exec("UPDATE missions SET layout=x'000300' WHERE id=2"); err != nil {
+ t.Fatal(err)
+ }
+ cold := &server{db: world.db, characters: map[uint32]*character{1: {id: 1}}}
+
+ err := cold.loadMissions()
+
+ if err == nil || len(cold.missionExpiry) != 0 || len(cold.characters[1].missions) != 0 {
+ t.Fatal("corrupt persisted layout silently generated a different mission", err)
+ }
+}
+
+func TestMissionLayoutBlobRoundTripsSignedFloorsAndMaximumDimensions(t *testing.T) {
+ layout := missionLayout{template: 341, width: 65535, depth: 32768, floorHeight: 1000,
+ ambient: [3]byte{0, 128, 255}, rooms: []missionRoom{{template: 10000, floor: -16, x: 32, z: 32, rotation: 3}, {floor: 16}}}
+
+ blob, err := layout.blob()
+ if err != nil {
+ t.Fatal(err)
+ }
+ restored, err := decodeMissionLayout(blob)
+
+ if err != nil || !reflect.DeepEqual(restored, layout) || len(blob) != 31 {
+ t.Fatal("native generator lost unsigned dimensions, signed floors or room order", restored, err)
+ }
+}
+
+func TestMissionLayoutBlobRejectsMalformedFramingAndPlacements(t *testing.T) {
+ for _, scenario := range []struct {
+ name string
+ change func([]byte) []byte
+ }{
+ {"short header", func(blob []byte) []byte { return blob[:18] }},
+ {"version", func(blob []byte) []byte { blob[1] = 2; return blob }},
+ {"zero rooms", func(blob []byte) []byte { binary.BigEndian.PutUint32(blob[15:19], 0); return blob[:19] }},
+ {"overflowing room count", func(blob []byte) []byte { binary.BigEndian.PutUint32(blob[15:19], 4294967295); return blob }},
+ {"short room", func(blob []byte) []byte { return blob[:len(blob)-1] }},
+ {"trailing byte", func(blob []byte) []byte { return append(blob, 0) }},
+ {"zero width", func(blob []byte) []byte { blob[2], blob[3] = 0, 0; return blob }},
+ {"low floor", func(blob []byte) []byte { blob[21] = 239; return blob }},
+ {"high floor", func(blob []byte) []byte { blob[21] = 17; return blob }},
+ {"x", func(blob []byte) []byte { blob[22] = 33; return blob }},
+ {"rotation", func(blob []byte) []byte { blob[24] = 4; return blob }},
+ } {
+ t.Run(scenario.name, func(t *testing.T) {
+ blob, err := starterMissionLayout().blob()
+ if err != nil {
+ t.Fatal(err)
+ }
+
+ _, err = decodeMissionLayout(scenario.change(blob))
+
+ if err == nil {
+ t.Fatal("invalid native generator was accepted")
+ }
+ })
+ }
+}
+
+func TestMissionWorldExpiryRemovesAssignmentButKeepsCounter(t *testing.T) {
+ world, _ := newAcceptedMissionWorld(t)
+ t.Cleanup(func() { world.db.Close() })
+
+ if err := world.expireMissions_locked(time.Now().Add(49*time.Hour), make(map[*worldClient][][]byte)); err != nil {
+ t.Fatal(err)
+ }
+ var count, counter uint32
+ if err := world.db.QueryRow("SELECT count(*) FROM missions").Scan(&count); err != nil {
+ t.Fatal(err)
+ }
+ if err := world.db.QueryRow("SELECT last_playfield_id FROM world WHERE id=1").Scan(&counter); err != nil {
+ t.Fatal(err)
+ }
+
+ if count != 0 || counter != 65536 || len(world.characters[1].missions) != 0 {
+ t.Fatal("expiry retained an assignment or rewound the world allocator", count, counter)
+ }
+}
+
+func TestMissionMovementMatchesNativeRaisedRoomMesh(t *testing.T) {
+ world := newMissionCollisionWorld(t)
+ player := world.characters[1]
+ // Published WASM replay297 of the saved generator: settled after jumping on this mesh.
+ position := [3]float32{15.027545, 2.160428, 21.828888}
+
+ player.placePosition(position)
+
+ if surfaceDistanceSquared(player.position, position) > .000004 || player.movement.falling {
+ t.Fatal("saved mission geometry differs from the native raised mesh contact", player.position)
+ }
+}
diff --git a/server/missions.go b/server/missions.go
@@ -16,19 +16,25 @@ type acceptedMission struct {
owner uint32
offer missionOffer
expiresAt time.Time
+ world uint32
+ layout []byte
}
-const missionColumns = "owner_id, booth_id, seed, difficulty, dimension_0, dimension_1, dimension_2, dimension_3, dimension_4, dimension_5, originator, description, playfield, entrance, position_x, position_y, position_z, objective_item, credits, experience, expires_at"
+const missionColumns = "owner_id, booth_id, seed, difficulty, dimension_0, dimension_1, dimension_2, dimension_3, dimension_4, dimension_5, originator, description, playfield, entrance, position_x, position_y, position_z, objective_item, credits, experience, expires_at, world_id, layout"
func (mission *acceptedMission) fields() []any {
return []any{&mission.owner, &mission.offer.booth, &mission.offer.seed, &mission.offer.difficulty,
&mission.offer.dimensions[0], &mission.offer.dimensions[1], &mission.offer.dimensions[2], &mission.offer.dimensions[3], &mission.offer.dimensions[4], &mission.offer.dimensions[5],
&mission.offer.originator, &mission.offer.definition.Description, &mission.offer.definition.Playfield, &mission.offer.definition.Entrance,
&mission.offer.definition.Position[0], &mission.offer.definition.Position[1], &mission.offer.definition.Position[2],
- &mission.offer.definition.ObjectiveItem, &mission.offer.definition.Credits, &mission.offer.definition.Experience, &mission.expiresAt}
+ &mission.offer.definition.ObjectiveItem, &mission.offer.definition.Credits, &mission.offer.definition.Experience, &mission.expiresAt, &mission.world, &mission.layout}
}
func insertMission(tx *sql.Tx, mission *acceptedMission) error {
+ // Original public resource identities fit in 16 bits; private worlds use a separate counter.
+ if err := tx.QueryRow("UPDATE world SET last_playfield_id=last_playfield_id+1 WHERE id=1 AND last_playfield_id<4294967295 RETURNING last_playfield_id").Scan(&mission.world); err != nil {
+ return fmt.Errorf("allocate mission world: %w", err)
+ }
// The accepted contract and its first key commit with inventory ownership.
var saved uint32
query := "INSERT INTO missions (id, " + missionColumns + ") VALUES (?" + strings.Repeat(", ?", len(mission.fields())) + ") RETURNING id"
@@ -52,6 +58,9 @@ func (server *server) loadMissions() error {
if err := rows.Scan(append([]any{&mission.id}, mission.fields()...)...); err != nil {
return err
}
+ if _, err := decodeMissionLayout(mission.layout); err != nil {
+ return fmt.Errorf("mission %d layout: %w", mission.id, err)
+ }
player := server.characters[mission.owner]
player.missions = append(player.missions, mission)
server.missionExpiry = append(server.missionExpiry, mission)
@@ -107,6 +116,11 @@ func (server *server) handleMissionAcceptance(client *worldClient, body []byte)
inventory.LastID = key.ID
inventory.Items = append(slices.Clone(inventory.Items), key)
mission := acceptedMission{id: key.ID, owner: player.id, offer: offer, expiresAt: time.Now().UTC().Add(48 * time.Hour)}
+ var err error
+ mission.layout, err = starterMissionLayout().blob()
+ if err != nil {
+ return err
+ }
store, err := server.itemStore_locked(player, inventory)
if err != nil {
return err
diff --git a/server/missions_test.go b/server/missions_test.go
@@ -177,8 +177,12 @@ func TestMissionAcceptanceFailureRollsBackKeyAndContractThenRetries(t *testing.T
err := world.handleMissionAcceptance(client, request)
cold := newTestInventoryServer(t).characters[1]
+ var worldCounter uint32
+ if err := world.db.QueryRow("SELECT last_playfield_id FROM world WHERE id=1").Scan(&worldCounter); err != nil {
+ t.Fatal(err)
+ }
- if err == nil || len(output.packets) != 0 || len(player.missions) != 0 || len(cold.missions) != 0 || len(cold.inventory.Items) != 1 || len(player.inventory.Items) != 1 ||
+ if err == nil || worldCounter != 65535 || len(output.packets) != 0 || len(player.missions) != 0 || len(cold.missions) != 0 || len(cold.inventory.Items) != 1 || len(player.inventory.Items) != 1 ||
world.nextItem != 1 || client.missionOffer == nil || player.inventory.Credits != 4 || cold.inventory.Credits != 4 {
t.Fatal("failed acceptance published state, consumed offer or lost committed fee", err)
}
@@ -270,7 +274,7 @@ func TestAcceptedMissionSurvivesEditsAndColdOwnerOnlyReplay(t *testing.T) {
owner := captureMissionReplay(t, cold, 1)
other := captureMissionReplay(t, cold, 2)
- if len(world.characters[1].missions) != 1 || world.characters[1].missions[0] != original || len(cold.characters[1].missions) != 1 || cold.characters[1].missions[0] != original ||
+ if len(world.characters[1].missions) != 1 || !reflect.DeepEqual(world.characters[1].missions[0], original) || len(cold.characters[1].missions) != 1 || !reflect.DeepEqual(cold.characters[1].missions[0], original) ||
len(owner) != 1 || len(other) != 0 || len(cold.characters[2].missions) != 0 || !bytes.Contains(owner[0], []byte("Recover the Blue Book of Secrets\n")) || bytes.Contains(owner[0], []byte("changed after generation")) {
t.Fatal("edit/checkpoint/restart changed the accepted contract or leaked its journal")
}
diff --git a/server/world.sql b/server/world.sql
@@ -3,6 +3,7 @@ CREATE TABLE IF NOT EXISTS world (
last_item_id INTEGER NOT NULL DEFAULT 0,
last_character_id INTEGER NOT NULL DEFAULT 0,
last_npc_id INTEGER NOT NULL DEFAULT 1000000,
+ last_playfield_id INTEGER NOT NULL DEFAULT 65535 CHECK (last_playfield_id BETWEEN 65535 AND 4294967295),
game_seconds REAL NOT NULL DEFAULT 48600,
clock_started TEXT NOT NULL,
npcs_initialized INTEGER NOT NULL DEFAULT 0
@@ -230,7 +231,9 @@ CREATE TABLE IF NOT EXISTS missions (
objective_item INTEGER NOT NULL,
credits INTEGER NOT NULL,
experience INTEGER NOT NULL,
- expires_at DATETIME NOT NULL
+ expires_at DATETIME NOT NULL,
+ world_id INTEGER NOT NULL UNIQUE CHECK (world_id BETWEEN 65536 AND 4294967295),
+ layout BLOB NOT NULL
);
CREATE TABLE IF NOT EXISTS mission_keys (
item_id INTEGER PRIMARY KEY REFERENCES items(id) ON DELETE CASCADE,