diff --git a/docs/adr/0100-primitive-lives-and-persistent-control.md b/docs/adr/0100-primitive-lives-and-persistent-control.md index 43732a3..7746f66 100644 --- a/docs/adr/0100-primitive-lives-and-persistent-control.md +++ b/docs/adr/0100-primitive-lives-and-persistent-control.md @@ -211,45 +211,28 @@ admission and retry behavior, not end-to-end recoverability or deployable gamepl Death, respawn, offline timers, biological tick integration and life transfer are outside 11.2 and remain governed by later gates. -## 11.2d contract gap: durable request outcomes and moved control +## 11.2d request outcomes and control movement -The first v5 request/receipt/outcome/query codec is implemented, but server -execution must remain disabled until the durable request contract is closed. -Inspection of schema v15/v16 and the C++ read adapter found two gaps: +Schema v17 closes the request contract without transferring a pending biological +operation between regions. A conflicting new request gets a durable +`existing_life` refusal row, so exact retry and query return the same final +result. The authenticated current controller can query by world/account/request +independently of the reservation's region; results include the owner and, after +publication, the immutable born tick and commit receipt. Missing rows resolve as +unknown, while a reserved row remains pending and is never called a birth. -- `reserve_primitive_life` raises `EVL16` when the account already has another - reserved or living life. It inserts no row for the incoming request, so that - request has no durable final outcome for exact retry or query. The current v5 - result vocabulary cannot express this refusal. -- `load_primitive_lives` reads successful bindings for one region. There is no - authenticated world/account/request query that resolves a refusal or a - pending reservation across regions. A repeated reservation can identify the - original owner region, but the runtime has no completed routing/recovery - contract for it. -- A pending reservation is pinned to its original region. If account control - moves before publication, admission in the new region returns that owner - region, while publication still requires current control. Without an explicit - ownership transition, the request can remain stranded; allowing the new - region to publish independently would risk two bodies. +When account control changes region or region epoch, the same fenced control +transaction marks unpublished reservations in the old region cancelled. +Published bindings are untouched. The cancelled request remains immutable and a +new request is required to try again. This avoids cross-region transfer of +speculative body state and prevents the old reservation becoming publishable +under a new controller. V5 now gives `existing_life` and `cancelled` durable +result values distinct from query-only `pending` and `unknown`. -These are contract blockers for 11.2d, not permission to infer new game rules. -Before implementing session execution, settle and record a schema/API contract -that gives every accepted new-life request a durable, immutable queryable -outcome, including an existing-life refusal, and resolves pending ownership -across control movement. One candidate is a world-scoped operation record keyed -by `(world, account, request_id)`, with durable pending/final state, owner region, -and the successful commit binding/sequence where applicable. Query must be -available to the authenticated current controller independently of its region. -An ownership move must either atomically transfer the pending operation under -the relevant fencing checks, or durably finalize it and require a new request; -two regions must never be able to publish it. Extend the versioned result -vocabulary for any accepted durable refusals, keeping query-only `pending` and -`unknown` distinct from final outcomes. - -The candidate above is a recommendation for review, not an accepted game rule. -Add PostgreSQL concurrency and process-crash evidence for exact retries, -cross-region queries, control movement during reservation/publication, and -immutable refusal results before enabling the v5 handler or primitive host. +Migration v17, its typed query adapter and PostgreSQL tests implement this +contract. Host/session execution, concurrent-process crash qualification and +readiness integration remain outstanding; v5 stays refused by the running +server until those gates pass. ## 11.2c-2d: Object-store publication and recovery adapter diff --git a/docs/engineering/M11_2_DELIVERY_PLAN.md b/docs/engineering/M11_2_DELIVERY_PLAN.md index 783ff4a..3bd92ce 100644 --- a/docs/engineering/M11_2_DELIVERY_PLAN.md +++ b/docs/engineering/M11_2_DELIVERY_PLAN.md @@ -90,13 +90,18 @@ Local checks do not close ADR-0097's reference-worker qualification. handling are implemented. Network and QUIC suites pass; targeted manual compile and link were needed because the normal Ninja build invocation idles. Host admission and durable execution are a separate slice. -- 11.2d contract review: stopped before host/session execution after tracing - reservation, publication and query paths. ADR-0100 records the missing durable - outcome for an existing-life refusal, lack of region-independent request query, - and unresolved pending-reservation behavior when account control moves. Resolve - and validate this request/ownership contract before expanding implementation. -- Remaining 11.2d after contract closure: primitive-capable region host, server - admission/execution, crash-boundary qualification and readiness integration. - The generic two-profile host still cannot serve profile 3. +- 11.2d-2 implementation: schema v17 records an immutable `existing_life` + refusal for each conflicting request, offers an authenticated world/account/ + request query, and cancels unpublished reservations atomically when control + changes region/epoch. Published bindings remain unchanged; v5 now distinguishes + `existing_life` and `cancelled` from query-only `pending`/`unknown`. Typed adapter, + migration, codec and PostgreSQL tests/docs are updated. Validation is pending: + the affected C++ files were compiled directly with MSVC and the updated network + and QUIC suites passed (2/2 and 5/5). PostgreSQL 18.6 is unavailable here, so + migration and adapter integration tests remain unrun. Host work remains paused + until database validation passes. +- Remaining 11.2d after 11.2d-2 validation: primitive-capable region host, + server admission/execution, crash-boundary qualification and readiness + integration. The generic two-profile host still cannot serve profile 3. No deployed world has been provisioned or changed by this work. diff --git a/docs/engineering/VALIDATION.md b/docs/engineering/VALIDATION.md index 0c3f675..2a73f98 100644 --- a/docs/engineering/VALIDATION.md +++ b/docs/engineering/VALIDATION.md @@ -5657,3 +5657,25 @@ The operator's live-region smoke test did pass using the prebuilt v4 `evo-session-probe`, `C:\Dev\tokens\m10-grants.bin` grant 0 and the supplied dev CA: `void.aeternalisgames.com:7400` returned Welcome, exit 0. This confirms existing v4 connectivity only; it does not execute or validate v5 or primitive-life handling. + +## 2026-10-10 — M11.2d-2 durable primitive-life outcomes (unverified) + +Implemented schema v17 durable `existing_life` outcomes, current-controller +world/account/request lookup, and atomic cancellation of unpublished reservations +when control changes region or region epoch. Updated v5 outcomes and typed adapter +tests. Direct clang-format 19.1.5 dry-run on all changed C++ files and `git diff +--check` passed. + +The network preset configured successfully, but its check invocation and a direct +`evo-network-tests` Ninja target remained silent without completion for more than +35 seconds and were interrupted, matching the previously recorded idle Ninja +condition. Direct MSVC Release/NDEBUG compilation succeeded for the modified +network protocol/test units, persistence adapter and its changed PostgreSQL test +units. The protocol library and network test executable were rebuilt from those +objects; `ctest --preset network` passed (2/2) and `ctest --preset quic` passed +(5/5). + +`psql` and PostgreSQL 18.6 are unavailable in this environment; Docker's Linux +engine is also not running. Schema v17 and its PostgreSQL integration, migration, +upgrade and privilege tests have not run. Do not continue to 11.2d host/session +execution until those database checks pass. diff --git a/include/evo/network/session_protocol.hpp b/include/evo/network/session_protocol.hpp index c45910b..53e6792 100644 --- a/include/evo/network/session_protocol.hpp +++ b/include/evo/network/session_protocol.hpp @@ -173,10 +173,12 @@ struct ActionQuery { }; enum class PrimitiveLifeResult : std::uint8_t { born = 1, - insufficient_funding, - no_placement, - pending, - unknown + insufficient_funding = 2, + no_placement = 3, + existing_life = 4, + cancelled = 5, + pending = 6, + unknown = 7 }; struct PrimitiveLifeRequest { std::uint64_t session{}, epoch{}, request_id{}; diff --git a/include/evo/persistence/life_reservation_store.hpp b/include/evo/persistence/life_reservation_store.hpp index 19f6960..efd79a5 100644 --- a/include/evo/persistence/life_reservation_store.hpp +++ b/include/evo/persistence/life_reservation_store.hpp @@ -26,7 +26,8 @@ enum class LifeRefusal : std::uint8_t { none = 0, // Reserved only; NOT successful spawn. insufficient_funding = 1, no_placement = 2, - cancelled = 3 + cancelled = 3, + existing_life = 4 }; struct LifeReservation { std::uint64_t identity{}, region{}; @@ -40,6 +41,11 @@ struct PrimitiveLifeBinding { std::uint64_t commit_sequence{}; friend bool operator==(const PrimitiveLifeBinding&, const PrimitiveLifeBinding&) = default; }; +struct PrimitiveLifeOutcome { + LifeReservation reservation; + std::optional published; + friend bool operator==(const PrimitiveLifeOutcome&, const PrimitiveLifeOutcome&) = default; +}; // Exact retry returns the original identity/owning region/refusal, even after // account control moves. The result grants no authority in the returned region. // request_id is in the new-life namespace, separate from M10 probe action IDs. @@ -57,4 +63,10 @@ reject_primitive_life(Postgres& db, RegionKey key, const LeaseGrant& lease, cons // are intentionally absent and must be reacquired after recovery. [[nodiscard]] std::expected, LifeReservationFailure> load_primitive_lives(Postgres& db, RegionKey key, std::chrono::milliseconds timeout); +// Authenticated world/account/request lookup. A missing value is unknown; a +// present pending reservation is still not a published life. +[[nodiscard]] std::expected, LifeReservationFailure> +query_primitive_life(Postgres& db, RegionKey key, const LeaseGrant& lease, const Uuid& account, + std::uint64_t generation, std::uint64_t request_id, + std::chrono::milliseconds timeout); } // namespace evo::persistence diff --git a/migrations/0017_life_request_outcomes.sql b/migrations/0017_life_request_outcomes.sql new file mode 100644 index 0000000..2105ede --- /dev/null +++ b/migrations/0017_life_request_outcomes.sql @@ -0,0 +1,99 @@ +-- M11.2d contract closure, ADR-0100. Existing durable request rows become +-- queryable outcomes for conflicts, and reservations cannot remain pending at +-- an old owner after account control moves. +ALTER TABLE evolution.life_reservations DROP CONSTRAINT life_reservations_rejection_check; +ALTER TABLE evolution.life_reservations ADD CONSTRAINT life_reservations_rejection_check + CHECK (rejection BETWEEN 0 AND 4); +-- 4 is an immutable refusal: another life is already reserved or published. + +CREATE FUNCTION evolution.cancel_moved_primitive_reservations() RETURNS trigger +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$ +BEGIN + IF OLD.region_id IS NOT NULL AND + (OLD.region_id IS DISTINCT FROM NEW.region_id OR + OLD.region_epoch IS DISTINCT FROM NEW.region_epoch) THEN + UPDATE evolution.life_reservations r SET rejection = 3 + WHERE r.world_id = OLD.world_id AND r.account_id = OLD.account_id + AND r.region_id = OLD.region_id AND r.rejection = 0 + AND NOT EXISTS (SELECT 1 FROM evolution.primitive_life_bindings b + WHERE b.world_id = r.world_id AND b.account_id = r.account_id + AND b.request_id = r.request_id); + END IF; + RETURN NEW; +END $$; +CREATE TRIGGER cancel_moved_primitive_reservations + AFTER UPDATE OF region_id, region_epoch ON evolution.account_controls + FOR EACH ROW EXECUTE FUNCTION evolution.cancel_moved_primitive_reservations(); + +-- Exact retry is checked before conflict detection. A conflicting request gets +-- its own durable refusal row and allocated identity (a permitted gap), so its +-- result survives reconnect and remains distinct from the older request. +CREATE OR REPLACE FUNCTION evolution.reserve_primitive_life(p_world evolution.u64, + p_region evolution.u64, p_holder uuid, p_epoch evolution.u64, p_account uuid, + p_generation evolution.u64, p_request evolution.u64, p_rules integer) +RETURNS TABLE (life_identity evolution.u64, life_region evolution.u64, rejection smallint) +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$ +DECLARE r evolution.life_reservations%ROWTYPE; allocated numeric; +BEGIN + IF p_request IS NULL OR p_request = 0 OR p_rules IS DISTINCT FROM 1 THEN + RAISE EXCEPTION 'invalid life request' USING ERRCODE = '22023'; + END IF; + PERFORM evolution.check_life_control(p_world, p_region, p_holder, p_epoch, p_account, p_generation); + SELECT * INTO r FROM evolution.life_reservations x + WHERE x.world_id = p_world AND x.account_id = p_account AND x.request_id = p_request; + IF FOUND THEN + RETURN QUERY SELECT r.identity, r.region_id, r.rejection; + RETURN; + END IF; + SELECT a.next_identity INTO allocated FROM evolution.life_allocators a + WHERE a.world_id = p_world FOR UPDATE; + IF NOT FOUND THEN + RAISE EXCEPTION 'life allocator not provisioned' USING ERRCODE = 'EVL04'; + END IF; + IF allocated = 18446744073709551615 THEN + RAISE EXCEPTION 'life identities exhausted' USING ERRCODE = 'EVL05'; + END IF; + PERFORM evolution.check_life_control(p_world, p_region, p_holder, p_epoch, p_account, p_generation); + IF EXISTS (SELECT 1 FROM evolution.life_reservations x + WHERE x.world_id = p_world AND x.account_id = p_account AND x.rejection = 0) THEN + UPDATE evolution.life_allocators SET next_identity = allocated + 1 WHERE world_id = p_world; + INSERT INTO evolution.life_reservations(world_id, account_id, request_id, identity, + region_id, rules, rejection) + VALUES (p_world, p_account, p_request, allocated, p_region, p_rules, 4); + RETURN QUERY SELECT allocated::evolution.u64, p_region, 4::smallint; + RETURN; + END IF; + UPDATE evolution.life_allocators SET next_identity = allocated + 1 WHERE world_id = p_world; + INSERT INTO evolution.life_reservations(world_id, account_id, request_id, identity, region_id, rules) + VALUES (p_world, p_account, p_request, allocated, p_region, p_rules); + RETURN QUERY SELECT allocated::evolution.u64, p_region, 0::smallint; +END $$; + +-- The caller must hold current account control in a live region session. The +-- row is world/account/request scoped, not limited to the reservation's region. +CREATE FUNCTION evolution.query_primitive_life(p_world evolution.u64, p_region evolution.u64, + p_holder uuid, p_epoch evolution.u64, p_account uuid, p_generation evolution.u64, + p_request evolution.u64) +RETURNS TABLE (life_identity evolution.u64, life_region evolution.u64, rejection smallint, + born evolution.u64, commit_id uuid, commit_sequence evolution.u64) +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$ +BEGIN + IF p_request IS NULL OR p_request = 0 THEN + RAISE EXCEPTION 'invalid life request' USING ERRCODE = '22023'; + END IF; + PERFORM evolution.check_life_control(p_world, p_region, p_holder, p_epoch, p_account, p_generation); + RETURN QUERY + SELECT r.identity, r.region_id, r.rejection, b.born, b.commit_id, c.commit_sequence + FROM evolution.life_reservations r + LEFT JOIN evolution.primitive_life_bindings b USING(world_id,account_id,request_id) + LEFT JOIN evolution.region_commits c ON c.commit_id=b.commit_id + WHERE r.world_id=p_world AND r.account_id=p_account AND r.request_id=p_request; +END $$; + +REVOKE ALL ON FUNCTION evolution.cancel_moved_primitive_reservations(), + evolution.query_primitive_life(evolution.u64,evolution.u64,uuid,evolution.u64,uuid,evolution.u64,evolution.u64) + FROM PUBLIC; +GRANT EXECUTE ON FUNCTION + evolution.query_primitive_life(evolution.u64,evolution.u64,uuid,evolution.u64,uuid,evolution.u64,evolution.u64) + TO :"runtime_role"; +INSERT INTO evolution.schema_migrations(version,sha256) VALUES (17, :'migration_sha_17'); diff --git a/migrations/apply.sql b/migrations/apply.sql index e17acc7..e23c3c5 100644 --- a/migrations/apply.sql +++ b/migrations/apply.sql @@ -89,28 +89,36 @@ SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname='evolution') || ',9:' || :'migration_sha_9' || ',10:' || :'migration_sha_10' || ',11:' || :'migration_sha_11' || ',12:' || :'migration_sha_12' || ',13:' || :'migration_sha_13' || ',14:' || :'migration_sha_14' - || ',15:' || :'migration_sha_15' || ',16:' || :'migration_sha_16' AS at_v16 \gset - \if :at_v16 + || ',15:' || :'migration_sha_15' || ',16:' || :'migration_sha_16' AS at_v16, + :'history' = '1:' || :'migration_sha' || ',2:' || :'migration_sha_2' || ',3:' || :'migration_sha_3' || ',4:' || :'migration_sha_4' || ',5:' || :'migration_sha_5' || ',6:' || :'migration_sha_6' || ',7:' || :'migration_sha_7' || ',8:' || :'migration_sha_8' || ',9:' || :'migration_sha_9' || ',10:' || :'migration_sha_10' || ',11:' || :'migration_sha_11' || ',12:' || :'migration_sha_12' || ',13:' || :'migration_sha_13' || ',14:' || :'migration_sha_14' || ',15:' || :'migration_sha_15' || ',16:' || :'migration_sha_16' || ',17:' || :'migration_sha_17' AS at_v17 \gset + \if :at_v17 + \elif :at_v16 + \ir 0017_life_request_outcomes.sql \elif :at_v15 \ir 0016_primitive_publication.sql + \ir 0017_life_request_outcomes.sql \elif :at_v14 \ir 0015_life_reservations.sql \ir 0016_primitive_publication.sql + \ir 0017_life_request_outcomes.sql \elif :at_v13 \ir 0014_probe_overdue.sql \ir 0015_life_reservations.sql \ir 0016_primitive_publication.sql + \ir 0017_life_request_outcomes.sql \elif :at_v12 \ir 0013_probe_incoming.sql \ir 0014_probe_overdue.sql \ir 0015_life_reservations.sql \ir 0016_primitive_publication.sql + \ir 0017_life_request_outcomes.sql \elif :at_v11 \ir 0012_probe_handoff.sql \ir 0013_probe_incoming.sql \ir 0014_probe_overdue.sql \ir 0015_life_reservations.sql \ir 0016_primitive_publication.sql + \ir 0017_life_request_outcomes.sql \elif :at_v10 \ir 0011_region_actions.sql \ir 0012_probe_handoff.sql @@ -118,6 +126,7 @@ SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname='evolution') \ir 0014_probe_overdue.sql \ir 0015_life_reservations.sql \ir 0016_primitive_publication.sql + \ir 0017_life_request_outcomes.sql \elif :at_v9 \ir 0010_account_control.sql \ir 0011_region_actions.sql @@ -126,6 +135,7 @@ SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname='evolution') \ir 0014_probe_overdue.sql \ir 0015_life_reservations.sql \ir 0016_primitive_publication.sql + \ir 0017_life_request_outcomes.sql \elif :at_v8 \ir 0009_serialized_authority.sql \ir 0010_account_control.sql @@ -135,6 +145,7 @@ SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname='evolution') \ir 0014_probe_overdue.sql \ir 0015_life_reservations.sql \ir 0016_primitive_publication.sql + \ir 0017_life_request_outcomes.sql \elif :at_v7 \ir 0008_upgrade_barrier.sql \ir 0009_serialized_authority.sql @@ -145,6 +156,7 @@ SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname='evolution') \ir 0014_probe_overdue.sql \ir 0015_life_reservations.sql \ir 0016_primitive_publication.sql + \ir 0017_life_request_outcomes.sql \elif :at_v6 \ir 0007_region_clones.sql \ir 0008_upgrade_barrier.sql @@ -156,6 +168,7 @@ SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname='evolution') \ir 0014_probe_overdue.sql \ir 0015_life_reservations.sql \ir 0016_primitive_publication.sql + \ir 0017_life_request_outcomes.sql \elif :at_v5 \ir 0006_commit_lookup.sql \ir 0007_region_clones.sql @@ -168,6 +181,7 @@ SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname='evolution') \ir 0014_probe_overdue.sql \ir 0015_life_reservations.sql \ir 0016_primitive_publication.sql + \ir 0017_life_request_outcomes.sql \elif :at_v4 \ir pre_v5_guard.sql \ir 0005_batch_decisions.sql @@ -182,6 +196,7 @@ SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname='evolution') \ir 0014_probe_overdue.sql \ir 0015_life_reservations.sql \ir 0016_primitive_publication.sql + \ir 0017_life_request_outcomes.sql \elif :at_v3 \ir 0004_lineage_profile.sql \ir pre_v5_guard.sql @@ -197,6 +212,7 @@ SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname='evolution') \ir 0014_probe_overdue.sql \ir 0015_life_reservations.sql \ir 0016_primitive_publication.sql + \ir 0017_life_request_outcomes.sql \elif :at_v2 \ir 0003_region_checkpoints.sql \ir 0004_lineage_profile.sql @@ -213,6 +229,7 @@ SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname='evolution') \ir 0014_probe_overdue.sql \ir 0015_life_reservations.sql \ir 0016_primitive_publication.sql + \ir 0017_life_request_outcomes.sql \elif :at_v1 \ir 0002_region_fencing.sql \ir 0003_region_checkpoints.sql @@ -230,6 +247,7 @@ SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname='evolution') \ir 0014_probe_overdue.sql \ir 0015_life_reservations.sql \ir 0016_primitive_publication.sql + \ir 0017_life_request_outcomes.sql \else \echo 'Unknown or changed migration history' DO $$ BEGIN RAISE EXCEPTION 'unknown or changed migration history'; END $$; @@ -252,6 +270,7 @@ SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname='evolution') \ir 0014_probe_overdue.sql \ir 0015_life_reservations.sql \ir 0016_primitive_publication.sql + \ir 0017_life_request_outcomes.sql \endif -- Effective-privilege audit on every run, including no-ops (ADR-0060). Attributes -- alone are insufficient: predefined roles such as pg_write_all_data, PUBLIC @@ -274,6 +293,7 @@ BEGIN ), fenced(oid) AS (VALUES ('evolution.publish_primitive_checkpoint(bytea,bytea)'::regprocedure::oid), ('evolution.load_primitive_lives(evolution.u64,evolution.u64)'::regprocedure::oid), + ('evolution.query_primitive_life(evolution.u64,evolution.u64,uuid,evolution.u64,uuid,evolution.u64,evolution.u64)'::regprocedure::oid), ('evolution.reserve_primitive_life(evolution.u64,evolution.u64,uuid,evolution.u64,uuid,evolution.u64,evolution.u64,integer)'::regprocedure::oid), ('evolution.reject_primitive_life(evolution.u64,evolution.u64,uuid,evolution.u64,uuid,evolution.u64,evolution.u64,smallint)'::regprocedure::oid), ('evolution.acquire_region_lease(evolution.u64,evolution.u64,integer)'::regprocedure::oid), diff --git a/schemas/life-reservations-v1.md b/schemas/life-reservations-v1.md index 5549477..b6ef4e5 100644 --- a/schemas/life-reservations-v1.md +++ b/schemas/life-reservations-v1.md @@ -24,10 +24,13 @@ resolve a life request by assumption. | 1 | Insufficient funding | | 2 | No placement/capacity | | 3 | Cancelled | +| 4 | Existing life already reserved or published | One unrejected reservation per world/account is enforced by a partial unique -index. Rejected rows remain permanently queryable by retry. A different request -may follow rejection and gets a new identity. There is no deletion API. +index. Rejected rows remain permanently queryable by retry. A conflicting new +request now gets its own durable `existing_life` refusal row and consumes an +identity (gaps are permitted). A different request may follow a final rejection +and gets a new identity. There is no deletion API. `reserve_primitive_life` requires the exact region lease and current durable account-control generation. Exact retry returns the original identity, owner and @@ -47,9 +50,14 @@ tables or internal control helper. Migration's effective privilege audit covers these additions, including no-op migration runs. A takeover may inspect its old reservation before its session wait expires, but -gets no biological control from it. The owner region stays unchanged. Session -admission must still honor ADR-0091's takeover wait before originating gameplay. -Final spawn success, checkpoint publication and reconciliation are 11.2c-2/d. +gets no biological control from it. When durable account control changes region +or region epoch, the control transaction atomically marks any unpublished old +reservation cancelled. A published life binding is never changed. Retrying the +cancelled request returns that immutable result; starting again requires a new +request. Session admission must still honor ADR-0091's takeover wait before +originating gameplay. `query_primitive_life` resolves the world/account/request +record for the authenticated current controller, independent of reservation +region, including final refusals and published commit identity/sequence. Validation: `tools/ci/postgres-check.sh --life-reservations-only` starts a fresh local socket-only PostgreSQL test cluster. The full postgres-check also executes diff --git a/schemas/network/session-v5.md b/schemas/network/session-v5.md index c0f9364..2eca0a2 100644 --- a/schemas/network/session-v5.md +++ b/schemas/network/session-v5.md @@ -16,6 +16,9 @@ are separate implementation gates. | 21 PrimitiveLifeQuery | client → server, reliable stream | request_id u64 | 8 | Result values: 1 born (identity and commit sequence must both be nonzero), 2 insufficient -funding, 3 no placement, 4 pending (query only), 5 unknown (query only). Non-born results -carry zero identity and commit sequence. Request IDs are a separate namespace from M10 +funding, 3 no placement, 4 existing life, 5 cancelled, 6 pending (query only), 7 unknown +(query only). Non-born results carry zero identity and commit sequence. A region-control +move durably cancels an unpublished reservation; retrying that request returns cancelled +and a new request is required. `existing life` is recorded for the conflicting request, +so its exact retry/query remains stable. Request IDs are a separate namespace from M10 action IDs. Receipt reports admission only; it does not claim that a life was durably born. diff --git a/src/persistence/region_lease_store.cpp b/src/persistence/region_lease_store.cpp index e99300f..792f7c8 100644 --- a/src/persistence/region_lease_store.cpp +++ b/src/persistence/region_lease_store.cpp @@ -626,7 +626,7 @@ reserve_primitive_life(Postgres& db, RegionKey key, const LeaseGrant& lease, con const auto identity = parse_integer((*rows)[0][0]); const auto region = parse_integer((*rows)[0][1]); const auto refusal = parse_integer((*rows)[0][2]); - if (!identity || *identity == 0 || !region || *region == 0 || !refusal || *refusal > 3) + if (!identity || *identity == 0 || !region || *region == 0 || !refusal || *refusal > 4) return std::unexpected{unknown}; return LifeReservation{*identity, *region, static_cast(*refusal)}; } @@ -690,6 +690,42 @@ load_primitive_lives(Postgres& db, RegionKey key, milliseconds timeout) { return out; } +std::expected, LifeReservationFailure> +query_primitive_life(Postgres& db, RegionKey key, const LeaseGrant& lease, const Uuid& account, + std::uint64_t generation, std::uint64_t request_id, milliseconds timeout) { + const auto base = control_parameters(key, lease, account, generation); + const std::array p{ + base[0], base[1], base[2], base[3], base[4], base[5], std::to_string(request_id)}; + auto rows = db.query("SELECT * FROM evolution.query_primitive_life($1::evolution.u64, " + "$2::evolution.u64, $3::uuid, $4::evolution.u64, $5::uuid, " + "$6::evolution.u64, $7::evolution.u64)", + p, timeout); + if (!rows) + return std::unexpected{life_failure(rows.error())}; + if (rows->empty()) + return std::optional{}; + const auto& row = (*rows)[0]; + if (rows->size() != 1 || row.size() != 6) + return std::unexpected{LifeReservationFailure{LifeReservationError::store, {}}}; + const auto identity = parse_integer(row[0]); + const auto region = parse_integer(row[1]); + const auto refusal = parse_integer(row[2]); + if (!identity || *identity == 0 || !region || *region == 0 || !refusal || *refusal > 4) + return std::unexpected{LifeReservationFailure{LifeReservationError::store, {}}}; + PrimitiveLifeOutcome out{ + LifeReservation{*identity, *region, static_cast(*refusal)}, std::nullopt}; + if (row[3] || row[4] || row[5]) { + const auto born = parse_integer(row[3]); + const auto commit = parse_uuid(row[4]); + const auto sequence = parse_integer(row[5]); + if (!born || *born == 0 || !commit || !sequence || *sequence == 0) + return std::unexpected{LifeReservationFailure{LifeReservationError::store, {}}}; + out.published = + PrimitiveLifeBinding{account, request_id, *identity, *born, *commit, *sequence}; + } + return std::optional{std::move(out)}; +} + // Schema v12 probe records and handoff (ADR-0096). Shares this file's parsing rules. namespace { ProbeStoreFailure probe_failure(const PgFailure& f) { diff --git a/tests/life_reservation_store_tests.cpp b/tests/life_reservation_store_tests.cpp index a64a5ba..0af6430 100644 --- a/tests/life_reservation_store_tests.cpp +++ b/tests/life_reservation_store_tests.cpp @@ -1,4 +1,4 @@ -// Real PostgreSQL schema v15 adapter checks, isolated world 9752. +// Real PostgreSQL schema v17 adapter checks, isolated world 9752. #include "evo/persistence/account_control_store.hpp" #include "evo/persistence/life_reservation_store.hpp" #include "evo/persistence/region_lease_store.hpp" @@ -59,6 +59,8 @@ void run_life_reservation_store_tests() { return reserve_primitive_life(*db, a, *lease_a, alice, control->generation, action, rules, 5s); }; + const auto absent = query_primitive_life(*db, a, *lease_a, alice, control->generation, 77, 5s); + CHECK(absent && !*absent); CHECK(failed(reserve(request), LifeReservationError::not_available)); CHECK(admin->query("INSERT INTO evolution.life_allocators VALUES " "(9752,9223372036854775808)", @@ -72,7 +74,15 @@ void run_life_reservation_store_tests() { first->refusal == LifeRefusal::none); db = connect_as(env("EVO_PG_RUNTIME_USER")); CHECK(reserve(request) == *first); - CHECK(failed(reserve(2), LifeReservationError::existing_life)); + const auto conflict = reserve(2); + CHECK(conflict && conflict->refusal == LifeRefusal::existing_life && conflict->region == 1 && + conflict->identity == first->identity + 1); + CHECK(reserve(2) == *conflict); + auto conflict_result = + query_primitive_life(*db, a, *lease_a, alice, control->generation, 2, 5s); + CHECK(conflict_result && *conflict_result && + (**conflict_result).reservation.refusal == LifeRefusal::existing_life && + !(**conflict_result).published); CHECK(failed(reserve_primitive_life(*db, a, *lease_a, alice, 2, request, 1, 5s), LifeReservationError::fenced)); CHECK(failed(reject_primitive_life(*db, a, *lease_a, alice, 1, request, LifeRefusal::none, 5s), @@ -91,30 +101,35 @@ void run_life_reservation_store_tests() { CHECK(admin->query("BEGIN", {}, 5s)); CHECK(admin->query("SELECT * FROM evolution.life_allocators WHERE world_id=9752 FOR UPDATE", {}, 5s)); - CHECK(failed(reserve_primitive_life(*db, a, *lease_a, alice, 1, 2, 1, 20ms), + CHECK(failed(reserve_primitive_life(*db, a, *lease_a, alice, 1, 3, 1, 20ms), LifeReservationError::unknown)); CHECK(admin->query("COMMIT", {}, 5s)); db = connect_as(env("EVO_PG_RUNTIME_USER")); - const auto reconciled = reserve(2); - CHECK(reconciled && reconciled->identity == first->identity + 1); - CHECK(reserve(2) == *reconciled); + const auto reconciled = reserve(3); + CHECK(reconciled && reconciled->identity == first->identity + 2); + CHECK(reserve(3) == *reconciled); const auto counter = admin->query( "SELECT next_identity FROM evolution.life_allocators WHERE world_id=9752", {}, 5s); - CHECK(counter && (*counter)[0][0] == "9223372036854775810"); - CHECK(reject_primitive_life(*db, a, *lease_a, alice, 1, 2, LifeRefusal::no_placement, 5s) == + CHECK(counter && (*counter)[0][0] == "9223372036854775811"); + CHECK(reject_primitive_life(*db, a, *lease_a, alice, 1, 3, LifeRefusal::no_placement, 5s) == LifeRefusal::no_placement); + const auto pending = reserve(4); + CHECK(pending && pending->refusal == LifeRefusal::none); + const auto moved = claim_account_control(*db, b, *lease_b, alice, 2, 2, 20000ms, 5s); + CHECK(moved); + auto moved_result = query_primitive_life(*db, b, *lease_b, alice, moved->generation, 4, 5s); + CHECK(moved_result && *moved_result && (**moved_result).reservation.region == 1 && + (**moved_result).reservation.refusal == LifeRefusal::cancelled); + const auto cancelled_retry = + reserve_primitive_life(*db, b, *lease_b, alice, moved->generation, 4, 1, 5s); + CHECK(cancelled_retry && cancelled_retry->refusal == LifeRefusal::cancelled); CHECK(admin->query("UPDATE evolution.life_allocators SET next_identity=18446744073709551615 " "WHERE world_id=9752", {}, 5s)); - CHECK(failed(reserve(3), LifeReservationError::exhausted)); - - const auto moved = claim_account_control(*db, b, *lease_b, alice, 2, 2, 20000ms, 5s); - CHECK(moved); + CHECK(failed(reserve_primitive_life(*db, b, *lease_b, alice, moved->generation, 5, 1, 5s), + LifeReservationError::exhausted)); CHECK(reserve_primitive_life(*db, b, *lease_b, alice, moved->generation, request, 1, 5s) == *refused); - CHECK(failed(reject_primitive_life(*db, b, *lease_b, alice, moved->generation, request, - LifeRefusal::cancelled, 5s), - LifeReservationError::not_available)); CHECK(failed(reserve(request), LifeReservationError::fenced)); CHECK(release_region_lease(*db, a, *lease_a, 5s)); CHECK(release_region_lease(*db, b, *lease_b, 5s)); diff --git a/tests/network_control.cpp b/tests/network_control.cpp index b2092fe..0d81e06 100644 --- a/tests/network_control.cpp +++ b/tests/network_control.cpp @@ -400,9 +400,15 @@ void session_codec() { CHECK(std::get(*decode_session(encode_session(intent))) == intent); const ActionOutcome outcome{5, ActionResult::not_committed, 0, 0}; CHECK(std::get(*decode_session(encode_session(outcome))) == outcome); - const std::array life_messages{ - PrimitiveLifeRequest{7, 8, 9}, PrimitiveLifeReceipt{9, AdmitStatus::admitted, 10}, - PrimitiveLifeOutcome{9, PrimitiveLifeResult::born, 11, 12}, PrimitiveLifeQuery{9}}; + const std::array life_messages{ + PrimitiveLifeRequest{7, 8, 9}, + PrimitiveLifeReceipt{9, AdmitStatus::admitted, 10}, + PrimitiveLifeOutcome{9, PrimitiveLifeResult::born, 11, 12}, + PrimitiveLifeOutcome{9, PrimitiveLifeResult::existing_life, 0, 0}, + PrimitiveLifeOutcome{9, PrimitiveLifeResult::cancelled, 0, 0}, + PrimitiveLifeOutcome{9, PrimitiveLifeResult::pending, 0, 0}, + PrimitiveLifeOutcome{9, PrimitiveLifeResult::unknown, 0, 0}, + PrimitiveLifeQuery{9}}; for (const auto& message : life_messages) { const auto bytes = encode_session(message); std::uint16_t version{}; diff --git a/tests/primitive_publication_tests.cpp b/tests/primitive_publication_tests.cpp index 68e9b77..7c4b992 100644 --- a/tests/primitive_publication_tests.cpp +++ b/tests/primitive_publication_tests.cpp @@ -199,6 +199,11 @@ void run_primitive_publication_tests() { auto bindings = db->query("SELECT * FROM evolution.load_primitive_lives(9753,1)", {}, 5s); CHECK(bindings && bindings->size() == 1 && (*bindings)[0][2] == "1" && (*bindings)[0][5] == "1"); + const auto durable_outcome = + query_primitive_life(*db, key, *lease, alice, control->generation, 1, 5s); + CHECK(durable_outcome && *durable_outcome && (**durable_outcome).published && + (**durable_outcome).published->identity == 1 && + (**durable_outcome).published->commit_sequence == 1); auto reject = reject_primitive_life(*db, key, *lease, alice, control->generation, 1, LifeRefusal::cancelled, 5s); CHECK(!reject && reject.error().kind == LifeReservationError::existing_life); diff --git a/tests/region_migration_tests.cpp b/tests/region_migration_tests.cpp index 190ecf5..c4c44c0 100644 --- a/tests/region_migration_tests.cpp +++ b/tests/region_migration_tests.cpp @@ -182,6 +182,7 @@ void upgrade_across_migration_and_barrier() { " -v migration_sha_14=$(s 0014_probe_overdue.sql)" " -v migration_sha_15=$(s 0015_life_reservations.sql)" " -v migration_sha_16=$(s 0016_primitive_publication.sql)" + " -v migration_sha_17=$(s 0017_life_request_outcomes.sql)" " -v runtime_role=evo_runtime_test -f migrations/apply.sql" " > /dev/null 2>&1") != 0); CHECK(history(*owner_db) == "1,2,3,4,5,6,7"); diff --git a/tools/ci/postgres-check.sh b/tools/ci/postgres-check.sh index 6d754e5..508d947 100644 --- a/tools/ci/postgres-check.sh +++ b/tools/ci/postgres-check.sh @@ -69,7 +69,7 @@ PGDATABASE=upgrade_path psql -X -v ON_ERROR_STOP=1 -1 -v "migration_sha=$v1_sha" -f "$root/migrations/0001_region_bootstrap.sql" > /dev/null test "$(PGDATABASE=upgrade_path psql -XAtc "SELECT string_agg(version::text, ',') FROM evolution.schema_migrations")" = 1 PGDATABASE=upgrade_path bash "$root/tools/migrate-postgres.sh" -test "$(PGDATABASE=upgrade_path psql -XAtc "SELECT string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16 +test "$(PGDATABASE=upgrade_path psql -XAtc "SELECT string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17 # v2 heads have no payload binding: v2->v3 fails closed and leaves history at v2. v2_sha="$(sha256sum "$root/migrations/0002_region_fencing.sql")" v2_sha="${v2_sha%% *}" @@ -90,7 +90,7 @@ PGDATABASE=v3_commits psql -X -v ON_ERROR_STOP=1 \ -c "INSERT INTO evolution.retained_builds VALUES (decode(repeat('b1', 32), 'hex'))" \ -c "SELECT evolution.provision_region_checkpoint(decode('4145564f52434d31' || '01000000' || '01000000' || '0100000000000000' || '0100000000000000' || '0900000000000000' || repeat('11', 16) || repeat('00', 8) || repeat('00', 16) || repeat('00', 32) || repeat('00', 16) || repeat('00', 16) || repeat('00', 8) || '50c3000000000000' || '020000000200000001000000010000000100000001000000010000000100000001000000' || repeat('b1', 32) || '00000000' || '00000000' || '01000000' || '6400000000000000' || repeat('a0', 32), 'hex'))" > /dev/null PGDATABASE=v3_commits bash "$root/tools/migrate-postgres.sh" -test "$(PGDATABASE=v3_commits psql -XAtc "SELECT count(*) || ':' || string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 16:1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16 +test "$(PGDATABASE=v3_commits psql -XAtc "SELECT count(*) || ':' || string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 17:1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17 test "$(PGDATABASE=v3_commits psql -XAtc "SELECT count(*) FROM evolution.region_commits")" = 1 # Review P1: a v4 database holding a published (possibly terminal) checkpoint has # no durable decisions for it. The v5 upgrade must refuse before changing anything. @@ -144,7 +144,7 @@ PGDATABASE=v6_populated psql -X -v ON_ERROR_STOP=1 \ -c "INSERT INTO evolution.retained_builds VALUES (decode(repeat('b1', 32), 'hex'))" \ -c "SELECT evolution.provision_region_checkpoint(decode('4145564f52434d31' || '02000000' || '01000000' || '0100000000000000' || '0100000000000000' || '0900000000000000' || repeat('11', 16) || repeat('00', 8) || repeat('00', 16) || repeat('00', 32) || repeat('00', 16) || repeat('00', 16) || repeat('00', 8) || '50c3000000000000' || '020000000200000001000000010000000100000001000000010000000100000001000000' || repeat('b1', 32) || '00000000' || '00000000' || '01000000' || '6400000000000000' || repeat('a0', 32) || repeat('00', 80), 'hex'))" > /dev/null PGDATABASE=v6_populated bash "$root/tools/migrate-postgres.sh" -test "$(PGDATABASE=v6_populated psql -XAtc "SELECT string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16 +test "$(PGDATABASE=v6_populated psql -XAtc "SELECT string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17 test "$(PGDATABASE=v6_populated psql -XAtc "SELECT count(*) FROM evolution.region_commits c, LATERAL evolution.parse_checkpoint_manifest(c.manifest) m WHERE m.commit_sequence = 0 AND m.predecessor_commit IS NULL")" = 1 test "$(PGDATABASE=v6_populated psql -XAtc "SELECT string_agg(conname, ',') FROM pg_constraint WHERE conrelid = 'evolution.region_heads'::regclass AND contype = 'c' AND pg_get_constraintdef(oid) LIKE '%end_tick%'")" = region_heads_published_tick # Inherited privileges bypass fencing, so every migrate run audits effective rights. @@ -189,9 +189,9 @@ expect_audit_failure 'GRANT SELECT ON evolution.account_controls TO evo_runtime_ expect_audit_failure 'REVOKE EXECUTE ON FUNCTION evolution.claim_account_control(evolution.u64, evolution.u64, uuid, evolution.u64, uuid, evolution.u64, evolution.u64, integer) FROM evo_runtime_test' 'GRANT EXECUTE ON FUNCTION evolution.claim_account_control(evolution.u64, evolution.u64, uuid, evolution.u64, uuid, evolution.u64, evolution.u64, integer) TO evo_runtime_test' bash "$root/tools/migrate-postgres.sh" # Restored configuration passes the audit again. # Unknown future versions and checksum drift must not be repaired silently. -psql -X -v ON_ERROR_STOP=1 -c 'UPDATE evolution.schema_migrations SET version=17 WHERE version=16' +psql -X -v ON_ERROR_STOP=1 -c 'UPDATE evolution.schema_migrations SET version=18 WHERE version=17' if bash "$root/tools/migrate-postgres.sh"; then exit 1; fi -psql -X -v ON_ERROR_STOP=1 -c "UPDATE evolution.schema_migrations SET version=16 WHERE version=17" +psql -X -v ON_ERROR_STOP=1 -c "UPDATE evolution.schema_migrations SET version=17 WHERE version=18" psql -X -v ON_ERROR_STOP=1 -c "UPDATE evolution.schema_migrations SET sha256=repeat('0',64) WHERE version=14" if bash "$root/tools/migrate-postgres.sh"; then exit 1; fi psql -X -v ON_ERROR_STOP=1 -c "UPDATE evolution.schema_migrations SET sha256=repeat('0',64) WHERE version=13" diff --git a/tools/ci/upgrade-check.sh b/tools/ci/upgrade-check.sh index 825ea7e..c230c2f 100644 --- a/tools/ci/upgrade-check.sh +++ b/tools/ci/upgrade-check.sh @@ -61,7 +61,7 @@ SQL [ "$code" != 0 ] && grep -q 'division by zero' "$work/migration.log" || fail "the rehearsal migration did not fail" [ "$(q -c "SELECT count(*) FROM information_schema.columns WHERE table_name = 'region_commits' AND column_name = 'rehearsal_column'")" = 0 ] || fail "the failed migration left a column" -[ "$(q -c 'SELECT max(version) FROM evolution.schema_migrations')" = 16 ] || fail "schema version moved" +[ "$(q -c 'SELECT max(version) FROM evolution.schema_migrations')" = 17 ] || fail "schema version moved" wait_ack "$work/b1.log" $((before + 40)) || fail "b1 did not resume after the failed migration" kill -0 "$b1_pid" 2> /dev/null || fail "b1 exited during the failed migration" bash "$root/tools/migrate-postgres.sh" > /dev/null || fail "migrate after the failure" diff --git a/tools/migrate-postgres.sh b/tools/migrate-postgres.sh index a0e46be..f75f170 100644 --- a/tools/migrate-postgres.sh +++ b/tools/migrate-postgres.sh @@ -44,6 +44,8 @@ digest_15="$(sha256sum "$root/migrations/0015_life_reservations.sql")" digest_15="${digest_15%% *}" digest_16="$(sha256sum "$root/migrations/0016_primitive_publication.sql")" digest_16="${digest_16%% *}" +digest_17="$(sha256sum "$root/migrations/0017_life_request_outcomes.sql")" +digest_17="${digest_17%% *}" psql -X --no-password --set=ON_ERROR_STOP=1 --set="migration_sha=$digest" \ --set="migration_sha_2=$digest_2" --set="migration_sha_3=$digest_3" \ --set="migration_sha_4=$digest_4" --set="migration_sha_5=$digest_5" \ @@ -53,5 +55,6 @@ psql -X --no-password --set=ON_ERROR_STOP=1 --set="migration_sha=$digest" \ --set="migration_sha_14=$digest_14" \ --set="migration_sha_15=$digest_15" \ --set="migration_sha_16=$digest_16" \ + --set="migration_sha_17=$digest_17" \ --set="runtime_role=$runtime_role" \ --file="$root/migrations/apply.sql"