feat(server): save economy hardening and CH5 continuation work

This commit is contained in:
shen
2026-10-22 06:22:23 -07:00
parent c979b53762
commit 5b7442ea37
142 changed files with 5850 additions and 1682 deletions
+16
View File
@@ -67,3 +67,19 @@ coins, orders, awards and items were removed; its one test sale was subtracted w
resetting other sales. Existing players received no test currency. db/auth/13 cores remained
healthy after cleanup. macOS release bundle and connected Android client's APK/resources
were updated; Android in-game purchase acceptance is not claimed by this release.
## 2026-10-20 safety fixes (not deployed)
`build_isolated.py` now requires a reviewed `--dependency-manifest`: JSON with `source_sha256` from `source_digest(source)` and `archives` mapping every source-relative `.a` path to SHA-256. The manifest binds reviewed dependency provenance to the exact server/extern sources; generating hashes alone does not certify provenance. FreeBSD is required. A fresh `game-release`, `db-release`, `game-warnings` or `db-warnings` directory is created beneath `--output`; reusing a target/mode directory fails. Source/dependency mismatches also fail. `--warnings` removes `-w`, enables format/conversion diagnostics and makes format/narrowing warnings errors. Build evidence and binary hashes are written to the new directory. FreeBSD validation remains required.
The wear40 planner now binds database/server identity, a persistent target UUID, item identity/state, quickslots and a plan checksum. `--apply` requires `--offline --backup-id ID`. Reuse the exact saved v2 plan for interrupted runs; old unbound plans are rejected. A completed marker is rechecked against actual data and schema; corrupt extra is rejected before mutation. Backups and stopping writers remain operational prerequisites, not facts inferred from command success.
Offline shop mutation and startup expiry cleanup are explicitly closed in game/db until durable custody/payment/delivery orders and crash recovery are implemented and accepted. Stored assets are preserved. This closure is a containment measure, not completion of offline trading.
### Pending-reward journal maintenance
`PointJournal` keeps its own durable pending set. Startup recovery and the retry event compact a log above 1 MiB when enough completed history can be removed. Compaction retains every pending token/request/time, writes a new file exclusively, fsyncs it, atomically renames it and fsyncs the directory. It does not cap the queue at 4096 entries. Do not pass a subset of runtime requests to replace the journal; there is deliberately no such API.
Keep the `.lock` sidecar in place for the writer's lifetime. Stop old binaries before upgrading a process that uses the same journal path; mixed old/new concurrent writers are unsupported. An I/O error pauses issuance, retaining a complete recovery source; fix the storage problem and preserve journal evidence before restarting. A corrupt log is not automatically truncated or compacted. These changes have standalone fault tests, including ELF32 probes, and do not replace real database/process-crash acceptance.
Strict builds also promote `-Wshorten-64-to-32` to an error. The broader strict warning gate is still failing on legacy code; see the maintenance evidence for the exact blockers.
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env python3
"""Check the exact remaining original offers and their staged dependencies. Never enables offers."""
import argparse,collections,hashlib,json
from pathlib import Path
ROOT=Path(__file__).resolve().parents[2]
CLIENT=ROOT.parent/'metin2-client'
def feature(row):
v=row['vnum'];t=row['source_type'];sub=row['source_subtype']
if v in (53998,53999):return 'costume_attribute_removal'
if v in (100001,100002):return 'dragon_soul_charge'
if v in (39063,39064):return 'gaya_consumables'
if v==71097:return 'dragon_soul_attribute_change'
if v==85009:return 'sash_detachment'
if v==6884:return 'rarity_conversion'
if v==72319:return 'offline_shop_key'
if v==72320:return 'storage_unlock'
if v==25159:return 'monthly_battlepass_ticket'
if v in (72067,72068):return 'rare_attribute_support'
if v in range(25163,25170):return 'dungeon_tickets'
if v==20059:return 'appearance_exchange_ticket'
if t=='ITEM_COSTUME':return sub.lower()
if t=='ITEM_PET':return 'growing_pet_'+sub.removeprefix('PET_').lower()
if t=='ITEM_GIFTBOX':return 'giftbox_reward_chain'
if t=='ITEM_TREASURE_KEY':return 'treasure_key_reward_chain'
if t=='ITEM_MATERIAL':return 'dragon_soul_refine_material'
if t=='ITEM_USE' and sub=='USE_CHANGE_ATTRIBUTE':return 'costume_fixed_attribute'
if t=='ITEM_UNIQUE':return 'unique_item_'+str(v)
if t=='ITEM_USE' and sub=='USE_AFFECT':return 'affect_consumable'
return 'quest_item_'+str(v)
def audit(staged=None,assets=None):
data=ROOT/'data/ava2-itemshop'
ledger=json.loads((data/'completion-168.json').read_text());remaining=ledger['products']
baseline=json.loads((data/'verified-products.json').read_text())['products']
originals={}
for line in (data/'original-products.tsv').read_text().splitlines():
c=line.split('\t');key=int(c[0]);assert key not in originals,'duplicate original id';originals[key]=(int(c[3]),int(c[4]))
ids=[r['id'] for r in remaining];assert len(ids)==len(set(ids))==ledger['count']==168,'remaining identity/count changed'
baseids={r['id'] for r in baseline};assert len(baseids)==49 and not baseids.intersection(ids)
assert baseids.union(ids)==set(originals),'original catalogue not partitioned exactly'
rows={}
if staged:
for line in Path(staged).read_bytes().splitlines():
c=line.split(b'\t')
if c[0].isdigit():
v=int(c[0]);assert v not in rows,'duplicate staged vnum';rows[v]=[x.decode('gbk') for x in c]
# Resolve the exact original icon/model mapping; a missing explicit mapping is
# shown as missing rather than guessed to be a working model.
items={}
for line in (ROOT.parent/'AVA2/1. Client DEV/pack_maker/locale/locale/es/item_list.txt').read_text(encoding='latin1').splitlines():
c=[x.strip().lower().replace('\\','/') for x in line.split('\t') if x.strip()]
if c and c[0].isdigit():items[int(c[0])]=c
result=[]
for r in remaining:
assert (r['vnum'],r['original_price'])==originals[r['id']],'offer identity or original price changed'
evidence=r.get('evidence',[])
for name in evidence:
p=Path(name);p=p if p.is_absolute() else ROOT.parent/p
assert p.is_file(),'missing evidence source: '+name
v=r['vnum'];proto=rows.get(v);entry=items.get(v,[str(v),'etc','icon/item/%05d.tga'%v]);paths=entry[2:4]
ready=bool(proto and proto[2]!='ITEM_NONE' and proto[2:4]==[r['source_type'],r['source_subtype']])
# QUEST_NONE/NONE are aliases for the zero subtype, not distinct handlers.
if proto and r['source_type']=='ITEM_QUEST':ready=proto[2]=='ITEM_QUEST' and proto[3] in ('0','NONE','QUEST_NONE')
result.append({'id':r['id'],'vnum':v,'original_price':r['original_price'],'feature':feature(r),'status':r['status'],'prototype_staged':ready if staged else None,'staged_type':proto[2:4] if proto else None,'direct_asset_paths':paths,'missing_direct_assets':[p for p in paths if not (Path(assets)/p).is_file()] if assets else None,'live_acceptance':'NOT_VERIFIED','evidence_sources':evidence})
return {'count':168,'baseline_count':49,'original_count':len(originals),'scope':'dependency inventory; source paths and direct assets do not prove working gameplay, full resource closure or live acceptance','ledger_sha256':hashlib.sha256((data/'completion-168.json').read_bytes()).hexdigest(),'groups':dict(sorted(collections.Counter(r['feature'] for r in result).items())),'statuses':dict(collections.Counter(r['status'] for r in result)),'prototype_staged_count':sum(r['prototype_staged'] is True for r in result) if staged else None,'products':result}
def main():
p=argparse.ArgumentParser(description=__doc__);p.add_argument('--staged-server-tsv',type=Path);p.add_argument('--assets',type=Path);p.add_argument('--output',type=Path,required=True);a=p.parse_args()
report=audit(a.staged_server_tsv,a.assets);a.output.parent.mkdir(parents=True,exist_ok=True);a.output.write_text(json.dumps(report,ensure_ascii=False,indent=2)+'\n');print(json.dumps({k:report[k] for k in ('count','groups','statuses','prototype_staged_count')},ensure_ascii=False))
if __name__=='__main__':main()
+87 -20
View File
@@ -1,29 +1,96 @@
#!/usr/bin/env python3
"""Build game/db without either Makefile's production installation default."""
"""Build a bound source snapshot in fresh per-target directories; never install it."""
import argparse
import hashlib
import json
from pathlib import Path
import platform
import re
import shutil
import subprocess
import sys
def digest(path):
return hashlib.sha256(path.read_bytes()).hexdigest()
def source_digest(source):
h=hashlib.sha256()
for part in ('server','extern'):
for path in sorted((source/part).rglob('*')):
if not path.is_file() or any(p in ('.obj','OBJDIR','obj','.git') for p in path.parts):continue
if path.suffix in ('.o','.a','.so','.d'):continue
h.update(str(path.relative_to(source)).encode()+b'\0'+path.read_bytes()+b'\0')
return h.hexdigest()
def validate_dependencies(source, manifest, revision):
if manifest.get('source_sha256')!=revision:raise ValueError('dependency manifest source mismatch')
archives=manifest.get('archives',{})
actual={str(p.relative_to(source)):digest(p) for p in source.rglob('*.a')}
if not actual or archives!=actual:raise ValueError('all dependency archives must match the reviewed source-bound manifest')
for name, expected in manifest.get('system_archives',{}).items():
dependency=Path(name)
if not dependency.is_absolute() or not dependency.is_file() or digest(dependency)!=expected:
raise ValueError('system dependency archive mismatch: '+name)
def prepare(source, output, target, dependency_manifest, warnings=False):
production=Path('/usr/metin2/server')
if output==production or production in output.parents or source==output or source in output.parents:
raise ValueError('output must be outside source and production trees')
revision=source_digest(source)
validate_dependencies(source,dependency_manifest,revision)
output.mkdir(parents=True,exist_ok=True)
state=output/'source-binding.json'
binding={'source':str(source),'sha256':revision,'dependencies':dependency_manifest}
if state.exists():
if json.loads(state.read_text())!=binding:raise ValueError('output belongs to another source/dependency set')
elif any(output.iterdir()):raise ValueError('unbound output must be empty')
else:state.write_text(json.dumps(binding,indent=2)+'\n')
run=output/(target+('-warnings' if warnings else '-release'))
run.mkdir() # Never silently reuse objects, even after a failed build.
snapshot=run/'source'
snapshot.mkdir()
for name in ('server','extern'):
shutil.copytree(source/name,snapshot/name,ignore=shutil.ignore_patterns('*.o','.obj','OBJDIR','*.d'))
for target_dir in (snapshot/'server/game/src',snapshot/'server/db/src'):
makefile=target_dir/'Makefile'
text=makefile.read_bytes().decode('latin1')
# Depend paths must follow this target's OBJDIR, not the original checkout.
text=re.sub(r'(?<![\w])(?:\.obj|OBJDIR)/', '$(OBJDIR)/',text)
if warnings:
text=re.sub(r'(?<!\S)-w(?!\S)','',text)
text+='\nCFLAGS += -Wall -Wextra -Wformat=2 -Wconversion -Wsign-conversion -Werror=format -Werror=implicit-int-conversion -Werror=shorten-64-to-32\n'
makefile.write_bytes(text.encode('latin1'))
for name in ('bin','work','obj'):(run/name).mkdir()
return run,snapshot,revision
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument('--source', type=Path, required=True, help='directory containing server/ and extern/')
p.add_argument('--output', type=Path, required=True)
p.add_argument('--target', choices=['game', 'db'], required=True)
p.add_argument('--jobs', type=int, default=1)
a = p.parse_args()
source, output = a.source.resolve(), a.output.resolve()
for destination in (output, (output/'bin').resolve(), (output/'work').resolve()):
if destination == Path('/usr/metin2/server') or Path('/usr/metin2/server') in destination.parents:
p.error('build outputs must not be inside the production server tree')
for name in ('bin', 'work', 'obj-'+a.target):
(output/name).mkdir(parents=True, exist_ok=True)
# DB uses DBDIR, game uses GAMEDIR. Always override both, even when building one target.
subprocess.run(['gmake', '-j%d' % max(1, a.jobs), 'BINDIR='+str(output/'work'),
'GAMEDIR='+str(output/'bin'), 'DBDIR='+str(output/'bin'),
'OBJDIR='+str(output/('obj-'+a.target))],
cwd=source/'server'/a.target/'src', check=True)
p=argparse.ArgumentParser(description=__doc__)
p.add_argument('--source',type=Path,required=True)
p.add_argument('--output',type=Path,required=True)
p.add_argument('--target',choices=['game','db'],required=True)
p.add_argument('--jobs',type=int,default=1)
p.add_argument('--dependency-manifest',type=Path,required=True,help='reviewed archive hashes bound to source_sha256')
p.add_argument('--warnings',action='store_true')
a=p.parse_args()
if platform.system()!='FreeBSD':p.error('FreeBSD target build requires a FreeBSD host (not PASS)')
try:run,snapshot,revision=prepare(a.source.resolve(),a.output.resolve(),a.target,json.loads(a.dependency_manifest.read_text()),a.warnings)
except (ValueError,OSError) as e:p.error(str(e))
cmd=['gmake','-j%d'%max(1,a.jobs),'BINDIR='+str(run/'work'),'GAMEDIR='+str(run/'bin'),'DBDIR='+str(run/'bin'),'OBJDIR='+str(run/'obj')]
record={'source_sha256':revision,'command':cmd,'warnings':a.warnings,'status':'FAIL'}
try:
record['compiler']=subprocess.check_output(['clang++-devel','--version'],text=True)
with (run/'build.log').open('w') as log:
subprocess.run(cmd,cwd=snapshot/'server'/a.target/'src',stdout=log,stderr=subprocess.STDOUT,check=True)
binary=run/'bin'/a.target
if not binary.is_file():raise RuntimeError('missing binary')
record.update(status='PASS',binary=str(binary),binary_sha256=digest(binary))
finally:(run/'result.json').write_text(json.dumps(record,indent=2)+'\n')
print(a.target+' PASS')
if __name__ == '__main__':
main()
if __name__=='__main__':main()
+102 -40
View File
@@ -5,12 +5,16 @@ The saved plan contains exact row IDs and before/after values. Reapplying that s
is safe after interruption; never regenerate a plan from partially migrated data.
"""
import argparse
import hashlib
import os
import json
from pathlib import Path
import re
import subprocess
import tempfile
NAME = 'ava2-shop-wear-40'
STATE_SQL="SHA2(CONCAT_WS(':',socket0,socket1,socket2,"+','.join('attrtype%d,attrvalue%d'%(i,i) for i in range(7))+"),256)"
def quickslots(blob):
@@ -27,12 +31,61 @@ def quickslots(blob):
return bytes(output)
def canonical(value):
return json.dumps(value, sort_keys=True, separators=(',', ':')).encode()
def plan_digest(plan):
return hashlib.sha256(canonical({k:v for k,v in plan.items() if k != 'sha256'})).hexdigest()
def validate_plan(plan, identity):
if plan.get('version') != 2 or plan.get('target') != identity:
raise RuntimeError('Stale/foreign migration plan; target identity must match exactly')
if plan.get('sha256') != plan_digest(plan):
raise RuntimeError('Migration plan checksum mismatch')
for table,pid,old,new in plan['quickslots']:
if table not in ('player','player_deleted') or quickslots(bytes.fromhex(old)).hex()!=new:
raise RuntimeError('Invalid quickslot plan')
ids = [row[0] for row in plan['items']]
if len(ids) != len(set(ids)):
raise RuntimeError('Duplicate item IDs in plan')
for row in plan['items']:
if not re.fullmatch('[a-fA-F0-9]{64}',plan.get('item_state',{}).get(str(row[0]),'')):
raise RuntimeError('Missing full item state binding')
if len(row) != 8 or row[3] != row[2]+8 or row[1] not in ('EQUIPMENT','INVENTORY'):
raise RuntimeError('Invalid item migration record')
def validate_extra_schema(columns):
# SHOW COLUMNS: name,type,null,key,default,extra
extra = next((c for c in columns if c[0]=='port_extra'), None)
if extra is not None and (extra[1].lower()!='varbinary(69)' or extra[2]!='NO' or extra[4]!=''):
raise RuntimeError('item.port_extra must be VARBINARY(69) NOT NULL DEFAULT empty')
return extra is not None
def atomic_json(path, value):
descriptor,name=tempfile.mkstemp(prefix=path.name+'.',suffix='.tmp',dir=path.parent)
temporary=Path(name)
with os.fdopen(descriptor,'w') as out:
out.write(json.dumps(value,indent=2)+'\n');out.flush();os.fsync(out.fileno())
os.replace(temporary, path)
fd=os.open(path.parent,os.O_RDONLY)
try:os.fsync(fd)
finally:os.close(fd)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--player', required=True)
parser.add_argument('--plan', type=Path, required=True)
parser.add_argument('--apply', action='store_true')
parser.add_argument('--offline', action='store_true', help='confirm ALL target writers stopped')
parser.add_argument('--backup-id', help='verified backup identity required for apply')
args = parser.parse_args()
if args.apply and (not args.offline or not args.backup_id):
parser.error('--apply requires --offline and --backup-id')
if not re.fullmatch('[A-Za-z0-9_]+', args.player):
parser.error('Invalid database name')
@@ -41,55 +94,64 @@ def main():
text=True, capture_output=True, check=True)
return [line.split('\t') for line in result.stdout.splitlines()]
sql('CREATE TABLE IF NOT EXISTS mt_migration_target(id TINYINT PRIMARY KEY, identity CHAR(36) NOT NULL);')
sql('INSERT IGNORE INTO mt_migration_target(id,identity) VALUES(1,UUID());')
identity = sql('SELECT DATABASE(),@@hostname,@@port,@@server_id,identity FROM mt_migration_target WHERE id=1;')
if len(identity)!=1:raise RuntimeError('Cannot bind target identity')
columns=sql('SHOW COLUMNS FROM item;')
has_extra=validate_extra_schema(columns)
if has_extra:
bad=sql("SELECT id FROM item WHERE OCTET_LENGTH(port_extra) NOT IN (0,69) OR (OCTET_LENGTH(port_extra)=69 AND SUBSTRING(port_extra,69,1)<>X'00');")
if bad:raise RuntimeError('Corrupt extra: quarantine original rows before migration: '+repr(bad[:20]))
sql('CREATE TABLE IF NOT EXISTS mt_migration(name VARCHAR(64) PRIMARY KEY,done DATETIME);')
if sql("SELECT name FROM mt_migration WHERE name='%s';" % NAME):
print(NAME + ': already applied')
return
markers=sql("SELECT name FROM mt_migration WHERE name='%s';" % NAME)
if markers and not has_extra:raise RuntimeError('Completed marker has missing extra schema')
if args.plan.exists():
plan = json.loads(args.plan.read_text())
if plan['schema'] != args.player:
raise RuntimeError('Plan belongs to another database')
plan=json.loads(args.plan.read_text());validate_plan(plan,identity[0])
else:
# Equipped DS cells are relative; belt cells in INVENTORY are absolute.
bad = sql("SELECT i.id FROM item i LEFT JOIN item_proto p ON i.vnum=p.vnum "
"WHERE i.window='EQUIPMENT' AND i.pos>=32 AND "
"(i.pos>43 OR p.type IS NULL OR p.type NOT IN (29,30));")
if bad:
raise RuntimeError('Unexpected occupied extended equipment cells; inspect before migration')
items = sql("SELECT id,pos FROM item WHERE (window='EQUIPMENT' AND pos BETWEEN 32 AND 43) "
"OR (window='INVENTORY' AND pos BETWEEN 287 AND 302) ORDER BY pos DESC;")
plan = {'schema': args.player, 'items': [[int(i), int(p), int(p)+8] for i, p in items],
'quickslots': []}
for table in ('player', 'player_deleted'):
for pid, value in sql('SELECT id,HEX(quickslot) FROM `%s`;' % table):
old = bytes.fromhex(value)
new = quickslots(old)
if old != new:
plan['quickslots'].append([table, int(pid), old.hex(), new.hex()])
args.plan.parent.mkdir(parents=True, exist_ok=True)
args.plan.write_text(json.dumps(plan, indent=2)+'\n')
args.plan.chmod(0o600)
if markers:raise RuntimeError('Completed marker has no bound plan; inspect instead of trusting marker')
bad=sql("SELECT i.id FROM item i LEFT JOIN item_proto p ON i.vnum=p.vnum WHERE i.window='EQUIPMENT' AND i.pos>=32 AND (i.pos>43 OR p.type IS NULL OR p.type NOT IN (29,30));")
if bad:raise RuntimeError('Unexpected equipment cells; inspect before migration')
rows=sql("SELECT id,window,pos,vnum,owner_id,count,%s,%s FROM item WHERE (window='EQUIPMENT' AND pos BETWEEN 32 AND 43) OR (window='INVENTORY' AND pos BETWEEN 287 AND 302) ORDER BY pos DESC;" % ('HEX(port_extra)' if has_extra else "''",STATE_SQL))
plan={'version':2,'schema':args.player,'target':identity[0], 'items':[], 'quickslots':[], 'item_state':{}}
for item,window,pos,vnum,owner,count,extra,state in rows:
plan['item_state'][item]=state
plan['items'].append([int(item),window,int(pos),int(pos)+8,int(vnum),int(owner),int(count),extra])
for table in ('player','player_deleted'):
for pid,value in sql('SELECT id,HEX(quickslot) FROM `%s`;' % table):
old=bytes.fromhex(value);new=quickslots(old)
if old!=new:plan['quickslots'].append([table,int(pid),old.hex(),new.hex()])
plan['sha256']=plan_digest(plan);args.plan.parent.mkdir(parents=True,exist_ok=True);atomic_json(args.plan,plan)
validate_plan(plan,identity[0])
print('planned items=%d quickslots=%d' % (len(plan['items']), len(plan['quickslots'])))
if not args.apply:
return
# Every update is conditional on its original value, allowing safe saved-plan replay.
for item, old, new in plan['items']:
row = sql('SELECT pos FROM item WHERE id=%d;' % item)
if row not in ([[str(old)]], [[str(new)]]):
raise RuntimeError('Item changed since planning; cores/db must stay stopped')
sql('UPDATE item SET pos=%d WHERE id=%d AND pos=%d;' % (new, item, old))
# Validate ALL rows before mutating any of them. Resume permits only each bound old/new state.
for item,window,old,new,vnum,owner,count,extra in plan['items']:
row=sql("SELECT window,pos,vnum,owner_id,count,%s,%s FROM item WHERE id=%d;" % ('HEX(port_extra)' if has_extra else "''",STATE_SQL,item))
expected=[window,str(new if markers else old),str(vnum),str(owner),str(count),extra,plan['item_state'][str(item)]]
alternative=list(expected);alternative[1]=str(new)
if len(row)!=1 or row[0] not in (expected,alternative):raise RuntimeError('Item identity/state differs from bound plan: '+str(item))
for table, pid, old, new in plan['quickslots']:
row = sql('SELECT HEX(quickslot) FROM `%s` WHERE id=%d;' % (table, pid))
if not row or row[0][0].lower() not in (old, new):
if not row or row[0][0].lower() not in ((new,) if markers else (old,new)):
raise RuntimeError('Quickslot changed since planning')
if not args.apply:return
if not has_extra:
sql("ALTER TABLE item ADD port_extra VARBINARY(69) NOT NULL DEFAULT ''; ")
for item,window,old,new,vnum,owner,count,extra in plan['items']:
if markers:continue
sql("UPDATE item SET pos=%d WHERE id=%d AND window='%s' AND pos=%d AND vnum=%d AND owner_id=%d AND count=%d;" % (new,item,window,old,vnum,owner,count))
for table,pid,old,new in plan['quickslots']:
sql("UPDATE `%s` SET quickslot=X'%s' WHERE id=%d AND HEX(quickslot)='%s';" %
(table, new, pid, old.upper()))
columns = sql("SELECT COLUMN_NAME FROM information_schema.columns WHERE TABLE_SCHEMA=DATABASE() "
"AND TABLE_NAME='item' AND COLUMN_NAME='port_extra';")
if not columns:
sql("ALTER TABLE item ADD port_extra VARBINARY(69) NOT NULL DEFAULT ''; ")
sql("INSERT INTO mt_migration(name,done) VALUES('%s',NOW());" % NAME)
print(NAME + ': applied; retain the saved plan for recovery')
# A completion marker is accepted only after re-reading every migrated target value.
for item,window,old,new,vnum,owner,count,extra in plan['items']:
if sql('SELECT pos FROM item WHERE id=%d;' % item)!=[[str(new)]]:raise RuntimeError('Item post-validation failed')
for table,pid,old,new in plan['quickslots']:
if sql('SELECT LOWER(HEX(quickslot)) FROM `%s` WHERE id=%d;' % (table,pid))!=[[new]]:raise RuntimeError('Quickslot post-validation failed')
validate_extra_schema(sql('SHOW COLUMNS FROM item;'))
sql("INSERT IGNORE INTO mt_migration(name,done) VALUES('%s',NOW());" % NAME)
atomic_json(args.plan.with_name(args.plan.name+'.receipt.json'),{'plan_sha256':plan['sha256'],'target':identity[0],'backup_id':args.backup_id,'verified':True})
print(NAME+': post-validated; preserve plan, receipt and backup')
if __name__ == '__main__':
+157
View File
@@ -0,0 +1,157 @@
# Durable economy transactions
This is the replacement DB transaction path for offline sales and Gaya. It is
implemented separately from the unsafe legacy offline-shop protocol. Do not
change `PortOfflineShopEconomyReady()` to enable that old protocol.
## Current entry points
- `/mt_economy status [PAGE]` lists recent results, public/owned listings,
buyer orders and available proceeds. Pages start at zero.
- `/mt_economy list CELL PRICE` places the complete inventory stack in custody.
- `/mt_economy buy LISTING PRICE` reserves that listing and holds the price in
its order. An outdated price or another buyer's reservation is rejected.
- `/mt_economy refund ORDER` returns the held price and reopens the listing.
- `/mt_economy claim ORDER` moves the original item ID into the buyer account's
mall storage and credits the seller's proceeds in the same transaction.
- `/mt_economy cancel LISTING` returns an OPEN listing to its owner's mall.
- `/mt_economy withdraw` transfers available proceeds into character gold.
- `/mt_economy gaya_retire` retires a migrated catalogue after its Gaya
balance reaches zero and active listings, refundable orders and proceeds are
settled. It permanently disables this character's Gaya catalogue so the native
character deletion flow can proceed. It uses the same logout/save fences.
Positive balances are refused, never silently discarded or refunded.
- Existing `/gem buy`, refresh and expansion commands/items submit DB intents.
Gaya purchases deliver stable item IDs to account mall storage. Paid refresh
and expansion consume their item in the same transaction as their effect.
All mutating requests close the game connection through the normal logout
path. Reconnect and select the same character: DB evicts its caches, completes
the queued SQL writes, settles the durable intent, and resumes character load.
No in-game gold, Gaya, inventory or paid catalogue change happens before this
handoff. `status` and the new `ui` query do not disconnect. The native client now
loads the original AVA2 offline window through its inventory button/F8 and routes
confirmed actions to this backend. Buying reserves an order; claiming is a
separate action that delivers to mall and credits the seller. Real connected
cross-channel/mobile acceptance is still pending. World NPC creation and legacy
NPC-to-new-seller mapping are not implemented by this window adapter.
The window uses `/mt_economy ui MODE PAGE SEQ OWNER TOKEN` (mode 0 public,
1 owned, 2 READY orders; zero-based pages of 20). A consistent read transaction
builds and validates complete `MTECON1 begin/row/meta/result/end` command frames
before sending any. Read failures return `MTECON1 error SEQ storage`.
`/mt_economy act TOKEN OP ...` preserves a nonzero random 32-hex receipt for
list/buy/claim/refund/cancel/withdraw. List additionally carries expected vnum
and count. Account, character and wallet fields always come from the session;
exact-token receipt queries are account/character scoped. Immediate rejection
returns `MTECON1 action_error TOKEN rejected`. UiStatus=12 cannot be enqueued
as a mutation; schema version and internal record sizes are unchanged.
An order remains READY until claimed or refunded; there is no automatic order
expiry. A full mall or gold/proceeds limit leaves the order/custody intact and
allows a later request. Seller proceeds become available after successful
delivery, rather than while the buyer can still refund the reservation.
## Storage and ownership
| Storage | Authority |
| --- | --- |
| `item` | Normal inventory, equipment, safebox and mall item rows |
| `port_economy_custody` | Exact original item row while a listing is OPEN/RESERVED |
| `port_economy_listings` | Seller, immutable price and current listing/order state |
| `port_economy_orders` | Held buyer payment and READY/CLAIMED/REFUNDED result |
| `port_economy_credit` | Seller proceeds awaiting withdrawal |
| `port_economy_requests` / `pending` | Immutable token/body, result and one pending intent per character |
| `port_economy_item_reservations` | Durable high-water marks for allocated Gaya reward IDs, including aborted intents |
| `port_economy_gaya` | Catalogue generation, deadline and all 27 offers |
| `player.gold` / `quest` gem flags | Character wallet and unlocked slots, changed only after logout/fencing |
The old `offline_shop_npc`, `offline_shop_item`, `offline_shop_log` and
`player.shop_money` are preserved. They are **not imported or treated as new
orders**. Their old writes did not record enough evidence to infer missing
buyer refunds or delivery safely. Existing production custody and balances
must be reconciled against actual item IDs, owners, statuses and logs before
any live migration. This batch has not modified or inspected production assets.
Custody uses an exact `CREATE TABLE ... LIKE item` layout; transactions copy all
stored columns, retaining sockets, attributes, extra state and the original ID.
Game item saves/destruction cannot write a custodial ID. ID range startup reads
the maximum across normal items, custody and durable reward reservations, so a
restart cannot reissue an escrowed or pending reward ID. Unmigrated legacy
`offline_shop_item` IDs are also reserved when that table exists, even before
the new economy schema is installed; lookup errors refuse range allocation. Reservation tombstones
must not be casually deleted during cleanup or rollback.
Gaya imports an existing validated local catalogue on its first economic
transaction. Its committed SQL catalogue then supersedes the local file and
does not depend on that file/directory being writable. Balance, reward rows and
offer/generation commit together; refresh/expansion effects and consumables do
likewise. The normal quest-save path remains a wallet mirror during play and is
fully drained before settlement. Wallet snapshots that do not match persisted
values are rejected, rather than spending an older balance.
Native character deletion is refused while there is pending work, active
custody, a refundable order, unclaimed proceeds or an active migrated Gaya
catalogue. Explicit `gaya_retire` preserves all offers, deadline and paid slots;
the reserved generation `9223372036854775807` marks the retained SQL row retired.
The immutable request records the original generation in its result reference.
Repeated retirement is harmless. Buy, refresh, expansion and local-file fallback
cannot reactivate the retired catalogue. Deletion remains blocked if a quest
writer later adds a nonzero Gaya balance. Spend Gaya and settle external assets
before retiring; this is not a balance forfeiture or currency conversion feature.
Use coordinated game/DB binaries that understand operation 11 and the terminal
generation. Existing table version 1 and request record sizes stay unchanged;
old pending requests remain readable. No additional startup DDL is required.
## Installation and recovery boundaries
`schema.sql` is an explicit, reviewable migration, never startup DDL. It supports
the unsuffixed player schema only. `player`, `item` and `quest`, plus every new
participant, must use InnoDB; readiness refuses missing/nontransactional tables
and differing custody/item column layouts. This script does not convert those
three existing tables or overwrite existing balances/history. Install and
change schemas only while all writers are stopped, with verified backups and
asset reconciliation. Schema presence is cached until process restart.
Deploy matching game, DB and all internal libraries together: internal packet
77 and the AsyncSQL fence ABI require coordinated binaries. The classic client
wire version stays `mt20261024`; deploy the matching native window client and
its offline layout/image resources with this integration.
Do not downgrade to a version that ignores custody and ID reservations after
new transactions have been accepted. Disabling the old offline-shop gate is
not a recovery mechanism for the new path.
SQL failures retain the same pending token for retry. An ambiguous COMMIT is
resolved from the committed request/order state. Connections can reconnect
before a new attempt, but automatic reconnect is disabled throughout a pinned
transaction. Failed final saves abort the intent without economic mutations.
Result/history and reservation rows are retained; no automatic log truncation
or destructive compensation is performed.
## Verification
`tests/features/test_economy.py` runs the actual C++ store with an explicit
SQLite SQL-dialect adapter and ASan/UBSan. The same C++ scenarios in
`fixtures/economy_probe.cpp` also run against isolated real MySQL 5.6/InnoDB on
FreeBSD i386. They cover all nine mutation types, each settlement statement/COMMIT exit
boundary after durable enqueue, competing buyers, duplicate claim/refund settlement, partial reward
SQL failure, full mall rollback, wallet changes and stable-ID replay.
`test_economy_coordinator.py` executes the production DB coordinator with peer,
cache and FIFO completion boundaries replaced. `test_gaya_runtime.py` executes
the production Gaya unit with SQL/item-factory/submission boundaries replaced,
verifying it does not charge, grant or consume paid items in game.
Evidence and real MySQL connection-loss/server-SIGKILL recovery results are in
the client repository's `audit/evidence/planb-economy-20261020/`. These tests do
not constitute a connected multi-core game/client or mobile-device acceptance.
No production installation or migration was performed.
## Current acceptance scope
The user excluded historical asset migration/compensation from the current
repair scope. Existing legacy rows remain preserved; no legacy import or refund
is implied by accepting new transactions. The optional read-only `reconcile.py`
utility is available for a future review and is not a current release gate.
Native NPC/window routing, complete connected acceptance, actual mall checkout,
mobile interaction and remaining Plan B product checks still require evidence.
+161
View File
@@ -0,0 +1,161 @@
#!/usr/bin/env python3
"""Read-only legacy asset inventory. Never guesses refunds or writes game tables."""
import argparse
from collections import Counter
import hashlib
import json
import os
from pathlib import Path
import re
import subprocess
import xml.etree.ElementTree as ET
TABLES = ('player', 'item', 'offline_shop_npc', 'offline_shop_item',
'offline_shop_log', 'offline_shop_log_important', 'port_economy_custody',
'port_economy_listings', 'port_economy_orders', 'port_economy_credit')
REQUIRED = {'player', 'item', 'offline_shop_item', 'offline_shop_npc',
'offline_shop_log', 'offline_shop_log_important'}
def canonical(value):
return json.dumps(value, sort_keys=True, separators=(',', ':'), ensure_ascii=True).encode()
def digest(value):
return hashlib.sha256(canonical(value)).hexdigest()
def xml_rows(output):
text = re.sub(r'<\?xml[^?]*\?>', '', output)
root = ET.fromstring('<results>' + text + '</results>')
return [[{f.attrib['name']: None if f.attrib.get('{http://www.w3.org/2001/XMLSchema-instance}nil') == 'true' else (f.text or '') for f in row} for row in result.findall('row')]
for result in root.findall('resultset')]
def snapshot(defaults, database):
if not re.fullmatch(r'[A-Za-z0-9_]+', database):
raise ValueError('invalid database name')
def query(sql):
# Credentials remain in the supplied protected MySQL defaults file.
result = subprocess.run(['mysql', '--defaults-extra-file=' + str(defaults.resolve()),
'--xml', '--database=' + database, '--execute=' + sql],
check=True, capture_output=True)
return xml_rows(result.stdout.decode('utf-8'))
metadata = query("SELECT TABLE_NAME,COLUMN_NAME FROM information_schema.columns "
"WHERE TABLE_SCHEMA=DATABASE() ORDER BY TABLE_NAME,ORDINAL_POSITION")[0]
columns = {}
for row in metadata:
if row['TABLE_NAME'] in TABLES:
columns.setdefault(row['TABLE_NAME'], []).append(row['COLUMN_NAME'])
if not REQUIRED <= columns.keys():
raise ValueError('required legacy tables missing: ' + ','.join(sorted(REQUIRED - columns.keys())))
engines = query("SELECT TABLE_NAME,ENGINE FROM information_schema.tables WHERE TABLE_SCHEMA=DATABASE()")[0]
nontransactional = [r['TABLE_NAME'] for r in engines if r['TABLE_NAME'] in columns and r['ENGINE'] != 'InnoDB']
if nontransactional:
raise ValueError('consistent snapshot requires InnoDB: ' + ','.join(nontransactional))
sql = ['SET SESSION TRANSACTION ISOLATION LEVEL REPEATABLE READ',
'START TRANSACTION WITH CONSISTENT SNAPSHOT']
for table, names in columns.items():
# Hex every value, including arbitrary binary metadata and names. NULL
# stays NULL; all original columns survive the review snapshot.
def ident(name):
return '`' + name.replace('`', '``') + '`'
sql.append('SELECT ' + ','.join('HEX(CAST(' + ident(n) + ' AS BINARY)) AS ' + ident(n) for n in names) +
' FROM ' + ident(table))
sql.append('COMMIT')
results = query(';'.join(sql))
if len(results) != len(columns):
raise ValueError('incomplete snapshot')
tables = dict(zip(columns, results))
# SELECT order is unspecified. Stable snapshots sort by complete row bytes.
for rows in tables.values():
rows.sort(key=canonical)
payload = {'format': 1, 'encoding': 'mysql-hex-all-columns', 'tables': tables}
return dict(payload, sha256=digest(payload))
def audit(snap):
payload = {k: v for k, v in snap.items() if k != 'sha256'}
if snap.get('format') != 1 or snap.get('encoding') != 'mysql-hex-all-columns' or digest(payload) != snap.get('sha256'):
raise ValueError('snapshot format or checksum mismatch')
if not REQUIRED <= snap['tables'].keys():
raise ValueError('incomplete legacy snapshot')
def rows(table):
return [{k: bytes.fromhex(v).decode('utf-8', 'surrogateescape') if v is not None else None
for k, v in row.items()} for row in snap['tables'].get(table, [])]
def number(row, key, maximum=2**32-1):
value = row.get(key)
if value is None or not re.fullmatch(r'[0-9]+', value) or int(value) > maximum:
raise ValueError('invalid ' + key)
return int(value)
players = rows('player')
ids = Counter(r.get('id') for r in players)
owners = {r.get('id') for r in players if ids[r.get('id')] == 1}
normal = Counter(r.get('id') for r in rows('item'))
custody = Counter(r.get('id') for r in rows('port_economy_custody'))
legacy = rows('offline_shop_item')
duplicates = Counter(r.get('id') for r in legacy)
assets = []
for row in legacy:
reasons = []
try:
item = number(row, 'id'); owner = number(row, 'owner_id')
if not item or not owner or not number(row, 'count', 2000) or not number(row, 'vnum'):
reasons.append('invalid_item')
if number(row, 'price', 2_000_000_000_000_000) == 0:
reasons.append('invalid_price')
except ValueError:
reasons.append('invalid_numeric_fields')
if duplicates[row.get('id')] != 1:
reasons.append('duplicate_legacy_id')
if normal[row.get('id')] or custody[row.get('id')]:
reasons.append('item_id_exists_elsewhere')
if row.get('owner_id') not in owners:
reasons.append('owner_missing_or_duplicate')
extra = row.get('port_extra')
if extra is None or len(extra.encode('utf-8', 'surrogateescape')) != 69:
reasons.append('missing_or_invalid_full_item_metadata')
if row.get('status') != '0':
reasons.append('historical_order_requires_delivery_payment_evidence')
# A structurally valid row is only a candidate. It is never an approved
# migration: legacy statuses cannot prove ownership or refund liability.
assets.append({'key': 'legacy-item:' + str(row.get('id')), 'row_sha256': digest(row),
'classification': 'quarantine' if reasons else 'custody_review',
'reasons': reasons, 'action': 'manual_evidence_review'})
for row in players:
if row.get('shop_money') not in (None, '0'):
reasons = []
try:
number(row, 'shop_money', 2_000_000_000_000_000)
except ValueError:
reasons.append('invalid_balance')
assets.append({'key': 'legacy-proceeds:' + str(row.get('id')), 'row_sha256': digest(row),
'classification': 'quarantine' if reasons else 'proceeds_review',
'reasons': reasons, 'action': 'reconcile_logs_before_transfer'})
history = {t: len(snap['tables'].get(t, [])) for t in ('offline_shop_log', 'offline_shop_log_important')}
return {'format': 1, 'snapshot_sha256': snap['sha256'], 'assets': assets,
'history_rows': history, 'automatic_refunds': [], 'automatic_writes': [],
'release_gate': 'BLOCKED_PENDING_RECONCILIATION',
'required_review': 'Resolve every asset against original item metadata, owners, payments, deliveries and logs; missing evidence stays quarantined.'}
def main():
parser = argparse.ArgumentParser(description=__doc__)
sub = parser.add_subparsers(dest='command', required=True)
export = sub.add_parser('snapshot')
export.add_argument('--defaults-file', type=Path, required=True)
export.add_argument('--database', required=True)
export.add_argument('--output', type=Path, required=True)
inspect = sub.add_parser('audit')
inspect.add_argument('--snapshot', type=Path, required=True)
inspect.add_argument('--output', type=Path, required=True)
args = parser.parse_args()
result = snapshot(args.defaults_file, args.database) if args.command == 'snapshot' else audit(json.loads(args.snapshot.read_text()))
# Refuse replacement of prior evidence; owner-only permissions for asset data.
with os.fdopen(os.open(args.output, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), 'w') as out:
out.write(json.dumps(result, indent=2, ensure_ascii=True) + '\n')
print(args.command + ' complete; no game tables modified')
if __name__ == '__main__':
main()
+53
View File
@@ -0,0 +1,53 @@
-- Explicit migration, never run at game startup. Select the player database.
-- player, item and quest MUST already use InnoDB. Back up before any production
-- engine conversion; this script intentionally does not convert those tables.
CREATE TABLE IF NOT EXISTS port_economy_version (
id INT UNSIGNED PRIMARY KEY, version INT UNSIGNED NOT NULL
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS port_economy_requests (
token CHAR(32) CHARACTER SET ascii COLLATE ascii_bin PRIMARY KEY,
account INT UNSIGNED NOT NULL, pid INT UNSIGNED NOT NULL,
body VARBINARY(8192) NOT NULL,
state ENUM('PENDING','DONE') NOT NULL,
result VARCHAR(64) NOT NULL, reference BIGINT UNSIGNED NOT NULL DEFAULT 0,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
INDEX player_history(pid,created_at)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS port_economy_pending (
pid INT UNSIGNED PRIMARY KEY, token CHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL UNIQUE
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS port_economy_item_reservations (
id INT UNSIGNED PRIMARY KEY, request CHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS port_economy_account_lock (
account INT UNSIGNED PRIMARY KEY
) ENGINE=InnoDB;
-- Exact column layout is checked before every transaction. All sockets,
-- attributes and port_extra bytes survive custody without reinterpretation.
CREATE TABLE IF NOT EXISTS port_economy_custody LIKE item;
ALTER TABLE port_economy_custody ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS port_economy_listings (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
owner INT UNSIGNED NOT NULL, account INT UNSIGNED NOT NULL,
item INT UNSIGNED NOT NULL, INDEX custody_item(item), price BIGINT NOT NULL,
state ENUM('OPEN','RESERVED','SOLD','CANCELLED') NOT NULL,
active_order BIGINT UNSIGNED NOT NULL DEFAULT 0,
INDEX public_list(state,id), INDEX owner_list(owner,id)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS port_economy_orders (
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
request CHAR(32) CHARACTER SET ascii COLLATE ascii_bin NOT NULL UNIQUE,
listing BIGINT UNSIGNED NOT NULL, buyer INT UNSIGNED NOT NULL,
account INT UNSIGNED NOT NULL, price BIGINT NOT NULL,
state ENUM('READY','CLAIMED','REFUNDED') NOT NULL,
INDEX buyer_orders(buyer,id)
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS port_economy_credit (
pid INT UNSIGNED PRIMARY KEY, amount BIGINT NOT NULL DEFAULT 0
) ENGINE=InnoDB;
CREATE TABLE IF NOT EXISTS port_economy_gaya (
pid INT UNSIGNED PRIMARY KEY, generation BIGINT UNSIGNED NOT NULL,
deadline INT UNSIGNED NOT NULL, offers VARBINARY(351) NOT NULL
) ENGINE=InnoDB;
INSERT INTO port_economy_version(id,version) VALUES(1,1)
ON DUPLICATE KEY UPDATE version=version;
+83
View File
@@ -0,0 +1,83 @@
#!/usr/bin/env python3
"""Plan/apply gold columns from the actual selected schemas; never truncate balances."""
import argparse
import hashlib
import json
import os
from pathlib import Path
import re
import subprocess
MAXIMUM=2000000000000000
def validate_column(kind):
if not re.fullmatch(r'(tinyint|smallint|mediumint|int|bigint)(\(\d+\))?( unsigned)?',kind.lower()):
raise ValueError('Unexpected money column definition: '+kind)
def fingerprint(value):
return hashlib.sha256(json.dumps(value,sort_keys=True,separators=(',',':')).encode()).hexdigest()
def save(path,value):
temporary=path.with_name(path.name+'.new')
with temporary.open('x') as out:
os.chmod(temporary,0o600);json.dump(value,out,indent=2);out.write('\n');out.flush();os.fsync(out.fileno())
os.replace(temporary,path)
fd=os.open(path.parent,os.O_RDONLY)
try:os.fsync(fd)
finally:os.close(fd)
def main():
p=argparse.ArgumentParser(description=__doc__)
p.add_argument('--player',required=True);p.add_argument('--log',required=True)
p.add_argument('--plan',type=Path,required=True);p.add_argument('--apply',action='store_true')
p.add_argument('--offline',action='store_true');p.add_argument('--backup-id')
a=p.parse_args()
if not all(re.fullmatch(r'[A-Za-z0-9_]+',s) for s in (a.player,a.log)):p.error('Invalid schema name')
if a.apply and (not a.offline or not a.backup_id):p.error('Apply requires --offline --backup-id')
def sql(query):
r=subprocess.run(['mysql','-N','-B'],input=query,text=True,capture_output=True,check=True)
return [line.split('\t') for line in r.stdout.splitlines()]
identity=sql('SELECT @@hostname,@@port,@@server_id,@@version;')
if len(identity)!=1:raise RuntimeError('Unknown server identity')
required=[(a.player,t,'gold',True) for t in ('player','player_deleted','safebox','guild')]+[(a.log,'money_log','gold',False)]
optional=[(a.log,'log','what',False)]+[(a.player,t,c,False) for t,c in [('player','shop_money'),('offline_shop_item','price'),('offline_shop_log','price'),('offline_shop_log_important','price')]]
rows=[];ddl={}
for schema,table,column,unsigned in required+optional:
definition=sql("SELECT COLUMN_TYPE,IS_NULLABLE,COLUMN_DEFAULT,EXTRA FROM information_schema.columns WHERE TABLE_SCHEMA='%s' AND TABLE_NAME='%s' AND COLUMN_NAME='%s';"%(schema,table,column))
if len(definition)!=1:
if (schema,table,column,unsigned) in optional:continue
raise RuntimeError('Missing required column: '+'.'.join((schema,table,column)))
validate_column(definition[0][0])
if definition[0][3]:raise RuntimeError('Generated/automatic money columns require explicit review')
target='bigint(20)'+(' unsigned' if unsigned else '')
upper=(2**63-1) if schema==a.log else MAXIMUM
lower=-(2**63) if schema==a.log else 0
invalid=sql('SELECT COUNT(*) FROM `%s`.`%s` WHERE `%s` IS NULL OR `%s`>%d OR `%s`<%d;'%(schema,table,column,column,upper,column,lower))
if invalid!=[['0']]:raise RuntimeError('Out of range/null money data: '+schema+'.'+table+'.'+column)
key=schema+'.'+table
if key not in ddl:ddl[key]=sql('SHOW CREATE TABLE `%s`.`%s`;'%(schema,table))
rows.append({'schema':schema,'table':table,'column':column,'before':definition[0],'target':target})
if a.plan.exists():
plan=json.loads(a.plan.read_text());checksum=plan.get('sha256');base={k:v for k,v in plan.items() if k!='sha256'}
if plan.get('version')!=1 or plan.get('identity')!=identity[0] or checksum!=fingerprint(base):raise RuntimeError('Foreign/stale/corrupt plan')
if [(r['schema'],r['table'],r['column']) for r in rows]!=[(r['schema'],r['table'],r['column']) for r in plan['columns']]:raise RuntimeError('Column inventory differs from plan')
for current,bound in zip(rows,plan['columns']):
if current['before']!=bound['before'] and current['before'][:2]!=[bound['target'],'NO']:raise RuntimeError('Column changed since planning')
else:
plan={'version':1,'identity':identity[0],'columns':rows,'show_create':ddl};plan['sha256']=fingerprint(plan)
a.plan.parent.mkdir(parents=True,exist_ok=True);save(a.plan,plan)
if not a.apply:
print('PLAN ONLY: review '+str(a.plan));return
for row in plan['columns']:
sql('ALTER TABLE `%s`.`%s` MODIFY COLUMN `%s` %s NOT NULL DEFAULT 0;'%(row['schema'],row['table'],row['column'],row['target']))
actual=sql("SELECT COLUMN_TYPE,IS_NULLABLE,COLUMN_DEFAULT FROM information_schema.columns WHERE TABLE_SCHEMA='%s' AND TABLE_NAME='%s' AND COLUMN_NAME='%s';"%(row['schema'],row['table'],row['column']))
if actual!=[[row['target'],'NO','0']]:raise RuntimeError('Money column post-validation failed')
save(a.plan.with_name(a.plan.name+'.receipt.json'),{'plan_sha256':plan['sha256'],'backup_id':a.backup_id,'verified':True})
print('PASS: columns verified; balances preserved. Runtime release acceptance is separate.')
if __name__=='__main__':main()
+4 -14
View File
@@ -1,14 +1,4 @@
-- Metin2 64-bit Gold Migration Script
-- Target: player database (player, safebox, guild)
-- GOLD_MAX_64 = 2,000,000,000,000,000 (2 quadrillion / 2000万亿)
USE `player`;
-- 1. Upgrade player.gold to BIGINT(20) UNSIGNED
ALTER TABLE `player` MODIFY COLUMN `gold` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0;
-- 2. Upgrade safebox.gold to BIGINT(20) UNSIGNED
ALTER TABLE `safebox` MODIFY COLUMN `gold` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0;
-- 3. Upgrade guild.gold to BIGINT(20) UNSIGNED
ALTER TABLE `guild` MODIFY COLUMN `gold` BIGINT(20) UNSIGNED NOT NULL DEFAULT 0;
-- Blind DDL cannot verify schema identity, player_deleted, or the actual money_log.
-- Use migrate_gold64.py --player SCHEMA --log LOG_SCHEMA --plan PATH.
-- Apply the reviewed plan with --apply --offline --backup-id BACKUP.
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT='Use the source-bound gold migration planner; blind DDL is disabled';
+4 -19
View File
@@ -1,19 +1,4 @@
-- Metin2 64-bit Gold Rollback Script
-- Target: player database (player, safebox, guild)
-- Restores gold column to INT(11) with clamp to 2,000,000,000 to prevent data truncation errors
USE `player`;
-- 1. Clamp values exceeding 2,000,000,000 before downcasting
UPDATE `player` SET `gold` = 2000000000 WHERE `gold` > 2000000000;
UPDATE `safebox` SET `gold` = 2000000000 WHERE `gold` > 2000000000;
UPDATE `guild` SET `gold` = 2000000000 WHERE `gold` > 2000000000;
-- 2. Restore player.gold to INT(11) NOT NULL DEFAULT 0
ALTER TABLE `player` MODIFY COLUMN `gold` INT(11) NOT NULL DEFAULT 0;
-- 3. Restore safebox.gold to INT(11) NOT NULL DEFAULT 0
ALTER TABLE `safebox` MODIFY COLUMN `gold` INT(11) NOT NULL DEFAULT 0;
-- 4. Restore guild.gold to INT(11) NOT NULL DEFAULT 0
ALTER TABLE `guild` MODIFY COLUMN `gold` INT(11) NOT NULL DEFAULT 0;
-- Asset-preserving rollback: keep the expanded schema and every balance.
-- Deploy a compatible binary that reads/writes BIGINT while disabling new features.
-- An automatic downgrade to INT is intentionally prohibited.
SELECT 'Keep BIGINT balances; use the compatible rollback binary' AS rollback_policy;