Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions docs/btd-death-regression.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
# Before the Dawn death and wave regression

The October 27 production exception is a death-callback failure, not a process
crash. The preserved stack identifies `_globallogic.gsc:5184`, entered through
`_callbacksetup.gsc:69` / `level.callbackPlayerKilled`: an existing inflictor's
undefined `targetname` is compared with `"zom"`. The game shuts down with
`Server disconnected`; a running container is therefore insufficient health.
The stack does not identify the actual damage source.

A disposable native player suicide reproduces that callback error and shutdown.
The source overlay adds a defined-field guard before comparison. It leaves the
zombie branch intact and does not modify VM comparison behavior or Promod.
After that correction, accelerated wave testing independently exposed a second
original-package defect: spawn structs contain only origin, while
`k3/_zombie.gsc:125` assigns their undefined angles to a native vector. A second
one-line overlay initializes angles to `(0, 0, 0)` in the spawn-point producer.
This second failure was not the production incident's recorded exception.

Preparation verifies every original input and pinned raw-source hash, reads
plaintext GSC raw members from the verified fastfile and generates private GSX
overlays. There is no bytecode decompilation or fastfile rebuild. The original
`mod.ff`/IWD/CFG bytes are retained. Generated third-party source remains in the
operator's private runtime and must not be committed or redistributed.
`inputs.json` records both overlay hashes; workspace packaging must validate them.

## Automated evidence

`python3 -m unittest discover -s tests -p test_btd_prepare.py` uses only synthetic
raw-source/package fixtures: input identity, missing/ambiguous conditions,
precise guard substitution, native-vector initialization and no original edits.

With authorized private runtime/game inputs, use the disposable runner below.
`--runtime` must contain `.bot-test-runtime`; every run copies inputs to a new
private `/tmp/btd-death-regression-*` directory. No remote service is touched.

```sh
python3 tests/run_btd_regression.py --runtime PRIVATE_RUNTIME --game GAME_DATA --binary PRESERVED_BINARY --scenario expression
python3 tests/run_btd_regression.py --runtime PRIVATE_RUNTIME --game GAME_DATA --binary PRESERVED_BINARY --scenario expression --fixed
python3 tests/run_btd_regression.py --runtime PRIVATE_RUNTIME --game GAME_DATA --binary PRESERVED_BINARY --scenario death
python3 tests/run_btd_regression.py --runtime PRIVATE_RUNTIME --game GAME_DATA --binary PRESERVED_BINARY --scenario death --fixed
python3 tests/run_btd_regression.py --runtime PRIVATE_RUNTIME --game GAME_DATA --binary PRESERVED_BINARY --scenario lifecycle --fixed --reproduce-spawn-defect
python3 tests/run_btd_regression.py --runtime PRIVATE_RUNTIME --game GAME_DATA --binary PRESERVED_BINARY --scenario lifecycle --fixed
```

The reproduction commands succeed only when the expected original failure is
observed. The fixed lifecycle run requires native player spawn, suicide, callback
completion, respawn, actual vendor zombie spawning/death handlers and progression
into wave two. Only fixture CFG values accelerate grace time/wave size; shipped
policy is unchanged. It then performs two real UDP admission handshakes with
intervening disconnects and native map transitions. Full logs and `results.json`
remain in the private evidence directory; script compile/runtime errors fail the
fixed run. `developer=1` is deliberate: the original private production CFG used
that setting, and `developer=0` can suppress script-error reporting.

The existing `run_btd_integration.py` covers all 15 installed maps, process restart,
CFG precedence, purity and denied RCON activation. It now explicitly enables script
error reporting. The existing Promod integration suite remains separate.

Synthetic players and UDP admission are not graphical client gameplay. Neither
playability nor production readiness is certified by these tests. Require
independent review, existing mandatory hosted CI, operator-approved merges,
master-based homologation deployment, and operator-supervised real-client death,
respawn, combat, waves, reconnection and map transitions before exact-image approval.
Keep recovered production Promod unchanged until explicit promotion authorization.
72 changes: 72 additions & 0 deletions tests/btd_regression.gsc
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
// Disposable fixture only. Never packaged in a runtime image.
main()
{
if (getdvar("btd_test_scenario") == "idle") return;
wait 4;
if (getdvar("btd_test_scenario") == "expression")
{
fixture = spawn("script_model", (0, 0, 0));
// The regression runner substitutes the actual pinned condition here.
if (BTD_TEST_CONDITION) setdvar("btd_test_result", "unexpected");
setdvar("btd_test_result", "expression_pass");
return;
}
player = addtestclient("DeathRegression");
player.pers["isBot"] = true;
wait 1;
player maps\mp\gametypes\_globallogic::menuAllies();
wait 1;
player maps\mp\gametypes\_globallogic::menuClass("specops_mp,0");
for (i = 0; i < 150; i++)
{
if (isalive(player) && player.sessionstate == "playing") break;
wait 0.1;
}
if (!isalive(player) || player.sessionstate != "playing")
{
setdvar("btd_test_result", "spawn_failed");
return;
}
setdvar("btd_test_result", "spawned");
wait 1;
player suicide();
wait 2;
setdvar("btd_test_result", "death_callback_survived");
if (getdvar("btd_test_scenario") != "lifecycle") return;
for (i = 0; i < 200; i++)
{
if (isalive(player) && player.sessionstate == "playing") break;
wait 0.1;
}
if (!isalive(player) || player.sessionstate != "playing")
{
setdvar("btd_test_result", "respawn_failed"); return;
}
setdvar("btd_test_respawn", "passed");
player.maxhealth = 100000;
player.health = 100000;
seen_spawn = false;
// Exercise the vendor wave loop with accelerated fixture CFG values.
// Damage notifications enter the vendor zombie health/death handler.
for (i = 0; i < 1800; i++)
{
zombies = getentarray("zom", "targetname");
for (j = 0; j < zombies.size; j++)
{
if (isdefined(zombies[j].health) && zombies[j].health > 0)
{
seen_spawn = true;
zombies[j] notify("damage", 100000, player, (1,0,0), zombies[j].origin,
"MOD_RIFLE_BULLET", "zombie", "tag_origin", "tag_origin", 0);
}
}
if (seen_spawn && level.currentwave >= 2) break;
wait 0.05;
}
if (!seen_spawn) { setdvar("btd_test_result", "zombie_spawn_failed"); return; }
setdvar("btd_test_zombie_spawn", "passed");
if (level.currentwave < 2) { setdvar("btd_test_result", "wave_failed"); return; }
setdvar("btd_test_wave", "passed");
kick(player getentitynumber());
setdvar("btd_test_result", "lifecycle_pass");
}
2 changes: 1 addition & 1 deletion tests/run_btd_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ def load(name):
service = {'entrypoint': [runtime.EXECUTABLE], 'read_only': True,
'volumes': [{'target': value} for value in ('/home/user/cod4/main', '/home/user/cod4/zone', runtime.PERSISTENT_HOME)],
'command': ['+set', 'dedicated', '1', '+set', 'net_ip', '127.0.0.1',
'+set', 'net_port', str(port), '+set', 'fs_homepath', runtime.PERSISTENT_HOME,
'+set', 'net_port', str(port), '+set', 'developer', '1', '+set', 'developer_script', '1', '+set', 'fs_homepath', runtime.PERSISTENT_HOME,
'+exec', 'private.cfg']}
adapted = runtime.adapt(service, 'qualification-only', 'zombies', fingerprint, fs_game, startup, maps, capacity)
checks[f'{attempt}_readonly_config_retained'] = adapted['read_only'] is True
Expand Down
132 changes: 132 additions & 0 deletions tests/run_btd_regression.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,132 @@
#!/usr/bin/env python3
"""Private disposable native-VM reproduction; never modifies input runtimes.
Synthetic clients are not proof of graphical client gameplay qualification.
"""
import argparse
import hashlib
import importlib.util
import json
from pathlib import Path
import re
import shutil
import socket
import subprocess
import tempfile
import time

ROOT = Path(__file__).resolve().parents[1]
p = argparse.ArgumentParser(description=__doc__)
for name in ('runtime', 'game', 'binary'):
p.add_argument('--' + name, required=True, type=Path)
p.add_argument('--fixed', action='store_true')
p.add_argument('--reproduce-spawn-defect', action='store_true', help='Apply death guard only, expect the native missing-angle failure')
p.add_argument('--scenario', choices=('expression', 'death', 'lifecycle'), required=True)
a = p.parse_args()
assert (a.runtime / '.bot-test-runtime').is_file()
spec = importlib.util.spec_from_file_location('btd', ROOT / 'tools/btd/prepare.py')
btd = importlib.util.module_from_spec(spec); spec.loader.exec_module(btd)
home = Path(tempfile.mkdtemp(prefix='btd-death-regression-'))
for name in ('mods', 'integrity'):
shutil.copytree(a.runtime / name, home / name)
for name in ('main', 'zone'):
(home / name).symlink_to((a.game / name).resolve(), target_is_directory=True)
shutil.copy2(a.binary, home / 'cod4x18_dedrun')
mod = home / 'mods/btd_alpha_001'
lock = json.loads((ROOT / 'tools/btd/dependencies.json').read_text())
ff = mod / 'mod.ff'
assert hashlib.sha256(ff.read_bytes()).hexdigest() == lock['files']['btd_alpha_001/mod.ff']
source = btd.death_overlay(ff.read_bytes(), lock['death_callback_source_sha256']).decode()
if not a.fixed:
source = source.replace(btd.SAFE_DEATH_CONDITION, btd.DEATH_CONDITION)
source = source.replace('init()\r\n{', 'init()\r\n{\r\n thread btd_regression::main();', 1)
assert 'thread btd_regression::main();' in source
out = mod / 'maps/mp/gametypes/_globallogic.gsx'
out.parent.mkdir(parents=True, exist_ok=True); out.write_bytes(source.encode())
if a.fixed and not a.reproduce_spawn_defect:
spawn = mod / btd.SPAWN_SCRIPT.replace('.gsc', '.gsx')
spawn.parent.mkdir(parents=True, exist_ok=True)
spawn.write_bytes(btd.spawn_overlay(ff.read_bytes(), lock['spawn_points_source_sha256']))
fixture = (ROOT / 'tests/btd_regression.gsc').read_text()
condition = btd.SAFE_DEATH_CONDITION if a.fixed else btd.DEATH_CONDITION
fixture = fixture.replace('BTD_TEST_CONDITION', condition.replace('eInflictor', 'fixture'))
(mod / 'btd_regression.gsc').write_text(fixture)
if a.scenario == 'lifecycle':
with (mod/'canonical-mode.cfg').open('a') as cfg:
cfg.write('\nset btd_grace_time "10"\nset btd_wave_settings "2"\nset btd_start_zoms "5"\n')
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s:
s.bind(('127.0.0.1', 0)); port = s.getsockname()[1]
cmd = [str(home / 'cod4x18_dedrun'), '+set', 'dedicated', '1', '+set', 'net_ip', '127.0.0.1',
'+set', 'net_port', str(port), '+set', 'fs_basepath', str(home), '+set', 'fs_homepath', str(home/'persistent'),
'+set', 'fs_game', 'mods/btd_alpha_001', '+set', 'sv_autoupdate', '0', '+set', 'developer', '1', '+set', 'developer_script', '1',
'+set', 'fs_localizedHeadersPath', str(home/'integrity'), '+set', 'sv_maxclients', '12',
'+set', 'btd_test_scenario', a.scenario, '+exec', 'canonical-shared.cfg',
'+exec', 'canonical-mode.cfg', '+map', 'mp_crash']
logpath = home/'console.log'
network_checks = {}
def status():
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as channel:
channel.settimeout(3); channel.sendto(b'\xff'*4+b'getstatus\n',('127.0.0.1',port))
data=channel.recv(65535)
assert b'statusResponse' in data
fields=data.split(b'\n')[1].split(b'\\')
return dict(zip(fields[1::2],fields[2::2]))

def admit(attempt):
with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as channel:
channel.bind(('127.0.0.2',0));channel.settimeout(3)
channel.sendto(b'\xff'*4+b'getchallenge 123456',('127.0.0.1',port))
challenge=channel.recv(2048)[4:].decode().split()[1]
userinfo=f'connect "\\protocol\\21\\challenge\\{challenge}\\qport\\{24444+attempt}\\name\\ReconnectFixture\\rate\\25000\\snaps\\20"'
channel.sendto(b'\xff'*4+userinfo.encode(),('127.0.0.1',port))
assert b'connectResponse' in channel.recv(2048)
time.sleep(.2)
text=re.sub(r'\^[0-9]', '', logpath.read_text(errors='replace'))
slot=re.findall(r'CS_CONNECTED for ReconnectFixture num (\d+)',text)[-1]
proc.stdin.write(('clientkick '+slot+'\n').encode());proc.stdin.flush()
time.sleep(2)

with logpath.open('w') as log:
proc = subprocess.Popen(cmd, cwd=home, stdin=subprocess.PIPE, stdout=log, stderr=subprocess.STDOUT)
try:
until = time.monotonic() + (130 if a.scenario == 'lifecycle' else 35)
while time.monotonic() < until and proc.poll() is None:
time.sleep(.25)
text = re.sub(r'\^[0-9]', '', logpath.read_text(errors='replace'))
if 'script runtime error' in text or 'script compile error' in text: break
proc.stdin.write(b'btd_test_result\nbtd_test_respawn\nbtd_test_zombie_spawn\nbtd_test_wave\n'); proc.stdin.flush()
success = {'expression': 'expression_pass', 'death': 'death_callback_survived', 'lifecycle': 'lifecycle_pass'}[a.scenario]
if '"'+success+'"' in text or re.search(r'"(?:spawn|respawn|zombie_spawn|wave)_failed"', text): break
if a.scenario == 'lifecycle' and '"lifecycle_pass"' in text and not a.reproduce_spawn_defect:
time.sleep(2)
for attempt in range(2):
admit(attempt); network_checks['udp_admission_'+str(attempt)]=True
proc.stdin.write(b'set btd_test_scenario idle\n');proc.stdin.flush()
for mapname in ('mp_strike','mp_crash'):
proc.stdin.write(('map '+mapname+'\n').encode());proc.stdin.flush()
time.sleep(3)
values=status()
assert values[b'mapname']==mapname.encode() and values[b'fs_game']==b'mods/btd_alpha_001' and values[b'g_gametype']==b'war' and values[b'sv_pure']==b'1'
network_checks['map_'+mapname]=True
finally:
if proc.poll() is None:
proc.stdin.write(b'quit\n'); proc.stdin.flush()
try: proc.wait(timeout=8)
except subprocess.TimeoutExpired: proc.kill(); proc.wait()
text = re.sub(r'\^[0-9]', '', logpath.read_text(errors='replace'))
error = bool(re.search(r'script (?:runtime|compile) error', text))
result = {'evidence': str(home), 'scenario': a.scenario, 'fixed': a.fixed,
'runtime_error': error, 'gameplay_qualified': False, 'network_checks': network_checks,
'expression_pass': '"expression_pass"' in text,
'death_callback_survived': '"death_callback_survived"' in text,
'spawn_failed': '"spawn_failed"' in text,
'respawn_pass': '"btd_test_respawn" is: "passed"' in text,
'zombie_spawn_pass': '"btd_test_zombie_spawn" is: "passed"' in text,
'wave_pass': '"btd_test_wave" is: "passed"' in text,
'lifecycle_pass': '"lifecycle_pass"' in text}
(home/'results.json').write_text(json.dumps(result, indent=2)+'\n')
print(json.dumps(result, indent=2))
expected = result[{'expression':'expression_pass','death':'death_callback_survived','lifecycle':'lifecycle_pass'}[a.scenario]]
if a.reproduce_spawn_defect:
assert error and 'type undefined is not a vector' in text, 'Spawn defect not reproduced: '+str(home)
elif a.fixed: assert not error and expected, 'Fixed regression failed: '+str(home)
else: assert error and "has unmatching types 'undefined' and 'string'" in text, 'Expected failure not reproduced: '+str(home)
41 changes: 39 additions & 2 deletions tests/test_btd_prepare.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@
from pathlib import Path
import tempfile
import unittest
import hashlib
import struct
import zlib

ROOT = Path(__file__).resolve().parents[1]
spec = importlib.util.spec_from_file_location('btd_prepare', ROOT / 'tools/btd/prepare.py')
Expand All @@ -24,6 +27,13 @@ def setUp(self):
mod.mkdir(parents=True)
for name in ('mod.ff', 'btd_images.iwd', 'btd_music.iwd', 'btd_weapons.iwd', 'btd_settings.cfg'):
(mod / name).write_bytes(b'original fixture')
self.raw = ('fixture() { if(' + btd.DEATH_CONDITION + ') return true; }').encode()
marker = b'\xff' * 4 + btd.SCRIPT.encode() + b'\0'
payload = b'fixture!' + struct.pack('<I', len(self.raw)) + marker + self.raw + b'\0'
self.spawn_raw = ('init() { ' + btd.SPAWN_ORIGIN + ' }').encode()
payload += struct.pack('<I', len(self.spawn_raw)) + b'\xff'*4 + btd.SPAWN_SCRIPT.encode() + b'\0' + self.spawn_raw + b'\0'
self.fastfile = b'fixture-head' + zlib.compress(payload)
(mod / 'mod.ff').write_bytes(self.fastfile)
(mod / 'server.cfg').write_text('unsafe sample must not be packaged')
(mod / 'btd_maprotation.cfg').write_text('set sv_mapRotation "gametype war map mp_crash"\n')
(self.source / 'readme.txt').write_text('retain original notice')
Expand All @@ -37,7 +47,9 @@ def setUp(self):
(self.root / 'bots').mkdir()
hashes = {str(p.relative_to(self.source)): btd.digest(p) for p in self.source.rglob('*') if p.is_file()}
(self.root / 'tools/btd/dependencies.json').write_text(json.dumps(
{'files': hashes, 'default_cfgs': ['btd_settings.cfg']}))
{'files': hashes, 'default_cfgs': ['btd_settings.cfg'],
'death_callback_source_sha256': hashlib.sha256(self.raw).hexdigest(),
'spawn_points_source_sha256': hashlib.sha256(self.spawn_raw).hexdigest()}))
(self.root / 'bots/dependencies.json').write_text(json.dumps(
{'integrity_headers': {p.name: btd.digest(p) for p in self.headers.iterdir()}}))
self.output = self.root / 'runtime'
Expand All @@ -49,7 +61,7 @@ def test_original_assets_not_modified_or_decompiled(self):
record = self.prepare()
self.assertEqual(record['maps'], ['mp_crash'])
self.assertEqual(record['asset_type'], 'btd-alpha-001')
self.assertEqual((self.output / 'mods/btd_alpha_001/mod.ff').read_bytes(), b'original fixture')
self.assertEqual((self.output / 'mods/btd_alpha_001/mod.ff').read_bytes(), self.fastfile)
self.assertFalse((self.output / 'mods/btd_alpha_001/server.cfg').exists())
self.assertEqual((self.output / 'licenses/Before-the-Dawn-readme.txt').read_text(), 'retain original notice')
self.assertNotIn('server.cfg', record['assets'])
Expand All @@ -72,3 +84,28 @@ def test_symlink_input_rejected(self):
with self.assertRaises(ValueError):
self.prepare()
self.assertFalse(self.output.exists())

def test_only_missing_field_guard_changes(self):
record = self.prepare()
overlay = self.output / 'mods/btd_alpha_001/maps/mp/gametypes/_globallogic.gsx'
self.assertEqual(overlay.read_bytes(), self.raw.replace(
btd.DEATH_CONDITION.encode(), btd.SAFE_DEATH_CONDITION.encode()))
self.assertEqual(record['overlays'][str(overlay.relative_to(self.output / 'mods/btd_alpha_001'))],
hashlib.sha256(overlay.read_bytes()).hexdigest())

def test_unpinned_source_rejected(self):
with self.assertRaisesRegex(ValueError, 'source hash mismatch'):
btd.death_overlay(self.fastfile, '0' * 64)

def test_unexpected_condition_rejected(self):
raw = self.raw.replace(b'eInflictor.targetname', b'eInflictor.otherfield')
marker = b'\xff' * 4 + btd.SCRIPT.encode() + b'\0'
ff = b'fixture-head' + zlib.compress(b'fixture!' + struct.pack('<I', len(raw)) + marker + raw + b'\0')
with self.assertRaisesRegex(ValueError, 'condition'):
btd.death_overlay(ff, hashlib.sha256(raw).hexdigest())

def test_spawn_points_receive_native_vector_angles(self):
self.prepare()
overlay = self.output / 'mods/btd_alpha_001' / btd.SPAWN_SCRIPT.replace('.gsc', '.gsx')
self.assertEqual(overlay.read_bytes(), self.spawn_raw.replace(
btd.SPAWN_ORIGIN.encode(), (btd.SPAWN_ORIGIN+' temp.angles = (0, 0, 0);').encode()))
Loading
Loading