feat: implement CH5 cube renewal, SQL fence routing, and transactional crafting

This commit is contained in:
shen
2026-10-23 20:17:22 -07:00
parent 6924dc9b49
commit b5e06c9a43
135 changed files with 8493 additions and 56 deletions
+407
View File
@@ -0,0 +1,407 @@
# Cube durable batch candidate
Status: **candidate SQL backend, DB FIFO adapter and disabled preparation handshake**. No live
craft command, capability or whole-feature macro is enabled by this directory.
The existing modern client remains a read-only catalogue/requirements preview.
Installing schema.sql alone does not establish an online ownership fence.
Original-LIVE image ACK candidate: optional `image-ack-schema.sql` adds two
InnoDB tables (v1) after base v2 / gold v2 / owner v1. Internal messages 20/21
carry the full canonical image. The store verifies current SQL, the original
LIVE grant and an already issued identical RESYNC image in the same account
transaction, then persists immutable full batch/grant/image bytes. Every retry
revalidates authority, including after lost COMMIT replies. This is evidence of
application only: Acknowledged actors remain held; owner leases and item fences
remain present and legacy Release remains denied. No startup schema install,
production migration, terminal release, save/event resume or thaw is provided.
The dedicated image-ACK probe is included in `test_mysql.sh`.
Optional `release-schema.sql` adds terminal-receipt v1 (requires ACK v1 and
the above schemas). `ReleaseStore::ReleaseLive` shares Fence.Release's account
transaction: full immutable ACK, current SQL image and original LIVE authority
are checked before archiving a terminal receipt and retiring the lease/item
fences atomically. Permanent ID reservations remain. Exact historical replay
requires the original broker, ACK/receipt/fence image and no conflicting newer
lease/fence. Internal22/23 DB route is disabled; game does not send release yet.
DB memory save/load gates survive this SQL decision, even when a trusted peer
loss reconciles its lost COMMIT reply. Saving/events/UI readiness, resume handoff
and actor thaw are still required. `test_mysql.sh` includes the release probe.
Owner authority candidate additionally requires explicit `owner-schema.sql`
(three InnoDB tables, v1) with base v2 and gold-addon v2. DB Arm refuses absent
or incompatible ownership metadata. No runtime installation or fabrication of
leases for historical batches occurs. A database-scoped MySQL connection lock
plus boot/connection generation fences old brokers; Fence.Begin atomically binds
the immutable original owner. Trusted disconnect revokes, and authenticated
non-playing-account recovery can only prepare a fresh **held** adoption after
original source/DONE/wallet validation. This does not authorize player loading,
currency writes or thaw. All registered leases block legacy release and ordinary
save/load. Owner-aware image/ACK/thaw and core-boot fencing are still pending.
Held adoptions and ambiguous adoption Retry proposals are retained in runtime
before returning. Pre-load recovery expects a non-playing account. Peer close,
validated current-peer logout and auth-record replacement invalidate them before
identity reuse; callbacks do not execute SQL. A joint round-robin queue runs at
most two revoke/drain-finalization jobs per tick, with five-second error backoff.
This bounds jobs, not SQL statements or wall-clock latency. Obsolete recovery
memory is retired only after durable revocation/non-ownership proof; SQL holds,
receipts and item locks are not removed. No public recovery transport is enabled.
## Contract and scope
- `common/cube_batch.h`: bounded canonical request codec and deterministic
settlement planner. A batch has account/player, nonzero owner/receipt IDs,
epoch, normalized recipe, 1..100 attempts, exact ordinary-inventory snapshot,
wallet snapshot and factory-produced reward templates. Decode rejects trailing
data, truncation, excessive counts and unsupported copy recipes. It does not
serialize C++ padding or trust a client-provided item image.
- `common/cube_store.h`: database-only `BatchStore<DB>`. The adapter provides
Query/Begin/Commit/Rollback, affected and warnings, using the same pinned
connection. `PortEconomy::Mysql` now exposes warning count without changing
existing economy policy; Cube explicitly rolls back on any warning.
- `Prepare` checks immutable receipt identity, a matching durable FROZEN fence,
epoch/owner/request, and absence of an offline-economy pending request. It
reserves worst-case reward IDs and persists all 1..100 rolls before any asset
mutation. Exact retries never call RNG again. Changed payload with the same
receipt is rejected. An uncommitted prepare may draw again; a committed one
may not, including when the original COMMIT acknowledgement was lost.
- `Execute(token, account, player)` loads its original request and draws from SQL,
verifies the fence again, locks the wallet and normal inventory, and compares
IDs, cells, vnums, counts, all sockets/attributes and all 69 port_extra bytes.
No caller-supplied recovery snapshot can replace that persisted request.
- It calculates the complete deduction/output grid before changing assets. All
attempts pay; only successful attempts generate rewards. A three-attempt batch
with two successes pays three material/fee units and receives two reward units.
Zero successes is a paid successful transaction with a durable receipt, not a
transaction error. Actual transaction failure rolls back all tentative writes.
- Costs, actual rewards and terminal receipt commit atomically. Failed logical
validation records a zero-cost terminal rejection. SQL/connection failure
keeps PREPARED; ambiguous commit is recovered by reading the same receipt,
never by issuing a refund or a new random batch. Replayed receipts validate
their result, original draws, fee and complete awarded item images.
- The five 5x9 inventory pages enforce physical item height and page boundaries.
Fully consumed stacks free cells; partial stacks keep their footprint. Rewards
are split at 2000 for stackables, one each for non-stackables. This candidate
does **not** merge rewards into pre-existing stacks or use special bags/mall.
- Stable reward IDs are factory reservations, not rows created prematurely.
Their permanent tombstones use existing port_economy_item_reservations, already
included by the DB restart item-ID high-water reader. Unused/rejected IDs must
not be deleted or reused. New IDs must still come from a verified game/DB range
allocator when the runtime coordinator is implemented.
Ready() requires the unsuffixed InnoDB schema, Cube version2 / economy version1 tables,
exactly the known item-column set and nonnullable 69-byte binary extra storage.
An unknown item column or incompatible schema fails closed, not a lossy fallback.
There is no startup auto-migration. The future coordinator must also explicitly
reject table postfixes; the current candidate is not a suffix-routing layer.
## Version2 drain and resync core / actual DB guards
`cube_drain.h` tracks the exact batch, transport-session generation, numbered
first/second main SQL callbacks, async callback and both failure epochs. Duplicate,
out-of-order and old-session callbacks cannot complete it. The core itself does
not enqueue SQL. `db/src/CubeRuntime.cpp` now provides the internal Arm/Submit
adapter: capture failure epochs before final saves, compare exact cached wallet
and normal-inventory metadata, lock all cached owned IDs (including tombstones),
persist DRAINING, evict caches and enqueue two numbered main FIFO barriers plus
the real PLAYER async FIFO barrier. Main result dispatch, pulse and peer-removal
hooks are compiled into DB. Header78 now carries a bounded, explicit little-endian
Arm/Submit/Poll/Cancel/Answer/Invalidate handshake. Both `HandshakeEnabled` and
`ActorMutationAuditComplete` remain **false**; actual DB ingress rejects before
any Arm/SQL work, and game Begin cannot start. No client command or capability
exposes this protocol. Do not enable it to run a live test.
`SQLFences.h` / `sql_fence_router.h` route both existing Economy and Cube results
from that SAME async connection. Monotonic process-local tokens are never reused
or dereferenced as pointers; a consumer cannot steal another kind's result.
Unknown/duplicate results poison the failure epoch; full capacity retries rather
than pretending the queue drained. DB teardown clears owned result messages.
The actual libsql threaded worker is tested against a dedicated socket, separately
from the explicit peer/cache coordinator test doubles.
Arm temporarily blocks account loads, foreign saves and competing economic
mutations. Peer loss is sticky even if the handle reappears. An unused Arm may
expire after 60 seconds; once Begin was attempted (including ambiguous COMMIT),
the hold never expires. Failed drains reach ABORTED, clean drains FROZEN, but
both remain held. This adapter does not call Prepare/Execute, resync or release.
Its unfinished held contexts intentionally fill a bounded 128-entry limit rather
than evicting ownership evidence. Activation requires a complete terminal path.
Cancellation is only acknowledged before any Begin attempt and retains a short
replay tombstone. A late cancel after Submit/Begin is a hold, not a refund/unlock.
`game/src/port_cube_actor.cpp` supplies preparation state, descriptor/VID/session
reply matching, canonical ordinary-inventory plus all-owned-window seals and the
Arm ACK -> final player/item saves -> Submit ordering. It rechecks live NPC and
the exact loaded recipe bytes rather than trusting the UI's FNV fingerprint.
`FlushDelayedSaveForPlayer` additionally flushes special bags and detached pending
destroys; it must not take an item now owned by someone else based on last-owner.
Timeout, DB loss and unrecognized replies never grant thaw. Only a matching
explicit pre-Begin cancellation ACK can clear preparation. This is NOT a complete
actor freeze: item expiry, combat/quest rewards and other direct mutators still
need audited quiescence. CanHandleItem gating and snapshot equality are necessary,
not sufficient. No PointChange/item setter silently drops mutations in this batch.
## Conservative admission and invalidation (2026-10-23)
`cube_mutation.h`, `port_cube_item.inc` and the game adapter now refuse preparing
an actor with personal quest timers/running scripts, an active switchbot slot,
party/victim/lifecycle hazards, busy/skip-save items or any owned item with an
expiry/ownership/destroy event, a clock proto limit or unique type. The restriction
on all unique items is deliberately conservative, not a claim all of them expire.
The query includes all captured owned windows and uses a non-creating quest-PC
lookup which does not change the current Lua PC. Recheck on Arm ACK and just
before Submit. No expiry event is cancelled, reset or extended to admit a batch.
Whole switchbot rolls and new starts yield before flags/RNG/payment; classic
Cube_make also refuses a held actor before materials/gold/RNG. These guards have
no effect on ordinary actors. Item Save, gold PointChange, quest-script execution,
actual flag/timer changes, WarpSet and Disconnect notify preparation without
suppressing the original operation. The sticky mutation mask prevents an ABA
change (value changed back) from making the old snapshot eligible again.
Before Submit the original Arm can only be cancelled; after Submit, Invalidate
retains the hold. DB poisons drain ownership and aborts only a provably unprepared
fence; an accepted PREPARED receipt is preserved, not cancelled/refunded.
**This is still not asset quiescence.** The ground-gold candidate below covers
only one source. Other legitimate rewards/expiry/mutations after Submit may be
detected but are not yet durably queued and reconciled. Normal
DB saves are fenced then; allowing logout/restart without durable recovery could
lose that legitimate work. Direct setters/field writes, global/server quest
callbacks, experience, party/ground-drop ownership and lifecycle handling still
need a complete audited policy. Keep both gates false. Do not run a live batch.
`python3 tools/cube/audit_mutations.py` prints a read-only lexical review index
with source hashes. It includes comments/definitions and misses indirect calls,
aliases and unlisted setters; counts are NOT semantic coverage or acceptance.
`cube_fence.h` implements the SQL lifecycle: DRAINING → FROZEN (clean proof) or
ABORTED (failed saves/lost owner), then RESYNC → RELEASED. DRAINING stores the
immutable body and per-item locks before cache eviction. Reward IDs are reserved
at this point, before Prepare; Prepare accepts only the same reservation identity.
Known SQL IDs, all supplied owned cached IDs and input/output IDs remain protected.
`ItemIDRangeManager::BuildRange` also includes active item-fence IDs, so restart
cannot reissue a dirty ID absent from item. Permanent reward reservations survive
release. Never delete them as a cleanup shortcut.
The DB now compiles `Cube.cpp`. Its gates are called by existing player/quest and
item save/delete gateways, item-flush ingress, character load/deletion and offline
economy mutation/settlement. Consumed IDs are checked without joining item; orphan
item locks also quarantine the player/account. No schema preserves the baseline;
partial/unknown schema, query failure or active fence denies the affected path.
Schema installation/removal requires coordinated restart. These are **real DB
gateway guards**, not evidence of an implemented game-side freeze or live RPC.
Resync reads and validates canonical SQL gold/normal inventory, including complete
stored item metadata and physical grid. Release requires the exact acknowledged
image, same body/owner/epoch/token and a locked SQL re-read equal to that image.
Only then are item locks removed and RELEASED committed atomically. Lost release
acknowledgements replay without releasing a later epoch. A persisted aborted-drain
marker makes repeated resync safe even when no crafting request was prepared.
`Recover` can reload the original body/stage/image after process restart; it does
not transfer ownership to a new game session by itself. No timeout releases holds.
The image does not encode runtime-only lock/event state; its usable bit is not
permission to unlock an item. The game adapter must separately preserve/rebuild
those states and must re-snapshot actual usability for each later batch.
Fresh installations use schema.sql. The unreleased v1 candidate requires explicit
maintenance upgrade-v2.sql: it refuses every unresolved v1 fence/PREPARED request,
preserves historical rows and can resume partial DDL. Applying schema.sql alone
does not upgrade a v1 row or manufacture missing ownership evidence. No production
migration was performed in this implementation batch.
## Not yet implemented / activation blockers
### Candidate deferred positive-gold addon (ingress still closed)
`cube_gold_intent.h` / `cube_gold_store.h` and the explicit DB instantiation in
`CubeGold.cpp` implement trusted positive-credit intent storage, not an automatic
PointChange interceptor. Optional `gold-schema.sql` now has its own version 2;
base Cube remains version 2. There is no startup migration. All three addon tables must be
InnoDB. Absence preserves the baseline; partial/unknown schema and SQL errors
fail closed. Installing/removing the addon requires coordinated maintenance and
restart because actual DB guards cache schema discovery. Never drop unresolved
intent rows or disable guards to recover a held actor.
The actual DB Arm now requires addon v2 even when the base batch store is ready;
the absent-addon compatibility baseline is not permission to start a modern actor.
Each canonical 129-byte body binds account/player/epoch/owner/request plus a
globally unique stable event ID, sequence (1..1024), source label and positive
amount. Source labels are not authentication. Enqueue never changes currency;
retries must send the identical body and event ID. The source must durably record
the event before acknowledging delivery: a trusted producer/outbox and durable
ACK protocol now has one compiled ground-gold source, described below; this is
not complete producer coverage or enabled ingress. Do not both execute a reward
locally and enqueue it here. Capacity/transport/SQL failure is not permission to drop a reward
or acknowledge success.
Apply takes identity only, reads the saved amount and requires clean FROZEN plus
a fully validated original DONE receipt. It locks the same economy account row,
checks the expected post-craft wallet and applied prefix, and atomically updates
wallet and APPLIED receipt. Only the next sequence can apply. Lost commit ACK,
restart and duplicate calls recover the original receipt, never another credit.
Pending intents block Resync/Release and actual player save/account load,
including orphan pending rows without a base fence. New intents cannot enqueue
after RESYNC; historical APPLIED replay does not change a later wallet.
ABORTED intents persist but cannot automatically apply; reconciliation is still
required. Overflow, wallet mismatch or corrupt history stays held, not refunded
or silently discarded. No item/EXP/negative-cost intents or general event-clock
freeze are implemented. Both activation gates remain false. The new route below
can call Enqueue only behind disabled ingress; no live code calls Apply.
### Ground-gold outbox candidate
After original distance/ownership checks, a submitted held non-party actor may
use `PortCubeDeferGroundGold`. The candidate validates the current actor binding
again, excludes party/lifecycle hazards, and binds a random 128-bit stable event
ID to the original batch/session/cookie/handle plus ground VID/vnum/map. Admission
before Submit is refused, not converted into a reward. Ordinary actors retain
GiveGold, removal and Save; the deferred path removes the pile only after fsync
and skips BOTH local GiveGold and stale player Save. Existing gold cap is checked
conservatively against pre-craft gold plus all credits reserved for that batch.
`cube_gold_outbox.h` is an append-only core-private journal under
`cube-gold-outbox/journal` in that core's working directory. Exclusive lifetime
lock, O_NOFOLLOW, regular/single-link owner checks, initial file/lock/directory
fsync, fixed 166-byte versioned LE records and checksum detect partial/corrupt
writes. The checksum is NOT source authentication. Claim and ACK fsync before
success. A failed/uncertain write pauses that writer; the runtime quarantines the
ground VID even against other players until restart/operator reconciliation.
Pure pre-write admission refusal does not quarantine a pile. Never delete the
journal or truncate a bad tail automatically.
ACK history is retained: next sequence cannot reset after restart. Limits are
1024 events per batch, 8192 historical claims and 16 MiB per journal. There is no
automatic compaction/deletion; reaching a bound refuses new source acceptance,
not existing retries. A healthy empty Pending result alone is not proof of actor
quiescence, and an unhealthy journal must never authorize thaw.
Internal header78 adds GoldEnqueue=7 / GoldAck=8, statuses GoldStored=8 /
GoldApplied=9. Prefix remains 102 bytes, body is the canonical 129-byte intent,
total 231 bytes. Both game/db must match this unreleased protocol. DB route
requires the original authenticated peer/login/handle/session/cookie and batch;
it ACKs only immutable Stored/Applied results. Game persists an exact-body ACK
with matching handle/session/cookie, independently of whether the actor exists;
ACK does NOT update the live wallet or release the hold. Retries are bounded to
two deliveries per three seconds, round-robin. Source label 1 here means ground
gold, not permission for arbitrary client requests to issue currency.
DB/game restart or changed owner/peer loses the in-memory binding; the local
outbox is retained, but old sessions are NOT automatically adopted or credited.
Trusted handover/reconciliation remains to implement. The ground-source barrier
below now proves no late locally durable credits remain for that source. It is
not coverage of other rewards/mutators. Keep both gates false until all required
mutation/factory/image and ownership paths close.
`test_cube_outbox.py` covers real source/helper/ACK bodies with explicit actor and
audited-ingress substitutes, journal write/sync faults and process exits, and a
journal -> SQL lost-ACK/replay -> durable ACK -> credit/release scenario. The
isolated MySQL script also runs that scenario against the actual addon DDL.
### Durable ground-source close and exact manifest
On a matching Frozen reply, the game fsyncs a source CLOSING marker before
refusing new claims. It may still retry old deliveries and accept their exact
ACKs. Only when all recorded claims have durable delivery ACKs may PendingSources
produce a close request. The binding includes account/player/epoch/owner/request
and original session/cookie/handle, including for a batch with zero rewards.
CGO1 keeps fixed 166-byte frames, adding op3 CLOSING and op4 source-ACK with a
96-byte binding, 4-byte count and canonical zero padding. Old CGO1 claim/ACK
records remain readable; an old binary rejects these unknown ops rather than
discarding them. No automatic downgrade or source reopening is supported.
Header78 GoldClose=9 / GoldCloseAck=10, status GoldClosed=10, carries an exact
4-byte count plus ordered 32-byte event IDs (maximum 32772-byte body / 32874-byte
frame). This is not a hash or mere count. Existing peer/login/session/cookie
checks apply. SQL source sealing and new intent enqueue share the account lock:
all current persisted event IDs must match, and a sealed request refuses new
events while still allowing exact historical retries. Source-close commit ACK
loss replays the identical proof. Game fsyncs the matching source ACK, which is
not permission to apply an image or thaw.
For addon v2 batches, Resync/Release require a valid stored source binding and manifest matching
all persisted intents, including the empty case, as well as completed credit
receipts/current wallet. SQL emptiness alone is never a source proof. Missing,
corrupt, truncated or reordered seals retain the hold. A vanished in-memory
owner cannot create a new seal merely by presenting an old request token.
New installations use gold-schema.sql. The old unreleased addon v1 requires
explicit maintenance gold-upgrade-v2.sql and coordinated restart. It preserves
all intents/receipts, creates no closure rows, rejects unknown/non-InnoDB/partial
source metadata, and supports retry after explicit repair. Applying fresh DDL
alone does not advance a v1 version row. Old held requests still require trusted
closure/reconciliation. No production migration is performed by tests/startup.
`test_cube_source.py` probes zero/late source closure, real journal fsync exits,
ambiguous SQL close commit, each close SQL failure/warning, process death and
two-process duplicate sealing, exact bounded manifests and old-version refusal.
Actual game close-ACK and DB close-route bodies have separate boundary tests.
Local addon probe: `python3 tests/features/test_cube_gold.py`. The isolated
MySQL script below also installs the actual addon DDL and runs its crash,
concurrency, failure/warning and replay probes after the base lifecycle probes.
### Remaining live integration
The batch store trusts a DB-owned FROZEN record; the lifecycle core can establish
it only from a trusted adapter proof. Compiled game/DB preparation has no enabled
entry; no live code calls Prepare/Execute. A real game coordinator must bind the active
recipe/NPC/window, current character/connection generation and trusted factory
images, stop **all** relevant mutation paths, flush game/item/player caches,
drive the DB adapter over an authenticated handshake and handle failed saves.
Do not insert that row from a client command or treat wall-clock expiry as proof.
Capture failure epochs before the final-save handoff. A one-shot trusted snapshot
ingress must be bound to its owner/generation: ordinary Save packets sent after
DRAINING are intentionally rejected by the new gates. Simply calling ch->Save()
after Begin, or capturing failure counters only after saves already failed, is
not a valid implementation. Eviction may directly flush known owned caches while
regular peer ingress is closed; callbacks must not reintroduce dirty caches after
the second barrier. The DB portion and disabled final-save handshake are
implemented/tested; complete game mutation-path quiescence is still required.
After commit, authoritative asset state must be loaded and reconciled into the
right still-frozen online owner before releasing it. Lost peers, changed epochs,
cross-channel login, reconnect and server restarts require ownership recovery;
never apply an unverified delta to an old cached actor. Existing offline Economy
must not settle concurrently. Completing this requires real game/db integration
and fault tests; a manually inserted test fence is not that evidence.
Copy-attribute rules, success-rate items, online action protocol/UI, resync,
timeouts/shutdown handling and actual Android-device asset acceptance remain
unfinished. Do not open the whole Cube macro based on SQL tests alone. No forced
logout shortcut or client loop over legacy Cube_make is authorized here.
## Reproduction
Local ASan/UBSan plus SQLite SQL/dialect boundary:
```sh
python3 tests/features/test_cube_batch.py
```
On the FreeBSD build host, with mysql_install_db/mysqladmin/mysql/mysql_config
and /usr/local/libexec/mysqld installed:
```sh
sh tools/cube/test_mysql.sh
# Full platform-matched source/library build tree: also exercise real SQL worker.
CUBE_TEST_SQL_WORKER=1 sh tools/cube/test_mysql.sh
```
The script creates a fresh `/tmp/ch5-cube-mysql.XXXXXX` datadir and socket-only
instance with `--no-defaults` and `--skip-networking`. Every client command uses
that exact socket and explicit test database. It never connects to production,
shuts down only that instance and retains test data/logs for inspection.
Base fixture tables are created before applying the actual schema.sql to the
fresh test database; the SQL adapter and production Mysql connection wrapper are
used without a SQLite rewrite in this run.
Probes cover fixed RNG replay, partial/all failure, 64-bit fees, multi-stack and
locked inputs, full/overlapping grid, sockets/attributes/extra preservation,
wrong owner/epoch/account, conflicting payload, corrupt request/draw/receipt,
every prepare/execute SQL failure position, commit rejected/lost acknowledgement,
process exit before/after durable commit, and two-process duplicate execution.
Real MySQL also checks MyISAM/unknown-column/version rejection and actual numeric
truncation warnings with strict mode disabled. None of these starts a real actor.
+38
View File
@@ -0,0 +1,38 @@
#!/usr/bin/env python3
"""Read-only review index, NOT a call graph or proof of complete quiescence."""
import hashlib
import json
import re
from pathlib import Path
ROOT=Path(__file__).resolve().parents[2]
PATTERNS={
'gold_points':r'\b(?:PointChange\s*\(\s*POINT_GOLD|SetGold\s*\(|m_points\.gold\s*[+*/-]?=)',
'experience_points':r'\b(?:PointChange\s*\(\s*POINT_EXP|SetExp\s*\()',
'item_ownership':r'\b(?:AddToCharacter|RemoveFromCharacter|AutoGiveItem|RemoveItem|DestroyItem)\s*\(',
'item_image':r'\b(?:SetCount|SetSocket|SetAttribute|SetPortExtra|SetItem)\s*\(',
'quest_work':r'\b(?:ExecuteQuestScript|SetFlag|DeleteFlag|AddTimer|ServerTimer)\s*\(',
'lifecycle':r'\b(?:Disconnect|WarpSet|SaveReal|SaveSingleItem)\s*\(',
}
def scan(folder):
hits=[];sources={}
for path in sorted(folder.rglob('*')):
if not path.is_file() or path.suffix not in {'.cpp','.h','.inc'}:
continue
data=path.read_bytes();text=data.decode('latin1') # ASCII tokens, preserve legacy bytes
relative=str(path.relative_to(folder));found=False
for number,line in enumerate(text.splitlines(),1):
for kind,pattern in PATTERNS.items():
if re.search(pattern,line):
hits.append(dict(file=relative,line=number,kind=kind));found=True
if found:sources[relative]=hashlib.sha256(data).hexdigest()
return dict(schema_version=1,scope='lexical_review_candidates_not_semantic_coverage',
warning='Includes definitions/comments/conditional branches; misses aliases, macros, indirect calls and unlisted setters. No hit is automatically accepted or safe.',
totals={kind:sum(x['kind']==kind for x in hits) for kind in PATTERNS},
source_sha256=sources,hits=hits,activation_allowed=False)
if __name__=='__main__':
print(json.dumps(scan(ROOT/'src/server/game/src'),indent=2))
+27
View File
@@ -0,0 +1,27 @@
-- Optional deferred positive-gold-intent candidate, version 2. Install only in
-- coordinated maintenance with matched Cube code; never applied at startup.
-- Base Cube remains schema v2. This does not enable a producer or crafting.
CREATE TABLE IF NOT EXISTS port_cube_gold_version (
id INT UNSIGNED PRIMARY KEY, version INT UNSIGNED NOT NULL
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS port_cube_gold_intents (
event CHAR(32) CHARACTER SET ascii COLLATE ascii_bin PRIMARY KEY,
request CHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
seq INT UNSIGNED NOT NULL, account INT UNSIGNED NOT NULL, pid INT UNSIGNED NOT NULL,
body VARBINARY(129) NOT NULL,
state ENUM('QUEUED','APPLIED') NOT NULL,
before_gold BIGINT UNSIGNED NOT NULL DEFAULT 0,
after_gold BIGINT UNSIGNED NOT NULL DEFAULT 0,
UNIQUE KEY batch_sequence(request,seq), INDEX player_pending(pid,state)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS port_cube_gold_sources (
request CHAR(32) CHARACTER SET ascii COLLATE ascii_bin PRIMARY KEY,
account INT UNSIGNED NOT NULL, pid INT UNSIGNED NOT NULL,
epoch BIGINT UNSIGNED NOT NULL,
owner CHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
session BIGINT UNSIGNED NOT NULL, cookie INT UNSIGNED NOT NULL, handle INT UNSIGNED NOT NULL,
manifest VARBINARY(32772) NOT NULL,
INDEX player_source(pid)
) ENGINE=InnoDB;
INSERT INTO port_cube_gold_version(id,version) VALUES(1,2)
ON DUPLICATE KEY UPDATE version=version;
+30
View File
@@ -0,0 +1,30 @@
-- Explicit maintenance upgrade of the unreleased gold addon v1. Preserve all
-- intents/receipts; do not invent a closed source for an old held actor. Stop
-- producers and matched game/DB first, then restart after verification.
DELIMITER //
DROP PROCEDURE IF EXISTS port_cube_gold_upgrade_v2//
CREATE PROCEDURE port_cube_gold_upgrade_v2()
gold_upgrade: BEGIN
DECLARE current_version INT DEFAULT 0;
DECLARE present INT DEFAULT 0;
SELECT version INTO current_version FROM port_cube_gold_version WHERE id=1;
IF current_version NOT IN (1,2) THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='Expected gold addon version 1 or 2'; END IF;
SELECT COUNT(*) INTO present FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND ENGINE='InnoDB' AND TABLE_NAME IN ('port_cube_gold_version','port_cube_gold_intents');
IF present<>2 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='Gold addon foundation missing/nontransactional; retain all history'; END IF;
CREATE TABLE IF NOT EXISTS port_cube_gold_sources (
request CHAR(32) CHARACTER SET ascii COLLATE ascii_bin PRIMARY KEY,
account INT UNSIGNED NOT NULL, pid INT UNSIGNED NOT NULL,
epoch BIGINT UNSIGNED NOT NULL,
owner CHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
session BIGINT UNSIGNED NOT NULL, cookie INT UNSIGNED NOT NULL, handle INT UNSIGNED NOT NULL,
manifest VARBINARY(32772) NOT NULL, INDEX player_source(pid)
) ENGINE=InnoDB;
SELECT COUNT(*) INTO present FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND ENGINE='InnoDB' AND TABLE_NAME='port_cube_gold_sources';
IF present<>1 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='Gold source table is nontransactional'; END IF;
SELECT COUNT(*) INTO present FROM information_schema.columns WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='port_cube_gold_sources' AND COLUMN_NAME IN ('request','account','pid','epoch','owner','session','cookie','handle','manifest');
IF present<>9 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='Gold source table incomplete; repair without dropping intents'; END IF;
UPDATE port_cube_gold_version SET version=2 WHERE id=1 AND version=1;
END//
CALL port_cube_gold_upgrade_v2()//
DROP PROCEDURE port_cube_gold_upgrade_v2//
DELIMITER ;
+13
View File
@@ -0,0 +1,13 @@
-- Optional image-ACK addon v1; requires Cube v2, gold v2 and owner v1.
-- Explicit coordinated maintenance only. No asset writes, release or adoption.
CREATE TABLE IF NOT EXISTS port_cube_image_ack_version (
id INT UNSIGNED PRIMARY KEY, version INT UNSIGNED NOT NULL
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS port_cube_image_acks (
request CHAR(32) CHARACTER SET ascii COLLATE ascii_bin PRIMARY KEY,
body MEDIUMBLOB NOT NULL,
owner_grant VARBINARY(160) NOT NULL,
image MEDIUMBLOB NOT NULL
) ENGINE=InnoDB;
INSERT INTO port_cube_image_ack_version(id,version) VALUES(1,1)
ON DUPLICATE KEY UPDATE version=version;
+31
View File
@@ -0,0 +1,31 @@
-- Optional owner authority v1. Explicit coordinated maintenance only.
-- Requires base Cube v2 and gold-addon v2. Does not adopt legacy holds,
-- manufacture source closure, enable crafting, or install at startup.
CREATE TABLE IF NOT EXISTS port_cube_owner_version (
id INT UNSIGNED PRIMARY KEY, version INT UNSIGNED NOT NULL
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS port_cube_owner_broker (
id INT UNSIGNED PRIMARY KEY,
generation BIGINT UNSIGNED NOT NULL,
boot CHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
connection_id BIGINT UNSIGNED NOT NULL
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS port_cube_owner_leases (
request CHAR(32) CHARACTER SET ascii COLLATE ascii_bin PRIMARY KEY,
account INT UNSIGNED NOT NULL, pid INT UNSIGNED NOT NULL,
body MEDIUMBLOB NOT NULL,
revision BIGINT UNSIGNED NOT NULL, generation BIGINT UNSIGNED NOT NULL,
boot CHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
connection_id BIGINT UNSIGNED NOT NULL, peer INT UNSIGNED NOT NULL,
binding VARBINARY(96) NOT NULL,
original_peer INT UNSIGNED NOT NULL, original_binding VARBINARY(96) NOT NULL,
phase ENUM('LIVE','REVOKED','ADOPTED') NOT NULL,
revoked_generation BIGINT UNSIGNED NOT NULL DEFAULT 0,
reason TINYINT UNSIGNED NOT NULL DEFAULT 0,
UNIQUE KEY held_account(account), UNIQUE KEY held_player(pid)
) ENGINE=InnoDB;
INSERT INTO port_cube_owner_broker(id,generation,boot,connection_id)
VALUES(1,0,'00000000000000000000000000000000',0)
ON DUPLICATE KEY UPDATE generation=generation;
INSERT INTO port_cube_owner_version(id,version) VALUES(1,1)
ON DUPLICATE KEY UPDATE version=version;
+13
View File
@@ -0,0 +1,13 @@
-- Optional terminal release v1. Requires Cube v2, gold v2, owner v1, ACK v1.
-- Coordinated maintenance only; no startup install or actor thaw permission.
CREATE TABLE IF NOT EXISTS port_cube_release_version (
id INT UNSIGNED PRIMARY KEY, version INT UNSIGNED NOT NULL
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS port_cube_releases (
request CHAR(32) CHARACTER SET ascii COLLATE ascii_bin PRIMARY KEY,
body MEDIUMBLOB NOT NULL,
owner_grant VARBINARY(160) NOT NULL,
image MEDIUMBLOB NOT NULL
) ENGINE=InnoDB;
INSERT INTO port_cube_release_version(id,version) VALUES(1,1)
ON DUPLICATE KEY UPDATE version=version;
+38
View File
@@ -0,0 +1,38 @@
-- Candidate Cube backend only. Never applied at startup. Requires the existing
-- unsuffixed player/item/economy InnoDB schema and matching online coordinator.
-- Installing these tables alone MUST NOT enable gameplay or create fences.
CREATE TABLE IF NOT EXISTS port_cube_version (
id INT UNSIGNED PRIMARY KEY, version INT UNSIGNED NOT NULL
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS port_cube_requests (
token CHAR(32) CHARACTER SET ascii COLLATE ascii_bin PRIMARY KEY,
account INT UNSIGNED NOT NULL, pid INT UNSIGNED NOT NULL,
body MEDIUMBLOB NOT NULL, rolls VARBINARY(100) NOT NULL,
state ENUM('PREPARED','DONE') NOT NULL,
result VARCHAR(64) CHARACTER SET ascii NOT NULL,
successes INT UNSIGNED NOT NULL DEFAULT 0,
fee BIGINT UNSIGNED NOT NULL DEFAULT 0, awards MEDIUMBLOB NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
INDEX player_history(pid,created_at)
) ENGINE=InnoDB;
-- Only the future cache-drain/owner coordinator may install FROZEN. Time alone
-- may never release it: ambiguous commits require journal lookup and resync.
CREATE TABLE IF NOT EXISTS port_cube_fences (
pid INT UNSIGNED PRIMARY KEY, account INT UNSIGNED NOT NULL,
epoch BIGINT UNSIGNED NOT NULL,
owner CHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
request CHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL UNIQUE,
phase ENUM('DRAINING','FROZEN','ABORTED','RESYNC','RELEASED') NOT NULL,
body MEDIUMBLOB NOT NULL, image MEDIUMBLOB NOT NULL,
drain_state TINYINT UNSIGNED NOT NULL DEFAULT 0
) ENGINE=InnoDB;
-- Covers consumed IDs too: lookup by the current item owner cannot protect an
-- ID after its row has been deleted by the transaction.
CREATE TABLE IF NOT EXISTS port_cube_item_fences (
id INT UNSIGNED PRIMARY KEY, pid INT UNSIGNED NOT NULL,
epoch BIGINT UNSIGNED NOT NULL,
request CHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
INDEX player_fence(pid,epoch)
) ENGINE=InnoDB;
INSERT INTO port_cube_version(id,version) VALUES(1,2)
ON DUPLICATE KEY UPDATE version=version;
+44
View File
@@ -0,0 +1,44 @@
#!/bin/sh
# Offline real-game-object probe. Never starts game main or connects to DB.
# Inputs must be a matching, fully rebuilt game source/object cohort; this
# script does not prove live asset acceptance or repair stale input objects.
set -eu
if [ "$(uname -s)" != FreeBSD ] || [ "$#" -ne 3 ]; then
echo "Usage (FreeBSD): sh test_factory_native.sh GAME_SRC OBJECT_DIR PROBE_CPP" >&2
exit 2
fi
cube_game_dir=$(cd "$1" && pwd)
cube_object_dir=$2
cube_probe_source=$3
case "$cube_object_dir" in ''|*/*|.|..) echo 'Expected a game-local object directory name' >&2; exit 2;; esac
case "$cube_probe_source" in /*) ;; *) echo 'Expected an absolute probe source path' >&2; exit 2;; esac
test -f "$cube_probe_source"
test -f "$cube_game_dir/$cube_object_dir/main.o"
test -f "$cube_game_dir/$cube_object_dir/port_cube_factory.o"
test -f "$cube_game_dir/$cube_object_dir/item_manager_idrange.o"
cube_probe_dir=$(mktemp -d /tmp/ch5-cube-factory.XXXXXX)
cube_cxx=${CXX:-clang++-devel}
echo "Offline probe evidence: $cube_probe_dir"
cd "$cube_game_dir"
"$cube_cxx" -g -Wall -w -O2 -m32 -pipe -std=c++2b -fexceptions -D_THREAD_SAFE -UNDEBUG \
-mtune=i686 -fstack-protector-all -I. -I../../../extern/include \
-I../../liblua/include -I../../libserverkey -I/usr/local/include -I/usr/include \
-c "$cube_probe_source" -o "$cube_probe_dir/probe.o" > "$cube_probe_dir/compile.log" 2>&1
objcopy --redefine-sym main=cubeUnusedGameMain "$cube_object_dir/main.o" "$cube_probe_dir/game-main-renamed.o"
set --
for cube_object in "$cube_object_dir"/*.o; do
case "$cube_object" in */main.o) ;; *) set -- "$@" "$cube_object" ;; esac
done
"$cube_cxx" -g -O2 -m32 -pipe -std=c++2b -fexceptions -D_THREAD_SAFE \
-mtune=i686 -fstack-protector-all -L../../../extern/lib -L../../libthecore/lib \
-L../../libpoly -L../../libsql -L../../libgame/lib -L../../liblua/lib \
-L../../libserverkey -L/usr/local/lib "$@" "$cube_probe_dir/probe.o" \
"$cube_probe_dir/game-main-renamed.o" -pthread -lm -lmd \
../../../extern/lib/libcryptopp.a ../../../extern/lib/libIL.a \
/usr/local/lib/mysql/libmysqlclient.a /usr/lib/libz.a /usr/lib/libssl.a /usr/lib/libcrypto.a \
-lthecore -lpoly -llua -llualib -lsql -lgame -lserverkey \
-o "$cube_probe_dir/probe" > "$cube_probe_dir/link.log" 2>&1
cd "$cube_probe_dir"
./probe > result.log 2>&1
cat result.log
sha256 probe probe.o game-main-renamed.o compile.log link.log result.log
+135
View File
@@ -0,0 +1,135 @@
#!/bin/sh
# Never connects to the production socket/server. Fresh no-defaults, socket-only
# instance, with its own data/pid/log files; preserve evidence after shutdown.
set -eu
repo_dir=$(CDPATH= cd -- "$(dirname -- "$0")/../.." && pwd)
test_dir=$(mktemp -d /tmp/ch5-cube-mysql.XXXXXX)
test_socket="$test_dir/mysql.sock"
printf 'Isolated Cube MySQL evidence: %s\n' "$test_dir"
mysql_install_db --no-defaults --basedir=/usr/local --datadir="$test_dir/data" --user=root > "$test_dir/install.log" 2>&1
mysqld_path=/usr/local/libexec/mysqld
"$mysqld_path" --no-defaults --basedir=/usr/local --datadir="$test_dir/data" --socket="$test_socket" \
--pid-file="$test_dir/mysql.pid" --log-error="$test_dir/mysql.log" --skip-networking --user=root \
--innodb-buffer-pool-size=32M --innodb-log-file-size=16M --key-buffer-size=8M --max-connections=10 \
> "$test_dir/console.log" 2>&1 &
cleanup() { mysqladmin --no-defaults --protocol=SOCKET --socket="$test_socket" -uroot shutdown >/dev/null 2>&1 || true; }
trap cleanup EXIT HUP INT TERM
ready=0
while [ "$ready" -lt 30 ]; do
if mysqladmin --no-defaults --protocol=SOCKET --socket="$test_socket" -uroot ping > /dev/null 2>&1; then break; fi
ready=$((ready+1)); sleep 1
done
mysqladmin --no-defaults --protocol=SOCKET --socket="$test_socket" -uroot ping
mysql --no-defaults --protocol=SOCKET --socket="$test_socket" -uroot -e 'CREATE DATABASE cube_batch_test'
c++ -std=c++17 -O1 -g -DPORT_CUBE_MYSQL -I"$repo_dir" $(mysql_config --cflags) \
"$repo_dir/tests/features/fixtures/cube_batch_probe.cpp" $(mysql_config --libs) -o "$test_dir/cube-batch"
"$test_dir/cube-batch" "$test_socket" base
mysql --no-defaults --protocol=SOCKET --socket="$test_socket" -uroot cube_batch_test < "$repo_dir/tools/cube/schema.sql"
"$test_dir/cube-batch" "$test_socket" > "$test_dir/result.log" 2>&1
"$test_dir/cube-batch" "$test_socket" fence >> "$test_dir/result.log" 2>&1
cat "$test_dir/result.log"
# Base/lifecycle probes above intentionally run with the addon absent. New
# optional schema and its exactly-once credit probes use this same isolated DB.
mysql --no-defaults --protocol=SOCKET --socket="$test_socket" -uroot cube_batch_test < "$repo_dir/tools/cube/gold-schema.sql"
c++ -std=c++17 -O1 -g -DPORT_CUBE_MYSQL -I"$repo_dir" $(mysql_config --cflags) \
"$repo_dir/tests/features/fixtures/cube_gold_probe.cpp" $(mysql_config --libs) -o "$test_dir/cube-gold"
"$test_dir/cube-gold" "$test_socket" > "$test_dir/gold-result.log" 2>&1
cat "$test_dir/gold-result.log"
c++ -std=c++17 -O1 -g -DPORT_CUBE_MYSQL -I"$repo_dir" $(mysql_config --cflags) \
"$repo_dir/tests/features/fixtures/cube_outbox_probe.cpp" $(mysql_config --libs) -o "$test_dir/cube-outbox"
"$test_dir/cube-outbox" "$test_socket" > "$test_dir/outbox-result.log" 2>&1
cat "$test_dir/outbox-result.log"
c++ -std=c++17 -O1 -g -DPORT_CUBE_MYSQL -I"$repo_dir" $(mysql_config --cflags) \
"$repo_dir/tests/features/fixtures/cube_source_probe.cpp" $(mysql_config --libs) -o "$test_dir/cube-source"
"$test_dir/cube-source" "$test_socket" > "$test_dir/source-result.log" 2>&1
cat "$test_dir/source-result.log"
mysql --no-defaults --protocol=SOCKET --socket="$test_socket" -uroot cube_batch_test < "$repo_dir/tools/cube/owner-schema.sql"
c++ -std=c++17 -O1 -g -DPORT_CUBE_MYSQL -I"$repo_dir" $(mysql_config --cflags) \
"$repo_dir/tests/features/fixtures/cube_owner_probe.cpp" $(mysql_config --libs) -o "$test_dir/cube-owner"
"$test_dir/cube-owner" "$test_socket" > "$test_dir/owner-result.log" 2>&1
cat "$test_dir/owner-result.log"
c++ -std=c++17 -O1 -g -DPORT_CUBE_MYSQL -I"$repo_dir" $(mysql_config --cflags) \
"$repo_dir/tests/features/fixtures/cube_image_probe.cpp" $(mysql_config --libs) -o "$test_dir/cube-image"
"$test_dir/cube-image" "$test_socket" > "$test_dir/image-result.log" 2>&1
cat "$test_dir/image-result.log"
mysql --no-defaults --protocol=SOCKET --socket="$test_socket" -uroot cube_batch_test < "$repo_dir/tools/cube/image-ack-schema.sql"
c++ -std=c++17 -O1 -g -DPORT_CUBE_MYSQL -I"$repo_dir" $(mysql_config --cflags) \
"$repo_dir/tests/features/fixtures/cube_image_ack_probe.cpp" $(mysql_config --libs) -o "$test_dir/cube-image-ack"
"$test_dir/cube-image-ack" "$test_socket" > "$test_dir/image-ack-result.log" 2>&1
cat "$test_dir/image-ack-result.log"
mysql --no-defaults --protocol=SOCKET --socket="$test_socket" -uroot cube_batch_test < "$repo_dir/tools/cube/release-schema.sql"
c++ -std=c++17 -O1 -g -DPORT_CUBE_MYSQL -I"$repo_dir" $(mysql_config --cflags) \
"$repo_dir/tests/features/fixtures/cube_release_probe.cpp" $(mysql_config --libs) -o "$test_dir/cube-release"
"$test_dir/cube-release" "$test_socket" > "$test_dir/release-result.log" 2>&1
cat "$test_dir/release-result.log"
c++ -std=c++17 -O1 -g -DPORT_CUBE_MYSQL -I"$repo_dir" $(mysql_config --cflags) \
"$repo_dir/tests/features/fixtures/cube_craft_probe.cpp" $(mysql_config --libs) -o "$test_dir/cube-craft"
"$test_dir/cube-craft" "$test_socket" > "$test_dir/craft-result.log" 2>&1
cat "$test_dir/craft-result.log"
# Only full source/build trees have the platform-matched internal libraries.
# Do not silently claim a worker test on the smaller SQL-store-only staging tree.
if [ "${CUBE_TEST_SQL_WORKER:-0}" = 1 ]; then
c++ -std=c++17 -O1 -g -pthread -I"$repo_dir" -I/usr/local/include \
"$repo_dir/tests/features/fixtures/sql_fence_mysql_probe.cpp" \
"$repo_dir/src/server/libsql/libsql.a" "$repo_dir/src/server/libthecore/lib/libthecore.a" \
$(mysql_config --libs) -o "$test_dir/sql-fence-worker"
"$test_dir/sql-fence-worker" "$test_socket" > "$test_dir/sql-worker.log" 2>&1
cat "$test_dir/sql-worker.log"
fi
# Separate legacy fixture database tests the actual explicit upgrade, including
# refusal to drop unresolved fences, partial-DDL retry and preserved history.
mysql --no-defaults --protocol=SOCKET --socket="$test_socket" -uroot <<'SQL'
CREATE DATABASE cube_upgrade_test;
USE cube_upgrade_test;
CREATE TABLE port_cube_version(id INT PRIMARY KEY,version INT) ENGINE=InnoDB;
INSERT INTO port_cube_version VALUES(1,1);
CREATE TABLE port_cube_requests(token VARCHAR(32) PRIMARY KEY,state ENUM('PREPARED','DONE'),body MEDIUMBLOB) ENGINE=InnoDB;
INSERT INTO port_cube_requests VALUES('history','DONE',X'010203');
CREATE TABLE port_cube_fences(pid INT PRIMARY KEY,account INT,epoch BIGINT,owner VARCHAR(32),request VARCHAR(32),phase ENUM('FROZEN','RESYNC') NOT NULL) ENGINE=InnoDB;
INSERT INTO port_cube_fences VALUES(1,1,1,'owner','request','FROZEN');
SQL
if mysql --no-defaults --protocol=SOCKET --socket="$test_socket" -uroot cube_upgrade_test < "$repo_dir/tools/cube/upgrade-v2.sql" > "$test_dir/upgrade-refused.log" 2>&1; then
echo 'ERROR: migration accepted unresolved v1 fence'; exit 1
fi
grep -F 'Resolve v1 fences before migration' "$test_dir/upgrade-refused.log" > /dev/null
mysql --no-defaults --protocol=SOCKET --socket="$test_socket" -uroot cube_upgrade_test -e "DELETE FROM port_cube_fences; INSERT INTO port_cube_requests VALUES('pending','PREPARED',X'00')"
if mysql --no-defaults --protocol=SOCKET --socket="$test_socket" -uroot cube_upgrade_test < "$repo_dir/tools/cube/upgrade-v2.sql" > "$test_dir/upgrade-pending-refused.log" 2>&1; then
echo 'ERROR: migration accepted prepared v1 batch'; exit 1
fi
grep -F 'Resolve v1 prepared batches before migration' "$test_dir/upgrade-pending-refused.log" > /dev/null
mysql --no-defaults --protocol=SOCKET --socket="$test_socket" -uroot cube_upgrade_test -e "DELETE FROM port_cube_requests WHERE token='pending'; ALTER TABLE port_cube_fences ADD body MEDIUMBLOB NOT NULL"
mysql --no-defaults --protocol=SOCKET --socket="$test_socket" -uroot cube_upgrade_test < "$repo_dir/tools/cube/upgrade-v2.sql"
mysql --no-defaults --protocol=SOCKET --socket="$test_socket" -uroot cube_upgrade_test < "$repo_dir/tools/cube/upgrade-v2.sql"
upgraded=$(mysql --no-defaults --protocol=SOCKET --socket="$test_socket" -uroot -N cube_upgrade_test -e "SELECT CONCAT(version,':',(SELECT HEX(body) FROM port_cube_requests WHERE token='history')) FROM port_cube_version WHERE id=1")
[ "$upgraded" = '2:010203' ]
echo 'PASS v1 upgrade: refuses unresolved state, retries partial DDL, retains history, idempotent v2'
# Separate old-addon fixture; never infer a closed source for preserved v1
# intentions. The new source table must remain empty after metadata migration.
mysql --no-defaults --protocol=SOCKET --socket="$test_socket" -uroot <<'SQL'
CREATE DATABASE cube_gold_upgrade_test;
USE cube_gold_upgrade_test;
CREATE TABLE port_cube_gold_version(id INT UNSIGNED PRIMARY KEY,version INT UNSIGNED NOT NULL) ENGINE=InnoDB;
INSERT INTO port_cube_gold_version VALUES(1,1);
CREATE TABLE port_cube_gold_intents(event CHAR(32) PRIMARY KEY,request CHAR(32) NOT NULL,seq INT UNSIGNED NOT NULL,account INT UNSIGNED NOT NULL,pid INT UNSIGNED NOT NULL,body VARBINARY(129) NOT NULL,state ENUM('QUEUED','APPLIED') NOT NULL,before_gold BIGINT UNSIGNED NOT NULL DEFAULT 0,after_gold BIGINT UNSIGNED NOT NULL DEFAULT 0,UNIQUE(request,seq),INDEX player_pending(pid,state)) ENGINE=InnoDB;
INSERT INTO port_cube_gold_intents VALUES('history','request',1,1,1,X'010203','QUEUED',0,0);
SQL
mysql --no-defaults --protocol=SOCKET --socket="$test_socket" -uroot cube_gold_upgrade_test < "$repo_dir/tools/cube/gold-upgrade-v2.sql"
mysql --no-defaults --protocol=SOCKET --socket="$test_socket" -uroot cube_gold_upgrade_test -e 'UPDATE port_cube_gold_version SET version=3'
if mysql --no-defaults --protocol=SOCKET --socket="$test_socket" -uroot cube_gold_upgrade_test < "$repo_dir/tools/cube/gold-upgrade-v2.sql" > "$test_dir/gold-upgrade-version-refused.log" 2>&1; then
echo 'ERROR gold migration accepted unknown version'; exit 1
fi
mysql --no-defaults --protocol=SOCKET --socket="$test_socket" -uroot cube_gold_upgrade_test -e 'UPDATE port_cube_gold_version SET version=1; ALTER TABLE port_cube_gold_sources DROP COLUMN manifest'
if mysql --no-defaults --protocol=SOCKET --socket="$test_socket" -uroot cube_gold_upgrade_test < "$repo_dir/tools/cube/gold-upgrade-v2.sql" > "$test_dir/gold-upgrade-partial-refused.log" 2>&1; then
echo 'ERROR gold migration accepted partial source metadata'; exit 1
fi
mysql --no-defaults --protocol=SOCKET --socket="$test_socket" -uroot cube_gold_upgrade_test -e 'ALTER TABLE port_cube_gold_sources ADD manifest VARBINARY(32772) NOT NULL; ALTER TABLE port_cube_gold_intents ENGINE=MyISAM'
if mysql --no-defaults --protocol=SOCKET --socket="$test_socket" -uroot cube_gold_upgrade_test < "$repo_dir/tools/cube/gold-upgrade-v2.sql" > "$test_dir/gold-upgrade-engine-refused.log" 2>&1; then
echo 'ERROR gold migration accepted nontransactional foundation'; exit 1
fi
mysql --no-defaults --protocol=SOCKET --socket="$test_socket" -uroot cube_gold_upgrade_test -e 'ALTER TABLE port_cube_gold_intents ENGINE=InnoDB'
mysql --no-defaults --protocol=SOCKET --socket="$test_socket" -uroot cube_gold_upgrade_test < "$repo_dir/tools/cube/gold-upgrade-v2.sql"
mysql --no-defaults --protocol=SOCKET --socket="$test_socket" -uroot cube_gold_upgrade_test < "$repo_dir/tools/cube/gold-upgrade-v2.sql"
gold_upgraded=$(mysql --no-defaults --protocol=SOCKET --socket="$test_socket" -uroot -N cube_gold_upgrade_test -e "SELECT CONCAT(version,':',(SELECT HEX(body) FROM port_cube_gold_intents WHERE event='history'),':',(SELECT COUNT(*) FROM port_cube_gold_sources)) FROM port_cube_gold_version WHERE id=1")
[ "$gold_upgraded" = '2:010203:0' ]
echo 'PASS gold-addon v1->v2 migration: history retained, no manufactured closure, unknown/partial/MyISAM refused, explicit repair/retry and idempotence'
printf 'PASS; dedicated instance will shut down, data retained at %s\n' "$test_dir"
+40
View File
@@ -0,0 +1,40 @@
-- Explicit maintenance migration for the unreleased v1 candidate only.
-- Requires a selected unsuffixed player database and coordinated shutdown.
-- Never manufactures a body/owner for an unresolved v1 fence or prepared batch.
DELIMITER //
DROP PROCEDURE IF EXISTS port_cube_upgrade_v2//
CREATE PROCEDURE port_cube_upgrade_v2()
cube_migration: BEGIN
DECLARE current_version INT DEFAULT 0;
DECLARE present INT DEFAULT 0;
SELECT version INTO current_version FROM port_cube_version WHERE id=1;
IF current_version=2 THEN
SELECT COUNT(*) INTO present FROM information_schema.columns WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='port_cube_fences' AND COLUMN_NAME IN ('body','image','drain_state');
IF present<>3 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='Cube v2 metadata is incomplete; retain quarantine'; END IF;
SELECT COUNT(*) INTO present FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='port_cube_item_fences';
IF present<>1 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='Cube v2 item fences missing; retain quarantine'; END IF;
LEAVE cube_migration;
END IF;
IF current_version<>1 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='Expected Cube candidate version 1'; END IF;
SELECT COUNT(*) INTO present FROM port_cube_fences;
IF present<>0 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='Resolve v1 fences before migration; no automatic ownership reset'; END IF;
SELECT COUNT(*) INTO present FROM port_cube_requests WHERE state='PREPARED';
IF present<>0 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='Resolve v1 prepared batches before migration'; END IF;
ALTER TABLE port_cube_fences MODIFY phase ENUM('DRAINING','FROZEN','ABORTED','RESYNC','RELEASED') NOT NULL;
SELECT COUNT(*) INTO present FROM information_schema.columns WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='port_cube_fences' AND COLUMN_NAME='body';
IF present=0 THEN ALTER TABLE port_cube_fences ADD body MEDIUMBLOB NOT NULL; END IF;
SELECT COUNT(*) INTO present FROM information_schema.columns WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='port_cube_fences' AND COLUMN_NAME='image';
IF present=0 THEN ALTER TABLE port_cube_fences ADD image MEDIUMBLOB NOT NULL; END IF;
SELECT COUNT(*) INTO present FROM information_schema.columns WHERE TABLE_SCHEMA=DATABASE() AND TABLE_NAME='port_cube_fences' AND COLUMN_NAME='drain_state';
IF present=0 THEN ALTER TABLE port_cube_fences ADD drain_state TINYINT UNSIGNED NOT NULL DEFAULT 0; END IF;
CREATE TABLE IF NOT EXISTS port_cube_item_fences (
id INT UNSIGNED PRIMARY KEY, pid INT UNSIGNED NOT NULL,
epoch BIGINT UNSIGNED NOT NULL,
request CHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL,
INDEX player_fence(pid,epoch)
) ENGINE=InnoDB;
UPDATE port_cube_version SET version=2 WHERE id=1 AND version=1;
END//
CALL port_cube_upgrade_v2()//
DROP PROCEDURE port_cube_upgrade_v2//
DELIMITER ;