From 757304437e2a35f416b8d184014310955718c4b4 Mon Sep 17 00:00:00 2001 From: dingo Date: Wed, 28 Oct 2026 16:06:56 -0400 Subject: [PATCH] feat(admin): take reserve, cull wildlife, wildlife cap, fresh bud costs (schema 67) ADR-0182 section 16, from playtesting region 16 at its 256-life cap. - Bud costs: the region host's cache of each genome's bud cost was keyed by genome only, so after a tuning adoption the client kept the old cost (or "cannot bud"). It now clears when the rules' encoding changes. - Wildlife cap: reproduction.wildlife_cap (optional, 0..organism cap, 0 = the organism cap) refuses buds of parents without an account at that many lives, keeping the slots above it for players. Bits 17-31 of the energy-cycle word, so older rules keep their bytes. DEV file: 200. - Schema 67: admin command kinds take_reserve (8: up to the amounts from a life's reserve to the spent pool) and remove_wildlife (9: every life without an account, as remove_cell). - Region view: caps; the portal shows lives against the cap. - Portal: Take reserve in the inspector, Remove all wildlife, and marking cells on the map (shift+click, shift+drag) for bulk removal; the guided editor lists optional keys the base revision lacks. - Client: a refused bud says the region may be full. Co-Authored-By: Claude Opus 5.5 --- apps/evo-admin-api/portal/app.js | 138 +++++++++++++++++- apps/evo-admin-api/portal/style.css | 2 + apps/evo-client/panels.cpp | 2 +- apps/evo-server/cellular_bridge.hpp | 19 ++- .../region/dev/tuning/cellular-revamp.tuning | 1 + docs/STATUS.md | 8 + .../adr/0182-admin-portal-and-world-tuning.md | 29 ++++ .../evo/biology/cellular_revamp_tuning.hpp | 1 + .../evo/server/lifecycle/cellular_lives.hpp | 4 + .../evo/server/lifecycle/cellular_revamp.hpp | 3 + migrations/0067_admin_take_and_cull.sql | 54 +++++++ migrations/apply.sql | 15 +- src/biology/cellular_revamp_tuning.cpp | 5 + src/server/admin/admin_api.cpp | 21 ++- src/server/lifecycle/cellular_admin_view.cpp | 6 + src/server/lifecycle/cellular_lives.cpp | 99 +++++++++---- src/server/lifecycle/cellular_revamp.cpp | 8 +- tests/cellular_admin_view_tests.cpp | 7 +- tests/cellular_revamp_owner_tests.cpp | 94 ++++++++++++ tests/cellular_revamp_tuning_tests.cpp | 10 ++ tests/grant_broker_tests.cpp | 12 +- tests/region_migration_tests.cpp | 3 +- tools/ci/postgres-check.sh | 10 +- tools/migrate-postgres.sh | 4 +- 24 files changed, 485 insertions(+), 70 deletions(-) create mode 100644 migrations/0067_admin_take_and_cull.sql diff --git a/apps/evo-admin-api/portal/app.js b/apps/evo-admin-api/portal/app.js index 69e3797..e350770 100644 --- a/apps/evo-admin-api/portal/app.js +++ b/apps/evo-admin-api/portal/app.js @@ -406,7 +406,7 @@ function channelTiles(values, subs = []) { const kindLabels = { remove_cell: 'remove cell', grant_reserve: 'grant reserve', add_bubbles: 'add bubbles', add_pool: 'add to spent pool', release_pool: 'release spent pool', spawn_wildlife: 'spawn wildlife', - adopt_tuning: 'adopt tuning', + adopt_tuning: 'adopt tuning', take_reserve: 'take reserve', remove_wildlife: 'remove all wildlife', }; // Admin commands (ADR-0182): queued now, applied by the region at its next ticks. @@ -781,6 +781,9 @@ async function regionPage(region, params) { const send = commandSender(region, () => commands.load()); let view = null, selected = null, timer = null, frame = 0, beats = 0; let zoom = 1, panX = 0, panY = 0, drag = null; + // Cells marked for a bulk removal (shift+click toggles, shift+drag adds a box of them). + const marked = new Set(); + let box = null; // Tick pace: the last ticks seen and when the tick last moved. const pace = { samples: [], movedAt: performance.now(), lastTick: null, fetchedAt: 0 }; const layers = { players: true, online: true, wildlife: true, pools: true, patches: true, energy: true, carbon: true, nitrogen: true, phosphorus: true, other: true }; @@ -825,15 +828,20 @@ async function regionPage(region, params) { chip('pools', 'pool', 'Pools'), chip('patches', 'patch', 'Patches'), ...channels.map((c) => chip(c.key, c.key, `${c.label} bubbles`))); const zoomBy = (factor) => { setZoom(zoom * factor, 0, 0); }; + const markCount = h('span'); + const markNote = h('span', { class: 'muted small' }); + const markBar = h('div', { class: 'mark-bar glass', hidden: true }, markCount, + h('button', { class: 'danger', onclick: () => removeMarked() }, 'Remove'), + h('button', { class: 'ghost', onclick: () => { marked.clear(); drawMarks(); paint(); } }, 'Clear'), markNote); const mapCard = h('div', { class: 'map-card' }, h('div', { class: 'map-toolbar' }, chipRow, h('div', { class: 'map-zoom' }, h('button', { title: 'Zoom in', onclick: () => zoomBy(1.6) }, '+'), h('button', { title: 'Zoom out', onclick: () => zoomBy(1 / 1.6) }, '−'), h('button', { title: 'Fit the region', onclick: () => { zoom = 1; panX = 0; panY = 0; paint(); } }, '⤢'))), - h('div', { class: 'map-stage' }, canvas, banner, + h('div', { class: 'map-stage' }, canvas, banner, markBar, h('div', { class: 'map-foot' }, - h('div', { class: 'map-hint glass' }, 'Click to inspect · scroll to zoom · drag to pan'), + h('div', { class: 'map-hint glass' }, 'Click to inspect · shift+click or shift+drag to mark cells · scroll to zoom · drag to pan'), h('div', { class: 'scale glass' }, scaleLabel, scaleRule)), tip)); @@ -908,7 +916,7 @@ async function regionPage(region, params) { h('div', { class: 'list-item' }, h('span', { class: 'mono faint' }, `#${c.id}`), h('div', { class: 'grow' }, kindLabels[c.kind] || c.kind, c.count ? ` ×${c.count}` : '', - c.kind === 'remove_cell' || c.kind === 'grant_reserve' ? h('span', { class: 'mono muted' }, ` ${c.target}`) : '', + ['remove_cell', 'grant_reserve', 'take_reserve'].includes(c.kind) ? h('span', { class: 'mono muted' }, ` ${c.target}`) : '', c.kind === 'adopt_tuning' ? ` revision ${c.target}` : '', h('div', { class: 'sub', title: c.author || '' }, (c.author || '').split(' (')[0])), c.applied_tick ? h('span', { class: 'badge alive' }, `tick ${fmtInt(c.applied_tick)}`) : h('span', { class: 'badge warn' }, 'pending')))) @@ -917,7 +925,17 @@ async function regionPage(region, params) { }, }; const schedules = schedulesBlock(region); + const cullReason = reasonInput(), cullNote = h('div', { class: 'note' }); + const cull = () => { + const wild = view ? view.cells.filter((c) => c.flags & 1).length : 0; + if (!confirm(`Remove all ${fmtInt(wild)} wildlife cells? Their bodies and reserves go to the spent pool.`)) return; + send({ kind: 'remove_wildlife' }, 'remove all wildlife', cullNote, cullReason); + }; tabBodies.actions.append( + block('Remove wildlife', null, + h('p', { class: 'hint' }, 'Every wildlife cell at once, in one command; bodies and reserves go to the spent pool. To remove some, shift+click or shift+drag them on the map.'), + h('div', { class: 'form-row' }, cullReason, h('button', { class: 'danger', onclick: cull }, 'Remove all wildlife')), + cullNote), block('Spawn wildlife', null, h('p', { class: 'hint' }, 'Founder wildlife at random spots, funded like any birth.'), h('div', { class: 'form-row' }, h('div', { class: 'field' }, h('label', {}, 'Cells'), spawnCount), spawnReason, @@ -1097,6 +1115,15 @@ async function regionPage(region, params) { ctx.beginPath(); ctx.arc(x, y, size / 2, 0, Math.PI * 2); ctx.fill(); ctx.globalAlpha = 1; if ((highlight && c.account === highlight) || (selected && selected.cell && selected.cell.life === c.life)) ring(x, y, size / 2); + if (marked.has(c.life)) { + ctx.strokeStyle = css('bad'); ctx.lineWidth = 2 * g.dpr; + ctx.beginPath(); ctx.arc(x, y, size / 2 + 2 * g.dpr, 0, Math.PI * 2); ctx.stroke(); + } + } + if (box) { + ctx.strokeStyle = css('bad'); ctx.lineWidth = g.dpr; ctx.setLineDash([5 * g.dpr, 4 * g.dpr]); + ctx.strokeRect(box.x0 * g.dpr, box.y0 * g.dpr, (box.x1 - box.x0) * g.dpr, (box.y1 - box.y0) * g.dpr); + ctx.setLineDash([]); } // Scale bar: a round length about 90 px long. const len = niceLength((90 * g.dpr) / g.s); @@ -1146,6 +1173,34 @@ async function regionPage(region, params) { h('div', { class: 'tip-row' }, h('span', {}, 'Radius'), h('span', {}, fmtLength(d.r)))]; } + // ----- Marked cells ----- + function drawMarks() { + markBar.hidden = marked.size === 0; + if (!view) return; + const wild = view.cells.filter((c) => marked.has(c.life) && c.flags & 1).length; + markCount.textContent = `${fmtInt(marked.size)} marked`; + markNote.textContent = wild === marked.size ? 'wildlife' : `${fmtInt(marked.size - wild)} player${marked.size - wild === 1 ? '' : 's'}`; + } + // One remove_cell command each, queued in turn; the region applies them over its next ticks. + async function removeMarked() { + const lives = [...marked]; + if (!lives.length || !confirm(`Remove ${fmtInt(lives.length)} marked cells? Their bodies and reserves go to the spent pool.`)) return; + let queued = 0, failed = ''; + for (const life of lives) { + markNote.textContent = `queuing ${queued + 1} of ${lives.length}…`; + try { + await api(`/api/regions/${region}/commands?${new URLSearchParams({ kind: 'remove_cell', target: life, reason: 'bulk removal from the map' })}`, true, 'POST'); + marked.delete(life); + ++queued; + } catch (e) { failed = e.code || e.message; break; } + } + commands.load(); + drawMarks(); + paint(); + markNote.textContent = failed ? `queued ${queued}; stopped: ${failed}` : `queued ${queued}`; + markBar.hidden = false; + } + // ----- Inspector ----- function select(found) { selected = found; @@ -1190,6 +1245,12 @@ async function regionPage(region, params) { try { values = grant.read(); } catch (e) { note.className = 'note error'; note.textContent = e.message; return; } send({ kind: 'grant_reserve', target: c.life, ...values }, `grant reserve to ${c.life}`, note, reason).then((ok) => { if (ok) grant.clear(); }); }; + const takeAmount = amountInputs(), takeReason = reasonInput(), takeNote = h('div', { class: 'note' }); + const take = () => { + let values; + try { values = takeAmount.read(); } catch (e) { takeNote.className = 'note error'; takeNote.textContent = e.message; return; } + send({ kind: 'take_reserve', target: c.life, ...values }, `take reserve from ${c.life}`, takeNote, takeReason).then((ok) => { if (ok) takeAmount.clear(); }); + }; const remove = () => { if (!confirm(`Remove ${c.flags & 1 ? 'wildlife' : 'player'} cell ${c.life}? Its body and reserve go to the spent pool.`)) return; send({ kind: 'remove_cell', target: c.life }, `remove cell ${c.life}`, note, reason); @@ -1198,6 +1259,8 @@ async function regionPage(region, params) { h('div', { class: 'inspect-head' }, swatch(cellLayer(c) === 'players' ? 'player' : cellLayer(c)), h('h2', { class: 'grow' }, cellName(c)), locate, close), inspectFacts, block('Grant reserve', null, grant.node, h('div', { class: 'form-row' }, reason, h('button', { onclick: give }, 'Grant')), note), + block('Take reserve', null, h('p', { class: 'hint' }, 'Moves up to these amounts from the cell\'s reserve to the spent pool (never more than it holds).'), + takeAmount.node, h('div', { class: 'form-row' }, takeReason, h('button', { onclick: take }, 'Take')), takeNote), block('Remove', null, h('p', { class: 'hint' }, 'Kills the cell now; its body and reserve go to the spent pool.'), h('button', { class: 'danger', onclick: remove }, 'Remove cell'))); } else { @@ -1324,6 +1387,11 @@ async function regionPage(region, params) { // ----- Pointer ----- canvas.addEventListener('mousemove', (e) => { const rect = canvas.getBoundingClientRect(); + if (box) { + box.x1 = e.clientX - rect.left; box.y1 = e.clientY - rect.top; + tip.hidden = true; + paint(); return; + } if (drag) { if (Math.abs(e.clientX - drag.x) > 3 || Math.abs(e.clientY - drag.y) > 3) { drag.moved = true; canvas.classList.add('dragging'); } panX = drag.panX + (e.clientX - drag.x); panY = drag.panY + (e.clientY - drag.y); @@ -1338,9 +1406,39 @@ async function regionPage(region, params) { tip.style.left = `${Math.min(x, rect.width - tip.offsetWidth - 8)}px`; tip.style.top = `${Math.min(y, rect.height - tip.offsetHeight - 8)}px`; }); - canvas.addEventListener('mouseleave', () => { tip.hidden = true; drag = null; canvas.classList.remove('dragging'); }); - canvas.addEventListener('mousedown', (e) => { drag = { x: e.clientX, y: e.clientY, panX, panY, moved: false }; }); + canvas.addEventListener('mouseleave', () => { tip.hidden = true; drag = null; box = null; canvas.classList.remove('dragging'); paint(); }); + canvas.addEventListener('mousedown', (e) => { + if (e.shiftKey) { + const rect = canvas.getBoundingClientRect(); + const x = e.clientX - rect.left, y = e.clientY - rect.top; + box = { x0: x, y0: y, x1: x, y1: y }; + return; + } + drag = { x: e.clientX, y: e.clientY, panX, panY, moved: false }; + }); canvas.addEventListener('mouseup', (e) => { + if (box) { + const b = box; + box = null; + if (Math.abs(b.x1 - b.x0) < 4 && Math.abs(b.y1 - b.y0) < 4) { + const found = hit(b.x0, b.y0); + if (found && found.cell) { + if (marked.has(found.cell.life)) marked.delete(found.cell.life); else marked.add(found.cell.life); + } + } else if (view) { + // Every shown cell whose centre is inside the box. + const g = geometry(); + const xs = [b.x0, b.x1].map((v) => g.fromX(v * g.dpr)), ys = [b.y0, b.y1].map((v) => g.fromY(v * g.dpr)); + const [x0, x1] = [Math.min(...xs), Math.max(...xs)], [y0, y1] = [Math.min(...ys), Math.max(...ys)]; + for (const c of view.cells) { + const cx = c.x + c.extent / 2, cy = c.y + c.extent / 2; + if (layers[cellLayer(c)] && cx >= x0 && cx <= x1 && cy >= y0 && cy <= y1) marked.add(c.life); + } + } + drawMarks(); + paint(); + return; + } const moved = drag && drag.moved; drag = null; canvas.classList.remove('dragging'); @@ -1397,7 +1495,16 @@ async function regionPage(region, params) { const deposits = Number(raw.deposits_total); const r = rate(); k.tick.set(fmtInt(tick), pace.stalled ? `not advancing for ${fmtDuration((now - pace.movedAt) / 1000)}` : `${r.toFixed(1)} ticks/s`, pace.stalled ? 'warn' : ''); - k.cells.set(fmtInt(players + wild), `${fmtInt(players)} players · ${fmtInt(wild)} wildlife`, players + wild ? '' : 'warn'); + if (raw.caps) { + // Births stop at the organism cap; wildlife buds stop at the wildlife cap. + const cap = Number(raw.caps[0]), wildCap = Number(raw.caps[1]) || cap, lives = players + wild; + const full = lives >= cap ? 'bad' : lives >= wildCap ? 'warn' : ''; + k.cells.set(`${fmtInt(lives)} / ${fmtInt(cap)}`, + `${fmtInt(players)} players · ${fmtInt(wild)} wildlife${wildCap < cap ? ` · wildlife stop at ${fmtInt(wildCap)}` : ''}`, + lives ? full : 'warn', lives / cap, full); + } else { + k.cells.set(fmtInt(players + wild), `${fmtInt(players)} players · ${fmtInt(wild)} wildlife`, players + wild ? '' : 'warn'); + } k.deposits.set(`${fmtInt(deposits)} / ${fmtInt(depositLimit)}`, `${fmtInt(kinds[2])} bubbles · ${fmtInt(kinds[1])} pools`, deposits >= depositLimit ? 'bad' : '', deposits / depositLimit, deposits >= depositLimit ? 'bad' : deposits >= depositLimit * 0.9 ? 'warn' : ''); k.energy.set(fmtEnergy(energy), `${fmtEnergy(freeOf(0))} free to eat`, energy ? '' : 'bad'); @@ -1416,6 +1523,11 @@ async function regionPage(region, params) { banner.hidden = !pace.stalled; banner.textContent = pace.stalled ? `Tick ${fmtInt(tick)} has not advanced for ${fmtDuration((now - pace.movedAt) / 1000)}` : ''; + if (marked.size) { + const alive = new Set(view.cells.map((c) => c.life)); + for (const life of marked) if (!alive.has(life)) marked.delete(life); + drawMarks(); + } if (selected) { if (selected.cell) { const again = view.cells.find((c) => c.life === selected.cell.life); @@ -1505,6 +1617,11 @@ const tuningUnits = [ [/_pj$/, 'pJ'], [/_fg$/, 'fg'], [/_ticks$/, 'ticks'], [/_ms$/, 'ms'], [/_um$/, 'µm'], [/_seconds$/, 's'], [/_mk$/, 'mK'], ]; const tuningSwitches = new Set(['feeding.split_evenly', 'spent.drip_absorb']); +const tuningOptional = [ + ['spent.heat_recycle_per_mille', '0', 'share of the heat returned to the spent pool each tick'], + ['spent.drip_absorb', '0', 'a drip at the deposit limit joins an existing bubble'], + ['reproduction.wildlife_cap', '0', 'wildlife buds refused at this many lives (0: the organism cap); the rest are for players'], +]; const isSwitch = (key) => tuningSwitches.has(key) || key.endsWith('.enabled'); function tuningLabel(key, section) { let name = key.slice(section.length + 1); @@ -1584,6 +1701,13 @@ async function tuningPage() { // ----- Guided editor ----- const groups = parseTuning(base.text); + // Optional keys a revision may lack, shown at the value that keeps the historical law. + for (const [key, value, note] of tuningOptional) { + const name = key.split('.')[0]; + let group = groups.find((g) => g.name === name); + if (!group) { group = { name, about: '', settings: [] }; groups.push(group); } + if (!group.settings.some((s) => s.key === key)) group.settings.push({ key, value, note, lead: '' }); + } const baseValues = new Map(groups.flatMap((g) => g.settings.map((s) => [s.key, s.value]))); const edits = new Map(); // key -> normalized new value (only where it differs) const problems = new Map(); // key -> message (bad input or the server's refusal) diff --git a/apps/evo-admin-api/portal/style.css b/apps/evo-admin-api/portal/style.css index 1fea817..d456a97 100644 --- a/apps/evo-admin-api/portal/style.css +++ b/apps/evo-admin-api/portal/style.css @@ -394,6 +394,8 @@ dl.facts dd { margin: 0; min-width: 0; overflow-wrap: anywhere; } .map-zoom button:hover { background: var(--panel-3); } .map-foot { position: absolute; left: 12px; right: 12px; bottom: 10px; display: flex; justify-content: space-between; align-items: flex-end; gap: 10px; pointer-events: none; } .map-hint { font-size: 12px; color: var(--muted); padding: 3px 9px; } +.mark-bar { position: absolute; left: 12px; top: 12px; display: flex; align-items: center; gap: 8px; padding: 6px 8px 6px 12px; font-size: 13px; font-weight: 500; } +.mark-bar button { padding: 3px 10px; } .scale { font-size: 11.5px; color: var(--muted); padding: 4px 9px 3px; text-align: center; } .scale .rule { height: 6px; border: 1.5px solid var(--muted); border-top: 0; margin-top: 2px; } .map-banner { diff --git a/apps/evo-client/panels.cpp b/apps/evo-client/panels.cpp index d234568..3788445 100644 --- a/apps/evo-client/panels.cpp +++ b/apps/evo-client/panels.cpp @@ -610,7 +610,7 @@ const char* bud_text(network::CellularBudOutcome outcome) { "Bud created: a descendant split off", "Bud failed: not fully grown", "Bud failed: not enough resources", - "Bud failed: no space beside you"}; + "Bud failed: no space beside you, or the region is full"}; const auto index = static_cast(outcome); return index < text.size() ? text.at(index) : ""; } diff --git a/apps/evo-server/cellular_bridge.hpp b/apps/evo-server/cellular_bridge.hpp index 6ccb489..0a981e0 100644 --- a/apps/evo-server/cellular_bridge.hpp +++ b/apps/evo-server/cellular_bridge.hpp @@ -222,6 +222,12 @@ class CellularBridge { return result; }; sessions_->replicate(tick, source); + // A tuning adoption changes what a bud costs, so cached costs hold for one rules set. + if (auto rules = server::encode_cellular_revamp_rules(state.revamp_rules()); + rules != bud_rules_) { + bud_rules_ = std::move(rules); + bud_costs_.clear(); + } for (const auto& life : state.lives()) { if (life.presence == server::CellularPresence::suspended) continue; @@ -378,13 +384,11 @@ class CellularBridge { const auto before = deposit_stock_.find(patch.id); deposit.drained = before != deposit_stock_.end() && (patch.available.energy.value < before->second.energy.value || - std::ranges::any_of( - std::array{0, 1, 2, 3}, - [&](int c) { - const auto i = static_cast(c); - return patch.available.matter.at(i).value < - before->second.matter.at(i).value; - })); + std::ranges::any_of(std::array{0, 1, 2, 3}, [&](int c) { + const auto i = static_cast(c); + return patch.available.matter.at(i).value < + before->second.matter.at(i).value; + })); seen_stock_[patch.id] = patch.available; // Rules 12 (v13): a bubble's world velocity, current plus induced drift, so the // client can carry it between perceptions. @@ -700,6 +704,7 @@ class CellularBridge { std::vector offers_; // Last offer view sent to each owner. std::map, std::optional> bud_costs_; + std::vector bud_rules_; // The rules bud_costs_ were computed under. // ADR-0136: deposit stocks seen at the last replicated tick, and this tick's. std::map deposit_stock_, seen_stock_; std::vector> owned_; // At last replication. diff --git a/deploy/kubernetes/region/dev/tuning/cellular-revamp.tuning b/deploy/kubernetes/region/dev/tuning/cellular-revamp.tuning index 2a0d98b..0e893a3 100644 --- a/deploy/kubernetes/region/dev/tuning/cellular-revamp.tuning +++ b/deploy/kubernetes/region/dev/tuning/cellular-revamp.tuning @@ -72,6 +72,7 @@ reproduction.bud_fee_p_fg = 10_000 reproduction.bud_fee_o_fg = 60_000 reproduction.bud_fee_scale_percent = 50 # 0 disables the fee; 100 charges the listed amounts reproduction.organism_cap = 256 # births refused at this many lives (an organism counts once) +reproduction.wildlife_cap = 200 # wildlife buds refused at this many lives: the rest are for players # Multicellular organisms (reproduction plan section 6). organism.load_per_mille = 500 # share of the extra members' mass loading one cell's thrust diff --git a/docs/STATUS.md b/docs/STATUS.md index 173227a..e24b107 100644 --- a/docs/STATUS.md +++ b/docs/STATUS.md @@ -1,5 +1,13 @@ # Project status and next steps +## Testing a full region - 2026-10-28 + +The Bud button follows a tuning adoption at once (the region's bud-cost cache was keyed by +genome only). `reproduction.wildlife_cap` keeps lives above it for players' buds. Two admin +commands (schema 67): take reserve from a cell, and remove all wildlife; the region map marks +cells (shift+click, shift+drag) for bulk removal. The 256-life organism cap is unchanged. See +[ADR-0182](adr/0182-admin-portal-and-world-tuning.md) section 16. + ## Opening regions from the portal - 2026-10-28 The Regions page can open a fresh region in place of the one DEV serves: the admin API diff --git a/docs/adr/0182-admin-portal-and-world-tuning.md b/docs/adr/0182-admin-portal-and-world-tuning.md index 378d8ec..e504b7f 100644 --- a/docs/adr/0182-admin-portal-and-world-tuning.md +++ b/docs/adr/0182-admin-portal-and-world-tuning.md @@ -351,6 +351,35 @@ Deployments, routes and ports; a multi-world admin API and broker). - **Network.** The portal's NetworkPolicy adds egress to 172.10.1.160:443 (Gitea through the node's ingress) and to the argocd-server pods on 8080. +### 16. Testing a full region (delivered 2026-10-28, schema 67) + +Playtesting region 16 (230 spawned wildlife under the 256-life cap) found three gaps. + +- **Stale bud costs.** The region host caches each genome's bud cost for the client's Bud + button. The cache was keyed by genome only, so after a tuning adoption players saw the old + cost (or "cannot bud") until the region restarted. The cache now clears when the rules' + encoding changes. +- **Wildlife cap.** Wildlife bud whenever they can pay, so at the organism cap every slot a + death freed went to a wildlife bud before a player's bud arrived; the player saw "no space". + `reproduction.wildlife_cap` (rules field `wildlife_cap`, 0..organism cap, 0 = the organism + cap) refuses buds of a parent without an account at that many lives, keeping the slots above + it for players. Spawning still answers to the organism cap. It takes bits 17-31 of the + word holding the energy cycle (section 14), so rules without it keep their bytes and digests; + the key is optional, adoptable live, and the DEV file sets 200. The region view reports + both caps (`caps`), and the region page's Population shows lives against the cap. +- **Take and cull.** Two admin command kinds: `take_reserve` (8) moves up to the given amounts + from one life's reserve to the spent pool, per channel never more than it holds (the inverse + of `grant_reserve`); `remove_wildlife` (9) removes every life without an account in one + command, each as `remove_cell` does (body and reserve to the spent pool, a removed corpse). + Schema 67 widens the kind check and `admin_enqueue_command_v1`. The portal adds Take reserve + to the cell inspector, Remove all wildlife to Actions, and marking on the map (shift+click, + shift+drag a box) to remove the marked cells, one `remove_cell` each. + +Not changed: the organism cap stays at most 256 (`max_cellular_tick_lives`). That bound sizes +the batch trace, checkpoints, migration traces and the database's trace checks, and region 16 +already runs at about a quarter of real time with about 250 lives. Raising it is a separate +format and performance change. + ## Delivery order 1. Read-only portal: login, accounts (from existing data), regions, region view (schema 61, diff --git a/include/evo/biology/cellular_revamp_tuning.hpp b/include/evo/biology/cellular_revamp_tuning.hpp index 27ff7f4..eb35f0e 100644 --- a/include/evo/biology/cellular_revamp_tuning.hpp +++ b/include/evo/biology/cellular_revamp_tuning.hpp @@ -57,6 +57,7 @@ struct CellularRevampTuning { std::int64_t reproduction_bud_fee_e_pj{}, reproduction_bud_fee_c_fg{}, reproduction_bud_fee_n_fg{}, reproduction_bud_fee_p_fg{}, reproduction_bud_fee_o_fg{}; std::int64_t reproduction_bud_fee_scale_percent{}, reproduction_organism_cap{}; + std::int64_t reproduction_wildlife_cap{}; // Optional; 0 is the organism cap. // Multicellular organisms. std::int64_t organism_load_per_mille{}, organism_emerge_members{}, organism_emerge_mass_fg{}, organism_emerge_reserve_pj{}; diff --git a/include/evo/server/lifecycle/cellular_lives.hpp b/include/evo/server/lifecycle/cellular_lives.hpp index ad2c714..4bae04d 100644 --- a/include/evo/server/lifecycle/cellular_lives.hpp +++ b/include/evo/server/lifecycle/cellular_lives.hpp @@ -196,6 +196,10 @@ enum class CellularAdminKind : std::uint8_t { // A u16 in the trace. // whose canonical rules encoding (encode_cellular_revamp_rules) has the SHA-256 held in the // energy, carbon, nitrogen and phosphorus amounts (little-endian words; `other` zero). adopt_tuning = 7, + // Schema 67: up to `amount` (per channel, never more than it holds) moved from the + // `target` life's reserve to the spent pool; and every wildlife life removed as by 1. + take_reserve = 8, + remove_wildlife = 9, }; struct CellularAdminCommand { std::uint64_t id{}; // The durable queue id. diff --git a/include/evo/server/lifecycle/cellular_revamp.hpp b/include/evo/server/lifecycle/cellular_revamp.hpp index 11bc9d1..a89e9fa 100644 --- a/include/evo/server/lifecycle/cellular_revamp.hpp +++ b/include/evo/server/lifecycle/cellular_revamp.hpp @@ -51,6 +51,9 @@ struct CellularRevampRules { accounting::Inventory bud_fee{}; std::uint32_t bud_fee_scale_percent{}; std::uint32_t organism_cap{256}; + // Wildlife buds are refused at this many lives (0: the organism cap), leaving the slots + // above it to players; spawning still answers to the organism cap. Below 32,768. + std::uint32_t wildlife_cap{}; // Multicellular organisms (reproduction plan section 6): the share of the extra members' // mass carried as load on one cell's thrust, and the emergence threshold. std::uint32_t organism_load_per_thousand{500}; diff --git a/migrations/0067_admin_take_and_cull.sql b/migrations/0067_admin_take_and_cull.sql new file mode 100644 index 0000000..3dd9167 --- /dev/null +++ b/migrations/0067_admin_take_and_cull.sql @@ -0,0 +1,54 @@ +-- Admin take and cull (ADR-0182 section 16, 2026-10-28). Two more admin command kinds for +-- testing a live region: take_reserve (8) moves up to the given amounts from one life's +-- reserve to the spent pool, the inverse of grant_reserve; remove_wildlife (9) removes every +-- life without an account at once, as remove_cell does one. + +ALTER TABLE evolution.admin_commands DROP CONSTRAINT admin_commands_kind_check; +ALTER TABLE evolution.admin_commands ADD CONSTRAINT admin_commands_kind_check + CHECK (kind BETWEEN 1 AND 9); + +-- Queues a command (the same shapes the owner accepts). Spawning takes its identities from the +-- world's life allocator, so they never meet a player's. +CREATE OR REPLACE FUNCTION evolution.admin_enqueue_command_v1(p_world evolution.u64, + p_region evolution.u64, p_kind integer, p_count integer, p_target evolution.u64, + p_energy evolution.u64, p_carbon evolution.u64, p_nitrogen evolution.u64, + p_phosphorus evolution.u64, p_other evolution.u64, p_subject text, p_reason text) +RETURNS TABLE (command_id bigint, target evolution.u64) +LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, pg_temp AS $$ +#variable_conflict use_column +DECLARE + has_amount boolean := p_energy + p_carbon + p_nitrogen + p_phosphorus + p_other > 0; + first numeric := p_target; +BEGIN + IF NOT ((p_kind IN (1, 2, 8) AND p_target > 0 AND p_count = 0 + AND has_amount = (p_kind IN (2, 8))) + OR (p_kind IN (3, 5) AND p_target = 0 AND p_count BETWEEN 1 AND 256 AND has_amount) + OR (p_kind = 4 AND p_target = 0 AND p_count = 0 AND has_amount) + OR (p_kind = 6 AND p_count BETWEEN 1 AND 64 AND NOT has_amount) + OR (p_kind = 9 AND p_target = 0 AND p_count = 0 AND NOT has_amount)) THEN + RAISE EXCEPTION 'invalid admin command' USING ERRCODE = '22023'; + END IF; + IF NOT EXISTS (SELECT 1 FROM evolution.region_leases l + WHERE l.world_id = p_world AND l.region_id = p_region) THEN + RAISE EXCEPTION 'unknown region' USING ERRCODE = '22023'; + END IF; + IF p_kind = 6 THEN + SELECT a.next_identity INTO first FROM evolution.life_allocators a + WHERE a.world_id = p_world FOR UPDATE; + IF first IS NULL OR first + p_count > 9223372036854775808 THEN + RAISE EXCEPTION 'no identities for wildlife' USING ERRCODE = '22023'; + END IF; + UPDATE evolution.life_allocators SET next_identity = first + p_count + WHERE world_id = p_world; + END IF; + RETURN QUERY + WITH queued AS ( + INSERT INTO evolution.admin_commands AS q(world_id, region_id, kind, cell_count, target, + energy, carbon, nitrogen, phosphorus, other, author_subject, reason) + VALUES (p_world, p_region, p_kind, p_count, first, p_energy, p_carbon, p_nitrogen, + p_phosphorus, p_other, p_subject, coalesce(p_reason, '')) + RETURNING q.command_id, q.target) + SELECT queued.command_id, queued.target FROM queued; +END $$; + +INSERT INTO evolution.schema_migrations(version,sha256) VALUES(67,:'migration_sha_67'); diff --git a/migrations/apply.sql b/migrations/apply.sql index 4dc539e..6028fcf 100644 --- a/migrations/apply.sql +++ b/migrations/apply.sql @@ -142,6 +142,7 @@ SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname='evolution') SELECT :'history_v63' || ',64:' || :'migration_sha_64' AS history_v64 \gset SELECT :'history_v64' || ',65:' || :'migration_sha_65' AS history_v65 \gset SELECT :'history_v65' || ',66:' || :'migration_sha_66' AS history_v66 \gset + SELECT :'history_v66' || ',67:' || :'migration_sha_67' AS history_v67 \gset SELECT :'history' = :'history_v22' AS at_v22, :'history' = :'history_v23' AS at_v23, :'history' = :'history_v24' AS at_v24, @@ -186,8 +187,10 @@ SELECT EXISTS (SELECT 1 FROM pg_catalog.pg_namespace WHERE nspname='evolution') :'history' = :'history_v63' AS at_v63, :'history' = :'history_v64' AS at_v64, :'history' = :'history_v65' AS at_v65, - :'history' = :'history_v66' AS at_v66 \gset - \if :at_v66 + :'history' = :'history_v66' AS at_v66, + :'history' = :'history_v67' AS at_v67 \gset + \if :at_v67 + \elif :at_v66 \elif :at_v65 \elif :at_v64 \elif :at_v63 @@ -613,7 +616,8 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, coalesce(max(version), 0) = 63 AS at_v63, coalesce(max(version), 0) = 64 AS at_v64, coalesce(max(version), 0) = 65 AS at_v65, - coalesce(max(version), 0) = 66 AS at_v66 + coalesce(max(version), 0) = 66 AS at_v66, + coalesce(max(version), 0) = 67 AS at_v67 FROM evolution.schema_migrations \gset \if :at_v24 \ir 0025_cellular_v2_bundle.sql @@ -848,6 +852,7 @@ SELECT coalesce(max(version), 0) = 24 AS at_v24, \elif :at_v64 \elif :at_v65 \elif :at_v66 +\elif :at_v67 \else \echo 'Unknown or changed migration history after v43' DO $$ BEGIN RAISE EXCEPTION 'unknown or changed migration history'; END $$; @@ -944,6 +949,10 @@ SELECT coalesce(max(version), 0) = 65 AS needs_v66 FROM evolution.schema_migrati \if :needs_v66 \ir 0066_tuning_revisions.sql \endif +SELECT coalesce(max(version), 0) = 66 AS needs_v67 FROM evolution.schema_migrations \gset +\if :needs_v67 + \ir 0067_admin_take_and_cull.sql +\endif -- Effective-privilege audit on every run, including no-ops (ADR-0060). Attributes -- alone are insufficient: predefined roles such as pg_write_all_data, PUBLIC -- grants or SET-able memberships would bypass the fenced functions. Checks the diff --git a/src/biology/cellular_revamp_tuning.cpp b/src/biology/cellular_revamp_tuning.cpp index 139af6a..f2deab5 100644 --- a/src/biology/cellular_revamp_tuning.cpp +++ b/src/biology/cellular_revamp_tuning.cpp @@ -87,6 +87,7 @@ constexpr std::array fields{ Field{"reproduction.bud_fee_scale_percent", &CellularRevampTuning::reproduction_bud_fee_scale_percent, 0, 100}, Field{"reproduction.organism_cap", &CellularRevampTuning::reproduction_organism_cap, 1, 256}, + Field{"reproduction.wildlife_cap", &CellularRevampTuning::reproduction_wildlife_cap, 0, 256}, Field{"organism.load_per_mille", &CellularRevampTuning::organism_load_per_mille, 0, 10'000}, Field{"organism.emerge_members", &CellularRevampTuning::organism_emerge_members, 2, 10'000}, Field{"organism.emerge_mass_fg", &CellularRevampTuning::organism_emerge_mass_fg, 0, @@ -262,6 +263,7 @@ parse_cellular_revamp_tuning(std::string_view text) { fields.at(index).key != "feeding.split_evenly" && fields.at(index).key != "spent.heat_recycle_per_mille" && fields.at(index).key != "spent.drip_absorb" && + fields.at(index).key != "reproduction.wildlife_cap" && fields.at(index).key != "reproduction.safety_version" && fields.at(index).key != "body.growth_reserve_seconds" && fields.at(index).key != "reproduction.split_launch_um_per_s") @@ -270,6 +272,9 @@ parse_cellular_revamp_tuning(std::string_view text) { if (tuning.version != cellular_revamp_tuning_version) return std::unexpected{ error(CellularTuningErrorKind::unsupported_version, 0, "tuning.version")}; + if (tuning.reproduction_wildlife_cap > tuning.reproduction_organism_cap) + return std::unexpected{ + error(CellularTuningErrorKind::inconsistent, 0, "reproduction.wildlife_cap")}; if (tuning.playtest_starting_wildlife_cells >= tuning.reproduction_organism_cap) return std::unexpected{ error(CellularTuningErrorKind::inconsistent, 0, "playtest.starting_wildlife_cells")}; diff --git a/src/server/admin/admin_api.cpp b/src/server/admin/admin_api.cpp index 9ee0a20..c8ce17e 100644 --- a/src/server/admin/admin_api.cpp +++ b/src/server/admin/admin_api.cpp @@ -578,11 +578,18 @@ OpsResponse AdminApi::set_window(std::uint64_t region, std::string_view query_te } namespace { -// Kinds 1-6 are queued by name; adopt_tuning (7) only through a tuning revision. -constexpr std::array command_kinds{ - "", "remove_cell", "grant_reserve", "add_bubbles", - "add_pool", "release_pool", "spawn_wildlife", "adopt_tuning"}; -constexpr std::size_t queued_kinds = 7; +// Every kind is queued by name but adopt_tuning (7), which comes only through a tuning revision. +constexpr std::array command_kinds{"", + "remove_cell", + "grant_reserve", + "add_bubbles", + "add_pool", + "release_pool", + "spawn_wildlife", + "adopt_tuning", + "take_reserve", + "remove_wildlife"}; +constexpr std::size_t tuning_kind = 7; std::string hex(std::span bytes) { constexpr std::string_view digits = "0123456789abcdef"; @@ -1023,7 +1030,7 @@ OpsResponse AdminApi::enqueue(std::uint64_t region, std::string_view query_text, kind_text ? std::ranges::find(command_kinds, *kind_text) : command_kinds.end(); if (!kind_text || kind_text->empty() || kind == command_kinds.end()) return error(400, "bad_kind"); - if (static_cast(kind - command_kinds.begin()) >= queued_kinds) + if (static_cast(kind - command_kinds.begin()) == tuning_kind) return error(400, "bad_kind"); // Absent numbers are zero; present ones must be plain u64 decimals. const auto value = [&](std::string_view name) -> std::optional { @@ -1107,7 +1114,7 @@ OpsResponse AdminApi::set_schedule(std::uint64_t region, std::string_view query_ kind_text ? std::ranges::find(command_kinds, *kind_text) : command_kinds.end(); if (!kind_text || kind_text->empty() || kind == command_kinds.end()) return error(400, "bad_kind"); - if (static_cast(kind - command_kinds.begin()) >= queued_kinds) + if (static_cast(kind - command_kinds.begin()) == tuning_kind) return error(400, "bad_kind"); const auto value = [&](std::string_view name, std::uint64_t absent) -> std::optional { diff --git a/src/server/lifecycle/cellular_admin_view.cpp b/src/server/lifecycle/cellular_admin_view.cpp index 2e40ad0..4424518 100644 --- a/src/server/lifecycle/cellular_admin_view.cpp +++ b/src/server/lifecycle/cellular_admin_view.cpp @@ -93,6 +93,12 @@ std::string render_cellular_admin_view(const CellularLives& state, out.push_back(','); append(out, rules.heat_recycle_per_thousand); out += rules.drip_absorb ? ",1]" : ",0]"; + // The organism cap and the wildlife cap (0: the organism cap). + out += ",\"caps\":["; + append(out, rules.organism_cap); + out.push_back(','); + append(out, rules.wildlife_cap); + out.push_back(']'); } out += ",\"cells_total\":"; append(out, lives.size()); diff --git a/src/server/lifecycle/cellular_lives.cpp b/src/server/lifecycle/cellular_lives.cpp index 2c05740..f8673f7 100644 --- a/src/server/lifecycle/cellular_lives.cpp +++ b/src/server/lifecycle/cellular_lives.cpp @@ -237,8 +237,10 @@ void write_revamp_offers(Writer& out, const CellularRevampRules& r) { out.put(r.split_launch_um_per_s, 4); out.put(b.carbon_for_light); out.put(r.offer_interval_ticks, 4); - // The offer interval's reserved word: the heat recycle share and the absorbing drip. - out.put(r.heat_recycle_per_thousand | (r.drip_absorb ? 0x10000U : 0U), 4); + // The offer interval's reserved word: the heat recycle share (bits 0-15), the absorbing + // drip (bit 16) and the wildlife cap (bits 17-31). + out.put(r.heat_recycle_per_thousand | (r.drip_absorb ? 0x10000U : 0U) | (r.wildlife_cap << 17U), + 4); for (const auto& m : r.mutations) { out.put(m.enabled ? 1 : 0, 1); out.zeros(3); @@ -288,7 +290,8 @@ bool read_revamp_offers(Reader& in, CellularRevampRules& r) { const auto cycle = in.get(4); r.heat_recycle_per_thousand = static_cast(cycle & 0xFFFFU); r.drip_absorb = (cycle & 0x10000U) != 0; - zero = zero && (cycle & ~0x1FFFFULL) == 0; + r.wildlife_cap = static_cast(cycle >> 17U); + zero = zero && (cycle >> 32U) == 0; for (auto& m : r.mutations) { const auto enabled = in.get(1); zero = zero && enabled <= 1 && in.get(3) == 0; @@ -1537,6 +1540,10 @@ bool cellular_admin_command_valid(const CellularAdminCommand& c) noexcept { c.target <= cellular_bud_namespace - c.count; case CellularAdminKind::adopt_tuning: return c.id != 0 && c.count == 0 && c.target != 0 && some && c.amount.matter[3].value == 0; + case CellularAdminKind::take_reserve: + return c.id != 0 && c.target != 0 && c.count == 0 && some; + case CellularAdminKind::remove_wildlife: + return c.id != 0 && c.target == 0 && c.count == 0 && !some; } return false; } @@ -1556,6 +1563,35 @@ CellularLives::admin_candidate(std::span commands, if (!candidate) return std::unexpected(candidate.error()); std::vector report; + // A removed life's body and reserve go to the spent pool, and it leaves a corpse. + const auto remove_life = [&](State& next, std::vector::iterator life) { + if (!next.archive.record_death(life->identity.organism, {tick()})) + return false; + auto single = *life; + single.revamp.members = 1; // A corpse records the single-cell extent. + const auto extent = budget_for( + next.archive, single, next.config.ambient_temperature_millikelvin, next.revamp.body); + if (!extent || !add_inventory(next.spent, life->body) || + !add_inventory(next.spent, life->reserve)) + return false; + CellularOwnedCorpse corpse{life->identity.life, + life->identity.organism, + life->source, + tick(), + life->position, + life->growth, + extent->phenotype.extent, + {}, + biology::CellularDeathCause::removed, + 0, + life->parent_life, + life->offspring_genome}; + const auto at = std::ranges::lower_bound(next.corpses, corpse.organism, {}, + &CellularOwnedCorpse::organism); + next.corpses.insert(at, corpse); + next.lives.erase(life); + return true; + }; for (const auto& command : commands) { // Each command works on a copy, kept only when it applies and still closes. auto attempt = restore((*candidate)->snapshot(), world(), region(), frame(), tick()); @@ -1568,34 +1604,36 @@ CellularLives::admin_candidate(std::span commands, const bool found = life != next.lives.end() && life->identity.life == command.target; switch (command.kind) { case CellularAdminKind::remove_cell: - if (found && next.archive.record_death(life->identity.organism, {tick()})) { - auto single = *life; - single.revamp.members = 1; // A corpse records the single-cell extent. - const auto extent = - budget_for(next.archive, single, next.config.ambient_temperature_millikelvin, - next.revamp.body); - if (extent && add_inventory(next.spent, life->body) && - add_inventory(next.spent, life->reserve)) { - CellularOwnedCorpse corpse{life->identity.life, - life->identity.organism, - life->source, - tick(), - life->position, - life->growth, - extent->phenotype.extent, - {}, - biology::CellularDeathCause::removed, - 0, - life->parent_life, - life->offspring_genome}; - const auto at = std::ranges::lower_bound(next.corpses, corpse.organism, {}, - &CellularOwnedCorpse::organism); - next.corpses.insert(at, corpse); - next.lives.erase(life); - applied = true; - } + applied = found && remove_life(next, life); + break; + case CellularAdminKind::remove_wildlife: { + std::vector wild; + for (const auto& each : next.lives) + if (each.account == LifeAccount{}) + wild.push_back(each.identity.life); + applied = !wild.empty(); + for (const auto id : wild) { + const auto at = std::ranges::lower_bound( + next.lives, id, {}, [](const auto& v) { return v.identity.life; }); + applied = applied && remove_life(next, at); } break; + } + case CellularAdminKind::take_reserve: { + if (!found) + break; + auto amount = command.amount; // Never more than the reserve holds. + for (std::size_t c = 0; c < 5; ++c) { + auto& want = c == 0 ? amount.energy.value : amount.matter[c - 1].value; + const auto have = + c == 0 ? life->reserve.energy.value : life->reserve.matter[c - 1].value; + want = std::min(want, have); + } + applied = amount != accounting::Inventory{} && + subtract_inventory(life->reserve, amount) && + add_inventory(next.spent, amount); + break; + } case CellularAdminKind::grant_reserve: applied = found && add_inventory(life->reserve, command.amount) && add_inventory(next.boundary.incoming, command.amount); @@ -3604,6 +3642,9 @@ CellularLives::advance_tick_with_mutations(std::span i if (identity == 0 || !*position || next_lives.size() >= biology::max_cellular_tick_lives || (revamp_rules && next_lives.size() >= state_->revamp.organism_cap) || + (revamp_rules && parent->account == LifeAccount{} && + state_->revamp.wildlife_cap != 0 && + next_lives.size() >= state_->revamp.wildlife_cap) || next_archive.organism(identity)) { if (!twin) bud_results.push_back({request.life_id, 0, CellularBudResult::no_placement}); diff --git a/src/server/lifecycle/cellular_revamp.cpp b/src/server/lifecycle/cellular_revamp.cpp index 8988012..9b8005f 100644 --- a/src/server/lifecycle/cellular_revamp.cpp +++ b/src/server/lifecycle/cellular_revamp.cpp @@ -63,9 +63,10 @@ bool cellular_revamp_valid(const CellularRevampRules& rules) noexcept { std::ranges::all_of(rules.bud_fee.matter, [](const accounting::Femtograms& f) { return f.value <= most; }) && rules.organism_cap != 0 && rules.organism_cap <= biology::max_cellular_tick_lives && - rules.organism_load_per_thousand <= 10'000 && rules.emerge_members >= 2 && - rules.emerge_members <= 10'000 && rules.emerge_mass_fg <= most && - rules.emerge_reserve_pj <= most && cellular_revamp_offer_rules_valid(rules); + rules.wildlife_cap <= rules.organism_cap && rules.organism_load_per_thousand <= 10'000 && + rules.emerge_members >= 2 && rules.emerge_members <= 10'000 && + rules.emerge_mass_fg <= most && rules.emerge_reserve_pj <= most && + cellular_revamp_offer_rules_valid(rules); } biology::CellularHandling cellular_loaded_handling(const biology::CellularHandling& handling, @@ -353,6 +354,7 @@ CellularRevampRules cellular_revamp_rules(const biology::CellularRevampTuning& t accounting::Femtograms{u64(t.reproduction_bud_fee_o_fg)}}}, .bud_fee_scale_percent = u32(t.reproduction_bud_fee_scale_percent), .organism_cap = u32(t.reproduction_organism_cap), + .wildlife_cap = u32(t.reproduction_wildlife_cap), .organism_load_per_thousand = u32(t.organism_load_per_mille), .emerge_members = u32(t.organism_emerge_members), .emerge_mass_fg = u64(t.organism_emerge_mass_fg), diff --git a/tests/cellular_admin_view_tests.cpp b/tests/cellular_admin_view_tests.cpp index 1630501..3554ddd 100644 --- a/tests/cellular_admin_view_tests.cpp +++ b/tests/cellular_admin_view_tests.cpp @@ -134,11 +134,12 @@ void renders_the_drip() { .drip_bubble_pj = 20'000'000, .drip_bubble_fg = 1'000'000, .heat_recycle_per_thousand = 1'000, - .drip_absorb = true}; + .drip_absorb = true, + .wildlife_cap = 200}; state = checked(state->revamp_upgrade_candidate(rules), "revamp upgrade"); const auto view = render_cellular_admin_view(*state, {}); - require(view.find(",\"drip\":[20,20000000,1000000,1000,1],\"cells_total\":") != - std::string::npos, + require(view.find(",\"drip\":[20,20000000,1000000,1000,1],\"caps\":[256,200]," + "\"cells_total\":") != std::string::npos, "rules-13 drip and energy cycle"); } } // namespace diff --git a/tests/cellular_revamp_owner_tests.cpp b/tests/cellular_revamp_owner_tests.cpp index 45c89d6..5cccf26 100644 --- a/tests/cellular_revamp_owner_tests.cpp +++ b/tests/cellular_revamp_owner_tests.cpp @@ -968,6 +968,98 @@ void admin_commands_apply_and_replay() { require(!decode_cellular_batch(mangled), "a trace 4 with commands decoded"); } +// Schema 67: take_reserve moves at most what a reserve holds to the spent pool, and +// remove_wildlife removes every life without an account in one command. +void take_and_cull() { + using Kind = CellularAdminKind; + for (const auto& bad : {CellularAdminCommand{1, Kind::take_reserve, 0, 100, {}}, + CellularAdminCommand{1, Kind::take_reserve, 0, 0, {{1}, {}}}, + CellularAdminCommand{1, Kind::remove_wildlife, 1, 0, {}}, + CellularAdminCommand{1, Kind::remove_wildlife, 0, 100, {}}, + CellularAdminCommand{1, Kind::remove_wildlife, 0, 0, {{1}, {}}}}) + require(!cellular_admin_command_valid(bad), "an invalid take or cull shape was accepted"); + auto live = revamp_region(); + checked(live->advance_tick(swim(*live, {})), "tick before the commands"); + live = checked(live->admin_candidate(std::vector{ + {1, Kind::spawn_wildlife, 3, 900'000, {}}}), + "wildlife to cull"); + require(live->lives().size() == 5, "the wildlife was not spawned"); + const auto reserve = life_of(*live, 100).reserve; + const auto spent = live->spent(); + accounting::Inventory carbon{}; + carbon.matter[0].value = 1; + const std::vector commands{ + {2, Kind::take_reserve, 0, 100, {{reserve.energy.value + 5}, {}}}, // All of it. + {3, Kind::take_reserve, 0, 100, {{1}, {}}}, // Nothing left to take: refused. + {4, Kind::take_reserve, 0, 424'242, {{1}, {}}}, // No such life: refused. + {5, Kind::remove_wildlife, 0, 0, {}}, + {6, Kind::remove_wildlife, 0, 0, {}}, // No wildlife left: refused. + }; + std::vector results; + auto after = checked(live->admin_candidate(commands, &results), "take and cull apply"); + require(results.size() == 5 && results[0].applied && !results[1].applied && + !results[2].applied && results[3].applied && !results[4].applied, + "unexpected take and cull results"); + closed(*after); + require(life_of(*after, 100).reserve.energy.value == 0 && + life_of(*after, 100).reserve.matter == reserve.matter, + "the take did not empty only the energy"); + require(after->lives().size() == 2 && + std::ranges::all_of(after->lives(), + [](const auto& l) { return l.account != LifeAccount{}; }), + "the cull missed wildlife or removed a player"); + require(after->spent().energy.value > spent.energy.value + reserve.energy.value, + "the taken energy and culled cells did not reach the spent pool"); + std::size_t removed = 0; + for (const auto& corpse : after->corpses()) + if (corpse.cause == biology::CellularDeathCause::removed) + ++removed; + require(removed == 3, "each culled cell should leave a removed corpse"); + require(restore(*after)->snapshot() == after->snapshot(), "take and cull do not restore"); + require(checked(live->admin_candidate(commands), "again")->snapshot() == after->snapshot(), + "take and cull are not deterministic"); +} + +// The wildlife cap keeps the slots above it for players: wildlife buds are refused there, +// while an uncapped twin buds. It rides the heat word of the rules encoding. +void the_wildlife_cap_leaves_room() { + auto rules = revamp(); + auto capped_rules = rules; + capped_rules.wildlife_cap = 32; + require(cellular_revamp_valid(capped_rules) && + encode_cellular_revamp_rules(capped_rules).size() == + encode_cellular_revamp_rules(rules).size() && + encode_cellular_revamp_rules(capped_rules) != encode_cellular_revamp_rules(rules), + "the wildlife cap is not a same-size distinct encoding"); + auto over = capped_rules; + over.wildlife_cap = over.organism_cap + 1; + require(!cellular_revamp_valid(over), "a wildlife cap above the organism cap was valid"); + auto source = opening(77, true, 64, false); + checked(source->advance_tick({}), "opening tick"); + source = checked(source->migration_upgrade_candidate(), "boundary"); + source = checked(source->maturation_upgrade_candidate(), "maturation"); + source = checked(source->inheritance_upgrade_candidate(), "inheritance"); + source = checked(source->photosynthesis_upgrade_candidate({0, 1, {0}}), "light"); + source = checked(source->liquid_upgrade_candidate(liquid()), "liquid"); + auto free = checked(source->revamp_upgrade_candidate(rules, 32, 900'000), "free wildlife"); + auto capped = checked(source->revamp_upgrade_candidate(capped_rules, 32, 900'000), "capped"); + require(restore(*capped)->revamp_rules() == capped_rules, "the wildlife cap did not restore"); + const auto first = free->next_bud_sequence(); + int ticks = 0; + for (; ticks < 12'000 && free->next_bud_sequence() == first; ++ticks) + checked(free->advance_tick(checked(wildlife_intents(*free, free->tick() + 1), "intents")), + "uncapped wildlife tick"); + require(free->next_bud_sequence() != first, "uncapped wildlife never budded"); + // A death (hunting) frees a slot a bud may take; the count never passes the cap. + for (int tick = 0; tick < 2 * ticks; ++tick) { + checked(capped->advance_tick( + checked(wildlife_intents(*capped, capped->tick() + 1), "capped intents")), + "capped wildlife tick"); + require(capped->lives().size() <= 32, "wildlife budded at the wildlife cap"); + } + closed(*capped); +} + // ADR-0182 tuning amendments: adopt_tuning swaps the rules at a recorded tick; whoever applies // or replays it must name the rules for its revision and digest, and the safety revision stays. void tuning_is_adopted_and_replayed() { @@ -1313,6 +1405,8 @@ void safe_bud_provision(bool become) { int main() try { admin_commands_apply_and_replay(); + take_and_cull(); + the_wildlife_cap_leaves_room(); tuning_is_adopted_and_replayed(); heat_cycles_back(); full_drip_is_absorbed(); diff --git a/tests/cellular_revamp_tuning_tests.cpp b/tests/cellular_revamp_tuning_tests.cpp index 0f7e1ee..469e22a 100644 --- a/tests/cellular_revamp_tuning_tests.cpp +++ b/tests/cellular_revamp_tuning_tests.cpp @@ -77,6 +77,7 @@ CellularRevampTuning trial(bool safety = true) { // The DEV revamp file cycles energy (ADR-0182 section 14). t.spent_heat_recycle_per_mille = 1'000; t.spent_drip_absorb = 1; + t.reproduction_wildlife_cap = 200; // Leaves 56 of the 256 lives to players. } return t; } @@ -172,6 +173,15 @@ void refusals() { CHECK(error_of(with(base, "spent.heat_recycle_per_mille", "1001")) == CellularTuningErrorKind::out_of_range); CHECK(error_of(with(base, "spent.drip_absorb", "2")) == CellularTuningErrorKind::out_of_range); + // The wildlife cap is optional, at most the organism cap. + auto uncapped = base; + const auto cap_at = uncapped.find("reproduction.wildlife_cap"); + uncapped.erase(cap_at, uncapped.find('\n', cap_at) - cap_at + 1); + CHECK(parse_cellular_revamp_tuning(uncapped) == trial()); + CHECK(parse_cellular_revamp_tuning(with(base, "reproduction.wildlife_cap", "200")) + ->reproduction_wildlife_cap == 200); + CHECK(error_of(with(with(base, "reproduction.organism_cap", "100"), "reproduction.wildlife_cap", + "101")) == CellularTuningErrorKind::inconsistent); CHECK(error_of(with(base, "playtest.starting_wildlife_cells", "256")) == CellularTuningErrorKind::out_of_range); CHECK(error_of(with(base, "playtest.starting_wildlife_cells", "-1")) == diff --git a/tests/grant_broker_tests.cpp b/tests/grant_broker_tests.cpp index 9bd4f92..378e9f4 100644 --- a/tests/grant_broker_tests.cpp +++ b/tests/grant_broker_tests.cpp @@ -560,8 +560,14 @@ void admin_api_tests(const Realm& realm) { {"/api/regions/1/commands", "/api/regions/1/commands?kind=explode", "/api/regions/1/commands?kind=add_pool", "/api/regions/1/commands?kind=add_pool&energy=x", "/api/regions/1/commands?kind=remove_cell&target=7&energy=5", - "/api/regions/1/commands?kind=spawn_wildlife&count=65"}) + "/api/regions/1/commands?kind=spawn_wildlife&count=65", + "/api/regions/1/commands?kind=take_reserve&target=7", + "/api/regions/1/commands?kind=remove_wildlife&target=7", + "/api/regions/1/commands?kind=remove_wildlife&energy=1"}) CHECK(post(bad).status == 400); + // Schema 67: take_reserve and remove_wildlife. + CHECK(post("/api/regions/1/commands?kind=take_reserve&target=424242&energy=5").status == 200); + CHECK(post("/api/regions/1/commands?kind=remove_wildlife").status == 200); const auto queued = must(JsonValue::parse(post("/api/regions/1/commands?kind=add_pool&energy=1000&carbon=7" "&reason=top+up") @@ -584,7 +590,7 @@ void admin_api_tests(const Realm& realm) { auto reader = connect_as(env("EVO_PG_RUNTIME_USER")); const auto pending = reader->query( "SELECT count(*) FROM evolution.load_pending_admin_commands_v1(9831, 1)", {}, 5s); - CHECK(pending && (*pending)[0][0] == "2"); + CHECK(pending && (*pending)[0][0] == "4"); CHECK(!reader->query("SELECT * FROM evolution.admin_enqueue_command_v1(9831, 1, 4, 0, 0, " "1, 0, 0, 0, 0, 'x', '')", {}, 5s)); @@ -612,7 +618,7 @@ void admin_api_tests(const Realm& realm) { CHECK(rows && rows->size() == 1); return std::string(*(*rows)[0][0]); }; - CHECK(pending_now() == "3" && pending_now() == "3"); + CHECK(pending_now() == "5" && pending_now() == "5"); const auto listed_schedules = must(JsonValue::parse(get("/api/regions/1/schedules", admin).body)); const auto& schedule = listed_schedules.member("schedules")->array()->at(0); diff --git a/tests/region_migration_tests.cpp b/tests/region_migration_tests.cpp index 213abbb..c083e43 100644 --- a/tests/region_migration_tests.cpp +++ b/tests/region_migration_tests.cpp @@ -232,6 +232,7 @@ void upgrade_across_migration_and_barrier() { " -v migration_sha_64=$(s 0064_account_admin.sql)" " -v migration_sha_65=$(s 0065_admin_schedules.sql)" " -v migration_sha_66=$(s 0066_tuning_revisions.sql)" + " -v migration_sha_67=$(s 0067_admin_take_and_cull.sql)" " -v runtime_role=evo_runtime_test -f migrations/apply.sql" " > /dev/null 2>&1") != 0); CHECK(history(*owner_db) == "1,2,3,4,5,6,7"); @@ -249,7 +250,7 @@ void upgrade_across_migration_and_barrier() { "tools/migrate-postgres.sh\" > /dev/null") == 0); CHECK(history(*owner_db) == "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24," "25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46," - "47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66"); + "47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67"); CHECK(scalar(*owner_db, "SELECT (c.condeferrable AND c.condeferred AND " "c.confrelid = 'evolution.region_commits'::regclass)::text " "FROM pg_catalog.pg_constraint c WHERE c.conrelid = " diff --git a/tools/ci/postgres-check.sh b/tools/ci/postgres-check.sh index 012d0e9..e210ab9 100644 --- a/tools/ci/postgres-check.sh +++ b/tools/ci/postgres-check.sh @@ -172,7 +172,7 @@ PGDATABASE=upgrade_path psql -X -v ON_ERROR_STOP=1 -1 -v "migration_sha=$v1_sha" -f "$root/migrations/0001_region_bootstrap.sql" > /dev/null test "$(PGDATABASE=upgrade_path psql -XAtc "SELECT string_agg(version::text, ',') FROM evolution.schema_migrations")" = 1 PGDATABASE=upgrade_path bash "$root/tools/migrate-postgres.sh" -test "$(PGDATABASE=upgrade_path psql -XAtc "SELECT string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66 +test "$(PGDATABASE=upgrade_path psql -XAtc "SELECT string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67 # v2 heads have no payload binding: v2->v3 fails closed and leaves history at v2. v2_sha="$(sha256sum "$root/migrations/0002_region_fencing.sql")" v2_sha="${v2_sha%% *}" @@ -193,7 +193,7 @@ PGDATABASE=v3_commits psql -X -v ON_ERROR_STOP=1 \ -c "INSERT INTO evolution.retained_builds VALUES (decode(repeat('b1', 32), 'hex'))" \ -c "SELECT evolution.provision_region_checkpoint(decode('4145564f52434d31' || '01000000' || '01000000' || '0100000000000000' || '0100000000000000' || '0900000000000000' || repeat('11', 16) || repeat('00', 8) || repeat('00', 16) || repeat('00', 32) || repeat('00', 16) || repeat('00', 16) || repeat('00', 8) || '50c3000000000000' || '020000000200000001000000010000000100000001000000010000000100000001000000' || repeat('b1', 32) || '00000000' || '00000000' || '01000000' || '6400000000000000' || repeat('a0', 32), 'hex'))" > /dev/null PGDATABASE=v3_commits bash "$root/tools/migrate-postgres.sh" -test "$(PGDATABASE=v3_commits psql -XAtc "SELECT count(*) || ':' || string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 66:1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66 +test "$(PGDATABASE=v3_commits psql -XAtc "SELECT count(*) || ':' || string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 67:1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67 test "$(PGDATABASE=v3_commits psql -XAtc "SELECT count(*) FROM evolution.region_commits")" = 1 # Review P1: a v4 database holding a published (possibly terminal) checkpoint has # no durable decisions for it. The v5 upgrade must refuse before changing anything. @@ -247,7 +247,7 @@ PGDATABASE=v6_populated psql -X -v ON_ERROR_STOP=1 \ -c "INSERT INTO evolution.retained_builds VALUES (decode(repeat('b1', 32), 'hex'))" \ -c "SELECT evolution.provision_region_checkpoint(decode('4145564f52434d31' || '02000000' || '01000000' || '0100000000000000' || '0100000000000000' || '0900000000000000' || repeat('11', 16) || repeat('00', 8) || repeat('00', 16) || repeat('00', 32) || repeat('00', 16) || repeat('00', 16) || repeat('00', 8) || '50c3000000000000' || '020000000200000001000000010000000100000001000000010000000100000001000000' || repeat('b1', 32) || '00000000' || '00000000' || '01000000' || '6400000000000000' || repeat('a0', 32) || repeat('00', 80), 'hex'))" > /dev/null PGDATABASE=v6_populated bash "$root/tools/migrate-postgres.sh" -test "$(PGDATABASE=v6_populated psql -XAtc "SELECT string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66 +test "$(PGDATABASE=v6_populated psql -XAtc "SELECT string_agg(version::text, ',' ORDER BY version) FROM evolution.schema_migrations")" = 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67 test "$(PGDATABASE=v6_populated psql -XAtc "SELECT count(*) FROM evolution.region_commits c, LATERAL evolution.parse_checkpoint_manifest(c.manifest) m WHERE m.commit_sequence = 0 AND m.predecessor_commit IS NULL")" = 1 test "$(PGDATABASE=v6_populated psql -XAtc "SELECT string_agg(conname, ',') FROM pg_constraint WHERE conrelid = 'evolution.region_heads'::regclass AND contype = 'c' AND pg_get_constraintdef(oid) LIKE '%end_tick%'")" = region_heads_published_tick phase permission-audit @@ -305,9 +305,9 @@ expect_audit_failure 'REVOKE EXECUTE ON FUNCTION evolution.load_world_cellular_m expect_audit_failure 'GRANT EXECUTE ON FUNCTION evolution.fork_restored_history_v1(uuid) TO evo_runtime_test' 'REVOKE EXECUTE ON FUNCTION evolution.fork_restored_history_v1(uuid) FROM evo_runtime_test' phase checksum-drift # Unknown future versions and checksum drift must not be repaired silently. -psql -X -v ON_ERROR_STOP=1 -c 'UPDATE evolution.schema_migrations SET version=67 WHERE version=66' +psql -X -v ON_ERROR_STOP=1 -c 'UPDATE evolution.schema_migrations SET version=68 WHERE version=67' if bash "$root/tools/migrate-postgres.sh"; then exit 1; fi -psql -X -v ON_ERROR_STOP=1 -c "UPDATE evolution.schema_migrations SET version=66 WHERE version=67" +psql -X -v ON_ERROR_STOP=1 -c "UPDATE evolution.schema_migrations SET version=67 WHERE version=68" psql -X -v ON_ERROR_STOP=1 -c "UPDATE evolution.schema_migrations SET sha256=repeat('0',64) WHERE version=14" if bash "$root/tools/migrate-postgres.sh"; then exit 1; fi psql -X -v ON_ERROR_STOP=1 -c "UPDATE evolution.schema_migrations SET sha256=repeat('0',64) WHERE version=13" diff --git a/tools/migrate-postgres.sh b/tools/migrate-postgres.sh index 32aa190..cd0407e 100644 --- a/tools/migrate-postgres.sh +++ b/tools/migrate-postgres.sh @@ -148,6 +148,8 @@ digest_65="$(sha256sum "$root/migrations/0065_admin_schedules.sql")" digest_65="${digest_65%% *}" digest_66="$(sha256sum "$root/migrations/0066_tuning_revisions.sql")" digest_66="${digest_66%% *}" +digest_67="$(sha256sum "$root/migrations/0067_admin_take_and_cull.sql")" +digest_67="${digest_67%% *}" psql -X --no-password --set=ON_ERROR_STOP=1 --set="migration_sha=$digest" \ --set="migration_sha_2=$digest_2" --set="migration_sha_3=$digest_3" \ --set="migration_sha_4=$digest_4" --set="migration_sha_5=$digest_5" \ @@ -199,6 +201,6 @@ psql -X --no-password --set=ON_ERROR_STOP=1 --set="migration_sha=$digest" \ --set="migration_sha_60=$digest_60" --set="migration_sha_61=$digest_61" \ --set="migration_sha_62=$digest_62" --set="migration_sha_63=$digest_63" \ --set="migration_sha_64=$digest_64" --set="migration_sha_65=$digest_65" \ - --set="migration_sha_66=$digest_66" "${admin[@]}" \ + --set="migration_sha_66=$digest_66" --set="migration_sha_67=$digest_67" "${admin[@]}" \ --set="runtime_role=$runtime_role" \ --file="$root/migrations/apply.sql"