Elo v3.5 integration and deployment
=================================

The launch configuration uses one CENTRAL rating service for every game VPS.
Every game process gets its own game/userraw/scriptdata directory and bridge.
The service is the only rating writer; local .dat/index files are display caches.
Do not run multiple servers against the old shared writable scriptdata folder.

Math and ranks
--------------
New accounts start at 1500. Rank reveals after 5 rated matches.
K is 64 for games 1-10, 48 for 11-30, 32 for 31-100, then 16. The five-game
rank reveal is separate from these early learning weights.
Expected result is logistic(team mean difference / 400).
The team transfer budget is the smaller of the two teams' summed K values.
Distribute that transfer within each team in proportion to its K weights.
One shared random offset rounds cumulative shares. All eight integer match
changes sum to exactly zero, even with mixed placements and veteran players.
Equal 100+ game veteran teams: +/-8 per player; games 31-100: +/-16.
Equal placement teams: +/-32. These are equal-weight examples; mixed teams
share the smaller team budget and can have smaller individual changes.
A draw scores 0.5, advances placements, and clears both streaks. No streak,
playtime, promotion protection, hard rating floor or decay changes Elo.

Individual performance (v3.5)
----------------------------
After calculating ordinary win/loss Elo, redistribute a small amount inside
each team. A player's adjustment cannot exceed floor(abs(base_delta)/5), and
never exceeds 3 points. +8 can become +7..+9; -8 becomes -9..-7. +32 becomes
+29..+35. A win cannot cost Elo and a loss cannot award Elo because of this
adjustment. Draws use ordinary Elo only. Both team totals remain unchanged.
The result screen shows a nonzero PERFORMANCE adjustment separately.

Use server-observed combat/objective score events from the installed game:
kills, headshots, assists, captures, returns, defenses, assaults, carrier kills,
bomb plants/defuses/destruction and saves. Normalize each award by that mode's
ordinary kill value (100 points per kill); cap any one event at 500 points.
CTF returns use the mode's existing return event because that version awards
XP but no scoreboard points for returns. Observe only its base objective value.
Flag pickups, challenge/rested XP, streak rewards and time played do not count.
There is no separate death/KD-ratio penalty that discourages objective attempts.
All credited events stay on the original GUID across disconnects and rounds;
warmup, late fill-ins and postgame activity cannot add contribution.

Expected teammate share is proportional to 10^(pre-match Elo / 800). Compare
actual points to that share, adding 2000 prior points across the team to soften
short/noisy matches. Center the residuals using each player's adjustment cap,
scale them to stay inside those caps, and use conserved integer rounding.
The 800-point contribution scale is an initial MODEL ASSUMPTION, not a measured
IW4x score/skill relationship. It needs live validation, especially by mode
and role. Strong players are expected to contribute more; raw top score alone
does not automatically earn the maximum adjustment. Missing legacy performance
data keeps ordinary result-only Elo; malformed/incomplete supplied data is
rejected for operator review, not accepted as player-supplied statistics.

The current study is qa/elo-performance/REPORT.txt: noisy, weak, unrelated and
biased performance signals, including inflated stats without stronger play.
Its improvements are synthetic evidence, not a guarantee that scoreboard
contribution perfectly measures skill. Five placements remain provisional.

Rank thresholds
---------------

Bronze <1200; Silver 1200-1399; Gold 1400-1599; Platinum 1600-1799;
Diamond 1800+. Default divisions III, II, I. Set divisions to 3, 4 or 5.
extra_ranks=1 introduces Master at 2000; =2 adds Grandmaster at 2200.
Adding labels never resets/rescales ratings or changes existing thresholds.
The lowest/highest enabled division extends beyond the usual 200-point band.

Only an original 4v4 human roster is rated. Freeze it after pre-match loading,
before objectives start. Original players keep the match result after leaving;
fill-ins do not get that result. A bot during play makes the match unrated.
The optional abandon penalty defaults to 0, and can be set to 0..32 centrally.
It is charged once and is a separate sink, never presented as zero-sum Elo.

These launch parameters were tested for 80 accounts, 10-20 daily players,
and roughly one new account/day. The post-100 reduction limits long-run noise
in a stable small pool; it also slows adaptation after a large skill change.
Simulations establish consistency and modeled tradeoffs, not optimal live
skill prediction. Fixed partners cannot reveal separate individual skill from
team results alone. Duos are never split to try to overcome that limitation.
Use real match outcomes to evaluate predictive calibration after launch.
The five-placement automatic-team report is qa/elo-automatic-10000/REPORT.txt.
The later solo/duo experiment is qa/elo-duos-10000/REPORT.txt. These supersede
captain-draft assumptions for Ranked; the older reports remain historical.
Five games reveal a provisional rank, not a precise individual skill estimate.
The earlier result-only sensitivity study and fresh-seed validation are in
qa/elo-sensitivity-validation/REPORT.txt. They cover narrow and wide skill
distributions, weak/strong newcomers, permanent duos, improvement and no growth.

Rank thresholds never depend on account count, leaderboard position or a
target percentage per tier. Nobody is forced into Bronze or Diamond. Elo is
relative to the people who actually play; without an external reference pool,
"Diamond here" cannot establish a universal skill level across communities.
Disconnected groups and permanent parties further limit what can be inferred.
Zero-sum arithmetic prevents point creation from match results; it does not
by itself guarantee accurate ranks or a stable rating spread. Reported error
is distance from simulated skill, not Elo lost. The community mean remains
1500 in these simulations, with abandon penalties off and new accounts at 1500.

Default rank intervals (inclusive integers)
------------------------------------------
             III          II           I
Bronze       <=1066       1067-1133     1134-1199
Silver       1200-1266     1267-1333     1334-1399
Gold         1400-1466     1467-1533     1534-1599
Platinum     1600-1666     1667-1733     1734-1799
Diamond      1800-1866     1867-1933     >=1934

Ranked keeps original teams throughout a match. The legacy mid-match
rebalancer and spectator backfills are disabled. Missing original players
can reconnect to their original team. Before play, all eight must load; a
failed load returns to the lobby without awarding a result.

Central service
---------------
Python 3.10+; standard library only. Run from the repository root.

1. Choose a database BEFORE starting games. For a new prelaunch pool, explicitly
   set allow_new_pool=true once, then change it back to false after initialization
   so a missing/mistyped database path cannot accidentally create a new season.
   Existing played ratings are never silently converted
   from the old 50-start/1000-wide-rank scale. Archive that season or deliberately
   prepare a migration; do not mix those old values with new 1500-start players.
   To import records already on the intended scale into an empty database:

     python3 -m rating_service.admin --database /private/ratings.sqlite3 import \
       --source /backup/scriptdata/elo_data

   Validation completes before insertion; a failed import inserts no players.
   Played ratings are preserved. Only an unplayed legacy 50 normalizes to 1500.

2. Copy rating_service/service.example.json outside the public/game folders.
   Set database to an absolute local path. Generate a distinct secret per game
   process with: python3 -c "import secrets; print(secrets.token_urlsafe(32))"
   Set server_tokens to a mapping of stable server names to those secrets.
   Never put tokens into GSC, menus, client dvars, the repo, or player downloads.

3. Bind to localhost behind an HTTPS reverse proxy, or a private VPN interface
   such as Tailscale. Plain HTTP must stay on localhost/a private encrypted VPN.
   Start: python3 -m rating_service.service --config /private/service.json
   Use your service supervisor to restart it on failure.
   Keep the SQLite database on ONE host's local disk, not SMB/NFS.

4. On EACH game process, copy bridge.example.json outside userraw and set its
   isolated scriptdata_dir, central service_url and corresponding server token.
   Start: python3 -m rating_service.bridge --config /private/comp-1.json
   The bridge must be running before the game server. It has no Python package
   dependencies. Windows works with py -3 in place of python3.

5. Deploy all scripts/mp files together, including elo_service.gsc. Configs use
   comp_elo_backend "service". Existing Bot Warfare loaders also require
   Bot Warfare v2.3.0's z_svr_bots.iwd and scriptdata/waypoints:
   https://docs.iw4x.io/guides/bot-warfare/
   Keep comp_prematch_hold enabled. A server without a reachable rating service
   can continue playing, but clearly starts unrated matches.

Failure/recovery behavior
-------------------------
BEGIN takes a central snapshot and reserves the eight GUIDs. Another server
cannot simultaneously rate those same players. FINISH writes all eight records
and the audit result in one SQLite transaction. The same match/result retries
return the original response; conflicting results are rejected. A rollback
leaves every player's rating unchanged. Cancelling never undoes a saved result.

Each bridge uses an OS process lock. Immutable, uniquely named outbox requests
survive map/process restarts and outages. Replies and caches use atomic file
replacement. FINISH is retried after network/acknowledgement failure; a UI timeout
shows that the result is pending. Never delete an outbox to clear an error.
Permanent rejections instead show "RESULT NEEDS ADMIN REVIEW" and retain the
original payload with a .rejected extension; they are not advertised as pending.
The optional conduct penalty is frozen from the central policy at match start.
A failed BEGIN becomes unrated and queues CANCEL. Even a delayed BEGIN cannot
revive a cancelled match. The roster persists only across explicit halftime or
round continuation. A fresh map/admin restart cancels an unfinished roster.

If a VPS dies permanently, preserve/replay its outbox first. Active matches do
not automatically expire and discard potentially valid queued results. Inspect:

  python3 -m rating_service.admin --database /private/ratings.sqlite3 active

After verifying no completed result is still queued, an operator may cancel a
stale session (releases player reservations without changing ratings):

  python3 -m rating_service.admin --database /private/ratings.sqlite3 cancel \
    --match server-name:request-id

Create a consistent backup even while the service is running:

  python3 -m rating_service.admin --database /private/ratings.sqlite3 backup \
    --output /backup/ratings-YYYYMMDD.sqlite3

Retain the per-server outbox and central database in backups. Interrupted local
v3.2 journals must be recovered before switching that directory to service mode;
the bridge refuses to overwrite a cache with a nonempty local pending journal.

Discord and other existing features
-----------------------------------
Discord is optional and disabled in launch configs. No account gate, bot or
Discord membership is required. If separately enabled, the bot reads a
bridge's synchronized rating cache and policy.json. Game displays, clan tags
and the optional bot use 5 placements and the same rank policy.
Leaderboard ties resolve by GUID. Missing career W/L is no longer fabricated
from the last ten results: draws make that reconstruction invalid.

Ranked parties use ranked_lobby, not the old Discord party gate. Optional !link
needs its responder configured separately. Legacy career K/D/W/L files and
optional Discord markers are not centralized by the rating API. An operator
enabling those optional features must arrange their storage independently.

Single-server file mode
-----------------------
For a genuinely standalone server only, comp_elo_backend "file" uses the tested
GSC journal path with the same v3.5 bounded performance. That folder must have
exactly one authoritative writer.
Never run the bridge against it. The service uses the exact logistic; file mode
uses the GSC interpolation table (max probability error below 0.000251).
Do not change backends mid-match or reuse service caches as a new live database.

Validation
----------
  python3 -m unittest discover -s tests -p 'test_*.py' -v
  python3 tests/elo/build_checks.py
  node tests/elo/checks.js
  python3 client_menu/build.py

See tests/elo/README.txt and docs/QA.txt for exactly what was executed and the
remaining native match/UI tests. Syntax/mock tests alone are not proof of an
8-player IW4x match, its halftime timing, or the menu's appearance.
