Angel Miranda

The four reconciliations

Update, November 2026

The first post covers the new engine behind calichess.cc: a PVS search, about 3039 Elo, 1.0 to 1.5 million positions a second in the tab. Once Explore ran on it, I audited the tree for places where old code was still answering for the new engine. I found four. This is the log: what each looked like, the evidence, what changed, and what is still open.

23dead scripts deleted, about 10,085 lines
5failure causes behind one "search-failed", now three errors
19.3xnodes/s in the benchmark once it timed the real engine
4 → 1request counters, now one tracker

1. Two engines in one binary, and a level 6 that was level 5

The line counts made it plain. The new search and evaluation are 3,192 lines: engine.rs (1,197), explore.rs (309), skill.rs (281), tapered.rs (1,405). The old ones, search/src/lib.rs (3,378) and eval/src/lib.rs (1,102), add 4,480 more, and they still feed three features: the coach review, the reaction map and the forcing-moves lens. Around them, only 8 of the 32 files in scripts/ were called by justfile or package.json.

The strength selector had a smaller version of the same problem. Levels 5 and 6 had the same depth cap and the same node budget, so picking 6 changed nothing:

// apps/web/src/play-wasm-executor.ts, before: two maps
[5, 16], [6, 16]                 // depth cap
[5, 960_000], [6, 960_000]       // node budget
// after: one map, strictly increasing
[5, { depth: 16, nodes: 960_000 }],
[6, { depth: 18, nodes: 1_920_000 }]

I deleted 23 dead scripts, about 10,085 lines, and kept the one a test still runs. I also removed best_move_user_context_json from the bridge: it took the player's color, ignored it, and forwarded the call. Still open: the old search stays until the coach, reaction map and forcing lens move to engine.rs.

2. Five failures, one error string

In the web app, five different paths resolved to the same "search-failed": malformed JSON, an exception in the WebAssembly runtime, a reply that failed schema validation, a missing export, and an ordinary cancel because the user had just made another move. A normal cancel looked exactly like a crash:

// apps/web/src/play-worker-engine.ts
cancel: () => {
  for (const [id, entry] of pending) {
    if (!entry.cancelable) continue;
    entry.resolve({ ok: false, error: "search-failed" });
    entry.resolve({ ok: false, error: "cancelled" });
    pending.delete(id);
  }
}

Now cancels return "cancelled", bad payloads "invalid-response", and real failures keep "search-failed" with their detail. The Rust bridge had the opposite habit, reporting success when it had no data:

// crates/wasm-bridge/src/lib.rs, before: no reference score means "best"
quality: move_quality_dto(
    best_exact_score
        .map(|best| classify_win_percent_loss(best, c.exact_score))
        .unwrap_or(MoveQuality::Best),
),
// after: the reference is the highest score among the candidates
let Some(best) = candidates.iter().map(|c| c.exact_score).max() else {
    return Vec::new();
};

That also fixed a wrong label. The reference used to be the first candidate, and Aggressive mode reorders candidates by pressure on the king. After 1.e4 e5 at 300k nodes, Bc4 (+23) sorted first, ahead of Nc3 and Nf3 (+42) and d4 (+40). Measured against +23 nothing lost anything, so all four were labeled best. Against the real maximum, only the +42 moves are best; Bc4 and d4 are excellent.

Last in this group, new_game() had a fallback that returned an ongoing game with zero legal moves, a state that cannot exist. The start position is a constant, so the fallback is gone and a test checks it has its twenty moves.

3. The benchmark was timing the wrong engine

just bench reported 239,982 nodes/s. The engine in the tab does 1.0 to 1.5 M in WebAssembly, and native code should be faster than that, not six times slower. The trace was short: the m8_bench example behind just bench, plus chess-cli bench and analyze-fen, all called chess_search::search, the old search. The committed baseline:

// benches/baseline.json, generated 2026-11-18
"command": "cargo run --release --quiet -p chess-search --example m8_bench",
"position_set": ["startpos", "kiwipete", "recapture_trap", "stalemate_trap", "back_rank_mate"],
"depth": 3,
"total_nodes": 53996,
"elapsed_ms": 225,
"nodes_per_second": 239982

All three now call Engine::think with a 16 MB transposition table:

CommandOld searchReal engine
just bench, 5 positionsdepth 3, 53,996 nodes, 225 ms, 239,982 nodes/sdepth 9, 194,109 nodes, 42 ms, 4,621,642 nodes/s
chess-cli bench --depth 61,022,976 nodes, 1,886 ms (3 positions)24,401 nodes, 8 ms (5 positions)
analyze-fen, Kiwipete, depth 6e2a6, 1,005,387 nodes, 1,817 mse2a6, 7,065 nodes, about 3 ms

The 19.3x matters less than what it now measures: a regression in the engine people use will move this number. The old figures stay in the new baseline as legacy_m8_baseline, so the comparison can be checked.

4. Resign forgot one of four counters

play-ui.ts was 6,014 lines. PlayUiState had 27 fields, the file reassigned state = { ...state, ... } 67 times, and a local let playMode shadowed state.playMode. Four version counters protected against late replies from the workers, and every transition had to bump the right ones by hand. resignGame bumped three:

// apps/web/src/play-ui.ts, resignGame, before
gameVersion += 1;
lensRequestVersion += 1;
// missing: forcingRequestVersion += 1;
sideExploreRequestVersion += 1;
cancelActiveSearches();
state = { ...state, lens: emptyLens(), reaction: emptyReaction(),
          // missing: forcing: emptyForcing(),
          sideExplore: emptySideExplore(), ... };

A forcing-moves reply still in flight could land on a game that was already over. The fix puts the counters in one tracker where invalidation is nested, so a new game cannot skip one:

// apps/web/src/play-state-machine.ts
const invalidateAnalysis = () => { counters.forcing += 1; counters.sideExplore += 1; };
const invalidatePosition = () => { counters.lens += 1; invalidateAnalysis(); };
const invalidateAll      = () => { counters.game += 1; invalidatePosition(); };

The shadow playMode is gone, and the transitions are pure functions tested in play-state-machine.test.ts. Still open: play-ui.ts is smaller but still one large file.

How it was checked

Before the commit: cargo fmt and clippy with warnings as errors, TypeScript typecheck and lint, 399 Rust tests, 15 web suites, the policy, network and oracle checks, and just bench. All passed. The knight at the top is the piece the CaliChess board uses, painted by a small Canvas 2D brush: layered washes and ink that runs dry.

More: the original notebook, in Spanish, with ELI5 and technical modes · the repo · A chess engine that plays in a browser tab · calichess.cc

El primer post cuenta el motor nuevo detrás de calichess.cc: una búsqueda PVS de unos 3039 Elo que corre en la pestaña a entre 1.0 y 1.5 millones de posiciones por segundo. Cuando Explorar ya corría sobre él, revisé el árbol buscando lugares donde el código viejo seguía respondiendo por el motor nuevo. Encontré cuatro. Esta es la bitácora: cómo se veía cada uno, la evidencia, qué cambió y qué sigue abierto.

23scripts muertos borrados, unas 10,085 líneas
5causas de fallo bajo un solo "search-failed", ahora tres errores
19.3xnodos/s en el benchmark al medir el motor real
4 → 1contadores de peticiones, ahora un rastreador

1. Dos motores en un binario, y un nivel 6 que era el 5

El conteo de líneas lo dejó claro. La búsqueda y la evaluación nuevas suman 3,192 líneas: engine.rs (1,197), explore.rs (309), skill.rs (281), tapered.rs (1,405). Las viejas, search/src/lib.rs (3,378) y eval/src/lib.rs (1,102), suman otras 4,480 y todavía alimentan tres funciones: la revisión del coach, el mapa de reacción y la lente de jugadas forzadas. Alrededor, solo 8 de los 32 archivos en scripts/ los llamaban justfile o package.json.

El selector de fuerza tenía una versión chica del mismo problema. Los niveles 5 y 6 tenían el mismo tope de profundidad y el mismo presupuesto de nodos, así que elegir el 6 no cambiaba nada:

// apps/web/src/play-wasm-executor.ts, antes: dos mapas
[5, 16], [6, 16]                 // tope de profundidad
[5, 960_000], [6, 960_000]       // presupuesto de nodos
// después: un mapa, estrictamente creciente
[5, { depth: 16, nodes: 960_000 }],
[6, { depth: 18, nodes: 1_920_000 }]

Borré 23 scripts muertos, unas 10,085 líneas, y dejé el único que todavía corre una prueba. También quité best_move_user_context_json del puente: recibía el color del jugador, lo ignoraba y pasaba la llamada tal cual. Sigue abierto: la búsqueda vieja se queda hasta que el coach, el mapa de reacción y la lente de forzadas pasen a engine.rs.

2. Cinco fallas, un solo texto de error

En la app web, cinco caminos distintos terminaban en el mismo "search-failed": JSON mal formado, una excepción en el runtime de WebAssembly, una respuesta que no pasaba la validación del esquema, un export faltante y una cancelación normal porque el usuario acababa de hacer otra jugada. Una cancelación normal se veía igual que un crash:

// apps/web/src/play-worker-engine.ts
cancel: () => {
  for (const [id, entry] of pending) {
    if (!entry.cancelable) continue;
    entry.resolve({ ok: false, error: "search-failed" });
    entry.resolve({ ok: false, error: "cancelled" });
    pending.delete(id);
  }
}

Ahora las cancelaciones regresan "cancelled", las respuestas malas "invalid-response" y los fallos reales conservan "search-failed" con su detalle. El puente en Rust tenía el hábito contrario: reportaba éxito cuando no tenía datos:

// crates/wasm-bridge/src/lib.rs, antes: sin puntaje de referencia, "best"
quality: move_quality_dto(
    best_exact_score
        .map(|best| classify_win_percent_loss(best, c.exact_score))
        .unwrap_or(MoveQuality::Best),
),
// después: la referencia es el puntaje más alto entre las candidatas
let Some(best) = candidates.iter().map(|c| c.exact_score).max() else {
    return Vec::new();
};

Eso también arregló una etiqueta equivocada. La referencia era la primera candidata, y el modo Agresivo reordena las candidatas por presión sobre el rey. Tras 1.e4 e5 a 300k nodos, Ac4 (+23) quedaba primera, delante de Cc3 y Cf3 (+42) y d4 (+40). Medidas contra +23, ninguna perdía nada, así que las cuatro salían como la mejor. Contra el máximo real, solo las de +42 son la mejor; Ac4 y d4 son excelentes.

Por último en este grupo, new_game() tenía un respaldo que devolvía una partida en curso con cero jugadas legales, un estado que no puede existir. La posición inicial es una constante, así que el respaldo se fue y una prueba comprueba que tiene sus veinte jugadas.

3. El benchmark medía el motor equivocado

just bench reportaba 239,982 nodos/s. El motor en la pestaña hace entre 1.0 y 1.5 M en WebAssembly, y el código nativo debería ir más rápido, no seis veces más lento. El rastro fue corto: el ejemplo m8_bench detrás de just bench, más chess-cli bench y analyze-fen, llamaban a chess_search::search, la búsqueda vieja. La línea base guardada:

// benches/baseline.json, generado el 2026-11-18
"command": "cargo run --release --quiet -p chess-search --example m8_bench",
"position_set": ["startpos", "kiwipete", "recapture_trap", "stalemate_trap", "back_rank_mate"],
"depth": 3,
"total_nodes": 53996,
"elapsed_ms": 225,
"nodes_per_second": 239982

Los tres ahora llaman a Engine::think con una tabla de transposición de 16 MB:

ComandoBúsqueda viejaMotor real
just bench, 5 posicionesprof. 3, 53,996 nodos, 225 ms, 239,982 nodos/sprof. 9, 194,109 nodos, 42 ms, 4,621,642 nodos/s
chess-cli bench --depth 61,022,976 nodos, 1,886 ms (3 posiciones)24,401 nodos, 8 ms (5 posiciones)
analyze-fen, Kiwipete, prof. 6e2a6, 1,005,387 nodos, 1,817 mse2a6, 7,065 nodos, unos 3 ms

El 19.3x importa menos que lo que ahora mide: una regresión en el motor que la gente usa sí moverá este número. Las cifras viejas se quedan en la línea base nueva como legacy_m8_baseline, para que la comparación se pueda revisar.

4. Rendirse olvidaba uno de cuatro contadores

play-ui.ts tenía 6,014 líneas. PlayUiState tenía 27 campos, el archivo reasignaba state = { ...state, ... } 67 veces y una variable local let playMode duplicaba a state.playMode. Cuatro contadores de versión protegían contra respuestas tardías de los workers, y cada transición tenía que subir los correctos a mano. resignGame subía tres:

// apps/web/src/play-ui.ts, resignGame, antes
gameVersion += 1;
lensRequestVersion += 1;
// falta: forcingRequestVersion += 1;
sideExploreRequestVersion += 1;
cancelActiveSearches();
state = { ...state, lens: emptyLens(), reaction: emptyReaction(),
          // falta: forcing: emptyForcing(),
          sideExplore: emptySideExplore(), ... };

Una respuesta de jugadas forzadas que siguiera en camino podía caer sobre una partida ya terminada. El arreglo pone los contadores en un solo rastreador donde la invalidación va anidada, así una partida nueva no puede saltarse ninguno:

// apps/web/src/play-state-machine.ts
const invalidateAnalysis = () => { counters.forcing += 1; counters.sideExplore += 1; };
const invalidatePosition = () => { counters.lens += 1; invalidateAnalysis(); };
const invalidateAll      = () => { counters.game += 1; invalidatePosition(); };

La variable sombra playMode ya no existe, y las transiciones son funciones puras con pruebas en play-state-machine.test.ts. Sigue abierto: play-ui.ts es más chico, pero sigue siendo un archivo grande.

Cómo se comprobó

Antes del commit: cargo fmt y clippy con las advertencias como errores, typecheck y lint de TypeScript, 399 pruebas de Rust, 15 suites web, los checks de política, red y oráculo, y just bench. Todo pasó. El caballo de arriba es la pieza que usa el tablero de CaliChess, pintada por un pincel chico en Canvas 2D: aguadas por capas y tinta que se va secando.

Más: el cuaderno original, con modos ELI5 y técnico · el repo · Un motor de ajedrez que juega en una pestaña · calichess.cc