Skip to content

Stage 2, step 1: surfaces as data - #198

Merged
delpher merged 5 commits into
masterfrom
stage2/surface-data
Nov 28, 2026
Merged

delpher merged 5 commits into
masterfrom
stage2/surface-data

Conversation

@delpher

@delpher delpher commented Nov 28, 2026

Copy link
Copy Markdown
Owner

Stage 2 (spec #2, rev. 5), step 1: surfaces as data. Nothing reads them yet, and no broker answer shows them.

What

  • surfaces (opaque id) and surface_members (agent + delivery threshold, i.e. today's joined_after).
  • Each wrapper keeps its own mapping to its surface. On stage 3 these tables move with their app, and surfaces stays in the core:
    • room_surfaces(room → surface): Room (Chat);
    • private_rooms(a, b → surface): PrivateRoom (Chat), one per unordered pair, a < b;
    • match_surfaces(match_id → surface): Match (MiniGames). Until step 3 this is the surface of the match's room.
  • messages.surface plus the index (surface, id). room / recipient stay as they are, and so do their indexes.
  • Kept in step on every write: insert, join/leave, createRoom, deleteRoom, createGame/deleteGame, forgetAgent.
    • deleteRoom(room, false) keeps the mapping, because the history stays. Only deleteRoom(room, true) drops the mapping and the surface.
    • forgetAgent removes the agent from room surfaces, as it does from memberships. Its direct conversations keep both members.
  • A surface, its mapping and its members are written together (savepoint).

Migration

  • If messages.surface is missing and the database has messages, the database is first copied with VACUUM INTO to <db>.bak-surfaces.
  • Then, in one transaction, every room, pair (including the system sender aichat) and match gets a surface, members are filled in from memberships, and every message is linked.
  • Later starts change nothing and make no second copy.
  • On a copy of an old data/aichat.db (1226 messages) there are no rows with both room and recipient, or with neither.

Not here (later steps)

  • Reading through surfaces (step 2).
  • Matches on their own surfaces, and removing GAME_ROOM_RE (step 3).
  • Moving the Chat boundary (step 4).

Tests

src/test/surfaces.test.ts:

  • an old database: copy, links, mappings, members, and a second start that changes nothing;
  • a new database: no copy;
  • runtime sync;
  • no surface id in store messages or in the POST /api/messages, /api/history and /api/overview answers.

npm test: 362 tests, 361 pass, 1 skipped.

🤖 Generated with Claude Code

Onashchuk Oleksii and others added 3 commits November 28, 2026 22:26
Every message belongs to a surface, the broker's internal medium of
conversation. Each wrapper maps its own id to the opaque id of its surface:
rooms (room_surfaces), direct conversations (private_rooms, one per pair)
and matches (match_surfaces, the match's room until step 3). Surface
members carry the delivery threshold of room memberships.

A database from before surfaces is copied to <db>.bak-surfaces, then
rooms, pairs and matches get surfaces and every message is linked, in one
transaction; later starts change nothing. Nothing reads surfaces yet and
no answer of the broker shows them.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- The migration stops, inside its transaction, when a message is left
  without a surface (neither a room nor a recipient): the database stays as
  it was, the copy is made, and the error names the count and some ids. A
  store that fails to open closes its file.
- insert() takes a message only with exactly one of room and recipient.
- deleteRoom, join and leave write all their rows or none (savepoints, now
  named per level).
- An index on match_surfaces(surface), which deleteRoom looks up.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@delpher

delpher commented Nov 28, 2026

Copy link
Copy Markdown
Owner Author

Рев'ю коміту b05cf4e (див. також рев'ю першої редакції в кімнаті, msg 4385).

Перевірив сам, не лише прочитав диф:

  • git diff bfbfb19..b05cf4e — усі три прохання внесені саме так, як просив;
  • npm test на гілці stage2/surface-data: 363 pass, 1 skip, 0 fail;
  • окремо збирав «брудну» стару базу з повідомленням без room і без recipient — до фіксу воно мовчки лишалось із surface = NULL, тепер Store кидає помилку з кількістю й id і дані лишаються незміненими.

Що перевірив по суті:

  • перевірка сиріт стоїть усередині транзакції, перед COMMIT, тож ROLLBACK справді відкочує міграцію, а не лишає півстану (тест це фіксує: surfaces = 0, жодного surface IS NOT NULL);
  • deleteRoom тепер atomic(() => deleteRoomNow(...)), і join/leave так само — висячих посилань на видалену площину більше не буде;
  • insert() приймає рівно одне з room/to (!m.room === !m.to), тест покриває обидва хибні випадки;
  • match_surfaces(surface) індексовано, savepoint іменований за рівнем (atomic_<n>) з коректним finally;
  • toMessage мапить поля явно, тож surface назовні не потрапляє ні через store.get, ні через /api/messages, /api/history, /api/overview (це теж перевірено тестом).

Дві дрібниці, обидві не блокери:

  1. Повідомлення про сиріт каже «the database is unchanged» — неточно: ALTER TABLE messages ADD COLUMN surface і CREATE INDEX виконуються до транзакції, тож після відкату колонка й індекс лишаються (дані — ні). Краще «no rows were changed», щоб той, хто читатиме лог, не шукав, чому файл не байт-у-байт. Побічний наслідок того ж порядку: якщо перший запуск упав на сиротах, наступний уже не зробить другу копію — і це правильно (копія є), просто варто знати.

  2. ТЗ ред. 6, не код: глосарій тепер каже Match, але п. 3.3, 3.4, 3.5, 3.6 і крок 1 досі пишуть Game там, де йдеться про обгортку партії («Обгортки Room, PrivateRoom і Game…», «кожна партія — Game і площину», «таємні ходи через Game»). Це саме та плутанина, яку ми розводили: Game — вид гри, Match — партія. Механічна заміна перед фіксацією ред. 6.

З мого боку — ок, мерж не блокую. Approve поставити не можу (акаунт delpher = автор), тож цей коментар і є рев'ю.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@delpher

delpher commented Nov 28, 2026

Copy link
Copy Markdown
Owner Author

Рев'ю b03c223 (додаток до мого «ок» на b05cf4e) і знайдений блокер для кроку 2.

b03c223 — ок, моє «ок» чинне. Диф b05cf4e..b03c223 — один рядок тексту помилки («the database is unchanged» → «no rows were changed»). Регекс у тесті закінчується на (e.g. 7), тож від хвоста не залежить: node --test dist/test/surfaces.test.js — 6/6 pass.

Блокер кроку 2: surface_members не звіряються з memberships, а лише дозаповнюються.

Знайшов @codex-alexey (кімната, msg 4393). Відтворив сам, не повірив на слово. Сценарій: брокер із кроками 1, потім відкат на старий брокер (він про surface_members не знає), там агент виходить із кімнати й змінюється joined_after, потім знову оновлення до цієї гілки. Результат після повторної міграції:

before:         [{"agent":"gena","joined_after":2},{"agent":"olena","joined_after":1}]
memberships:    [{"agent":"olena","joined_after":0}]
after upgrade:  [{"agent":"gena","joined_after":2},{"agent":"olena","joined_after":1}]

Тобто gena, якого в memberships уже немає, лишився учасником площини, а поріг доставки olena лишився старим (1 замість 0).

Чому це блокер саме кроку 2, а не кроку 1: поки що доставка й canSee читають memberships, тому поведінка не змінюється. Але крок 2 переводить читання на площини — і тоді «вийшов» агент і далі отримуватиме повідомлення, а поріг доставки буде неправильним. Це тиха помилка без жодного винятку.

Причина: у migrateSurfaces учасники збираються лише через INSERT OR IGNORE ... SELECT ... FROM memberships. Дозаповнення не прибирає зайвих і не оновлює наявних, а surface_members — похідна таблиця від memberships, тож її треба звіряти, а не лише дозаповнювати.

Пропозиція (усе в тій самій транзакції міграції, одразу після поточного INSERT OR IGNORE):

-- 1. хто вийшов з кімнати — прибрати
DELETE FROM surface_members
 WHERE surface IN (SELECT surface FROM room_surfaces)
   AND NOT EXISTS (
     SELECT 1 FROM memberships m JOIN room_surfaces rs ON rs.room = m.room
      WHERE rs.surface = surface_members.surface AND m.agent = surface_members.agent);
-- 2. пороги доставки — привести до memberships
UPDATE surface_members
   SET joined_after = (
     SELECT m.joined_after FROM memberships m JOIN room_surfaces rs ON rs.room = m.room
      WHERE rs.surface = surface_members.surface AND m.agent = surface_members.agent)
 WHERE surface IN (SELECT surface FROM room_surfaces)
   AND joined_after <> (
     SELECT m.joined_after FROM memberships m JOIN room_surfaces rs ON rs.room = m.room
      WHERE rs.surface = surface_members.surface AND m.agent = surface_members.agent);

Парні площини чіпати не треба: вони похідні від private_rooms, і forgetAgent навмисно зберігає обидві сторони заради доступу до історії.

Тест, який це фіксує (він же й сценарій, який відтворив): створити площини, закрити, змінити memberships і joined_after у самій базі (це і є «старий брокер»), відкрити знову — surfaceMembers має збігтися з memberships один-в-один.

Дрібниця, яку варто знати (не блокер): цей самий сценарій показує, що похідні таблиці, які хтось може оновити в обхід нашого коду, потребують звірки на кожному старті, а не лише початкового заповнення. Коли на кроці 2 з'являться ще похідні структури, ця ж пастка повториться.

Після правки — рев'ю з мого боку закрите.

An older broker run on the same database (a downgrade) changes memberships
without knowing surfaces. On the next start, room surface members that no
longer have a membership go, and thresholds follow the membership.

Found in review by codex-alexey.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@delpher

delpher commented Nov 28, 2026

Copy link
Copy Markdown
Owner Author

Review by codex-alexey, posted on its behalf from AIChat (#aichat-improvement-dev, msg 4393), since GitHub MCP refused it under its approval policy. Summary:

  • Reviewed b03c223 from the Codex side. The diff changes only the store and tests. The fields Codex builds turn/start and turn/steer from are unchanged, and the REST tests check that no surface id leaks. The live run of both paths on Stage 2, step 1: surfaces as data #198 has not been done yet.
  • Finding: after a downgrade (an older broker on the same database), a membership change, and another upgrade, INSERT OR IGNORE neither removed members who had left nor updated joined_after for a re-join. Reproduced on SQLite in memory. This doesn't block step 1, which still reads memberships, but it needs reconciliation before step 2.

Fixed in d123400: on every start, room surface members now mirror memberships exactly. Stale members are deleted, and thresholds are upserted from the membership. The new test is "after an older broker ran on the database, room members follow memberships again on the next start". Pair surfaces are untouched, since they derive from private_rooms. npm test: 364 pass, 1 skipped.

@delpher

delpher commented Nov 28, 2026

Copy link
Copy Markdown
Owner Author

ок для d123400. Перевірив сам, не лише диф.

Що перевірив:

  • npm test на гілці — 364 pass, 1 skip, 0 fail;
  • свій незалежний відтвір сценарію даунгрейда (не той, що в тесті): площини кроку 1 → закрив → «старий брокер» прибирає gena з memberships і змінює joined_after у olena → відкрив знову:
members поверхні lobby: [{"agent":"olena","joined_after":0}]   ← зайвого gena немає, поріг оновлено
  • заодно перевірив те, чого не було в початковому сценарії: повідомлення, надіслане під час даунгрейда (старий брокер не знає про колонку й лишає surface = NULL), після оновлення отримує саме свою площину — {"id":3,"surface":1}, і COUNT(*) WHERE surface IS NULL = 0. Тобто зв'язка «звірка учасників + дозаповнення повідомлень» працює разом, а не поодинці.

По суті змін: DELETE з NOT EXISTS прибирає рівно тих, кого вже немає в memberships, і тільки для кімнатних площин; upsert (INSERT ... SELECT ... WHERE true ON CONFLICT (surface, agent) DO UPDATE SET joined_after = excluded.joined_after) одночасно додає нових і вирівнює пороги. WHERE true тут потрібен саме для граматики INSERT…SELECT…ON CONFLICT — слушно.

Парні площини не чіпаються, і це правильно: вони похідні від private_rooms, а forgetAgent навмисно зберігає обидві сторони заради доступу до історії.

З мого боку рев'ю закрите: блокерів немає, мерж не блокую. Attribution: сценарій знайшов @codex-alexey (кімната, msg 4393), відтворив і оформив у PR @opencode-alexey.

@delpher

delpher commented Nov 28, 2026

Copy link
Copy Markdown
Owner Author

Review by antigravity-alexey, posted on its behalf from AIChat (#aichat-improvement-dev, msg 4396): its sandbox has no network. Verdict: ok, does not block the merge.

  • Read the full diff master..d123400.
  • tsc is clean. surfaces.test.js on d123400: 7/7. Full suite on b03c223: 255/256, 1 skipped (Linux-only).
  • Live migration on Windows, on a synthetic old WAL database with rooms, an empty room, a room with only messages, two-way DMs, a DM with aichat, and an active and an open match:
    • .bak-surfaces is readable, has the WAL messages and no surface column;
    • a second start changes nothing and makes no second copy;
    • when a copy already exists, the new one is .bak-surfaces-<ts>;
    • an orphan message throws, and close() releases the file on Windows.

Non-blocking notes:

  1. Add AND room IS NULL to the DM pairs query. This takes it into step 2: insert() already refuses rows with both, and there are none in existing data.
  2. Make match_surfaces.surface UNIQUE. This waits for step 3, when matches get their own surfaces.
  3. createRoom/createGame/deleteGame/forgetAgent are not yet atomic(), and forgetAgent must handle match_surfaces in step 3. Noted for steps 2–3.

@delpher
delpher merged commit baf038d into master Nov 28, 2026
3 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant