rshogi-core 0.2.0

A high-performance shogi engine core library with NNUE evaluation
Documentation
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
//! 評価・補正ヘルパー関数群
//!
//! 補正履歴、静的評価コンテキスト、置換表プローブ等。

#[cfg(not(feature = "search-no-pass-rules"))]
use crate::eval::evaluate_pass_rights;
use crate::position::Position;
use crate::types::{Bound, Color, DEPTH_UNSEARCHED, Depth, MAX_PLY, Move, Value};

use super::alpha_beta::{
    EvalContext, ProbeOutcome, SearchContext, SearchState, TTContext, to_corrected_static_eval,
};
use super::history::CORRECTION_HISTORY_SIZE;
use super::search_helpers::{ensure_nnue_accumulator, nnue_evaluate};
use super::stats::inc_stat_by_depth;
#[cfg(feature = "tt-trace")]
use super::tt_sanity::{
    InvalidTtLog, TtCutoffTrace, TtProbeTrace, TtWriteTrace, helper_tt_write_enabled_for_depth,
    maybe_log_invalid_tt_data, maybe_trace_tt_cutoff, maybe_trace_tt_probe, maybe_trace_tt_write,
};
use super::tt_sanity::{is_valid_tt_eval, is_valid_tt_stored_value};
use super::types::{ContHistKey, NodeType, value_from_tt};

// =============================================================================
// 補正履歴
// =============================================================================

/// 補正履歴から静的評価の補正値を算出
#[inline]
pub(super) fn correction_value(
    st: &SearchState,
    ctx: &SearchContext<'_>,
    pos: &Position,
    ply: i32,
) -> i32 {
    let us = pos.side_to_move();
    let pawn_idx = (pos.pawn_key() as usize) & (CORRECTION_HISTORY_SIZE - 1);
    let minor_idx = (pos.minor_piece_key() as usize) & (CORRECTION_HISTORY_SIZE - 1);
    let non_pawn_idx_w = (pos.non_pawn_key(Color::White) as usize) & (CORRECTION_HISTORY_SIZE - 1);
    let non_pawn_idx_b = (pos.non_pawn_key(Color::Black) as usize) & (CORRECTION_HISTORY_SIZE - 1);

    // YO準拠: (ss-1)->currentMove を使って continuation correction を参照
    let prev_move = if ply >= 1 {
        st.stack[(ply - 1) as usize].current_move
    } else {
        Move::NONE
    };
    let move_ok = prev_move.is_normal();

    // continuation correction 用キー: (ss-2) と (ss-4) の2段階(YO準拠)
    // YO準拠: plyが小さい場合はsentinel(NO_PIECE, SQ_ZERO)テーブルを参照
    let sentinel_key = ContHistKey::null_sentinel();
    let cont_key_2 = if move_ok {
        if ply >= 2 {
            st.stack[(ply - 2) as usize].cont_hist_key
        } else {
            Some(sentinel_key)
        }
    } else {
        None
    };
    let cont_key_4 = if move_ok {
        if ply >= 4 {
            st.stack[(ply - 4) as usize].cont_hist_key
        } else {
            Some(sentinel_key)
        }
    } else {
        None
    };

    // SAFETY: 単一スレッド内で使用、可変参照と同時保持しない
    let h = unsafe { ctx.history.as_ref_unchecked() };
    let pcv = h.correction_history.pawn_value(pawn_idx, us) as i32;
    let micv = h.correction_history.minor_value(minor_idx, us) as i32;
    let wnpcv = h.correction_history.non_pawn_value(non_pawn_idx_w, Color::White, us) as i32;
    let bnpcv = h.correction_history.non_pawn_value(non_pawn_idx_b, Color::Black, us) as i32;

    // YO準拠: move無効の場合はcntcv全体が8(個別デフォルトの合計ではない)
    let cntcv = if move_ok {
        let cv2 = cont_key_2
            .map(|key| {
                let pc = pos.piece_on(prev_move.to());
                h.correction_history.continuation_value(key.piece, key.to, pc, prev_move.to())
                    as i32
            })
            .unwrap_or(8);
        let cv4 = cont_key_4
            .map(|key| {
                let pc = pos.piece_on(prev_move.to());
                h.correction_history.continuation_value(key.piece, key.to, pc, prev_move.to())
                    as i32
            })
            .unwrap_or(8);
        cv2 + cv4
    } else {
        8
    };

    9536 * pcv + 8494 * micv + 10_132 * (wnpcv + bnpcv) + 7156 * cntcv
}

/// 補正履歴の更新
#[inline]
pub(super) fn update_correction_history(
    st: &SearchState,
    ctx: &SearchContext<'_>,
    pos: &Position,
    ply: i32,
    bonus: i32,
) {
    let us = pos.side_to_move();
    let pawn_idx = (pos.pawn_key() as usize) & (CORRECTION_HISTORY_SIZE - 1);
    let minor_idx = (pos.minor_piece_key() as usize) & (CORRECTION_HISTORY_SIZE - 1);
    let non_pawn_idx_w = (pos.non_pawn_key(Color::White) as usize) & (CORRECTION_HISTORY_SIZE - 1);
    let non_pawn_idx_b = (pos.non_pawn_key(Color::Black) as usize) & (CORRECTION_HISTORY_SIZE - 1);

    // YO準拠: (ss-1)->currentMove を使って continuation correction を更新
    let prev_move = if ply >= 1 {
        st.stack[(ply - 1) as usize].current_move
    } else {
        Move::NONE
    };
    let move_ok = prev_move.is_normal();

    // (ss-2) context — YO準拠: plyが小さい場合はsentinel(NO_PIECE, SQ_ZERO)テーブルを更新
    let sentinel_key = ContHistKey::null_sentinel();
    let cont_params_2 = if move_ok {
        let key = if ply >= 2 {
            st.stack[(ply - 2) as usize].cont_hist_key
        } else {
            Some(sentinel_key)
        };
        key.map(|k| {
            let pc = pos.piece_on(prev_move.to());
            (k.piece, k.to, pc, prev_move.to())
        })
    } else {
        None
    };
    // (ss-4) context
    let cont_params_4 = if move_ok {
        let key = if ply >= 4 {
            st.stack[(ply - 4) as usize].cont_hist_key
        } else {
            Some(sentinel_key)
        };
        key.map(|k| {
            let pc = pos.piece_on(prev_move.to());
            (k.piece, k.to, pc, prev_move.to())
        })
    } else {
        None
    };

    const NON_PAWN_WEIGHT: i32 = 165;

    // SAFETY: 単一スレッド内で使用、他の参照と同時保持しない
    let h = unsafe { ctx.history.as_mut_unchecked() };
    h.correction_history.update_pawn(pawn_idx, us, bonus);
    h.correction_history.update_minor(minor_idx, us, bonus * 156 / 128);
    h.correction_history.update_non_pawn(
        non_pawn_idx_w,
        Color::White,
        us,
        bonus * NON_PAWN_WEIGHT / 128,
    );
    h.correction_history.update_non_pawn(
        non_pawn_idx_b,
        Color::Black,
        us,
        bonus * NON_PAWN_WEIGHT / 128,
    );

    // YO準拠: continuation(ss-2) 重み 137/128
    if let Some((piece, to, pc, prev_to)) = cont_params_2 {
        h.correction_history
            .update_continuation(piece, to, pc, prev_to, bonus * 137 / 128);
    }
    // YO準拠: continuation(ss-4) 重み 64/128
    if let Some((piece, to, pc, prev_to)) = cont_params_4 {
        h.correction_history
            .update_continuation(piece, to, pc, prev_to, bonus * 64 / 128);
    }
}

// =============================================================================
// 置換表プローブ
// =============================================================================

/// 置換表プローブ
#[allow(clippy::too_many_arguments)]
pub(super) fn probe_transposition<const NT: u8>(
    st: &mut SearchState,
    ctx: &SearchContext<'_>,
    pos: &mut Position,
    depth: Depth,
    beta: Value,
    ply: i32,
    pv_node: bool,
    in_check: bool,
    excluded_move: Move,
    cut_node: bool,
) -> ProbeOutcome {
    let key = pos.key();
    let tt_result = ctx.tt.probe(key, pos);
    let tt_hit = tt_result.found;
    let mut tt_data = tt_result.data;

    st.stack[ply as usize].tt_hit = tt_hit;
    // excludedMoveがある場合は前回のttPvを維持(YaneuraOu準拠)
    st.stack[ply as usize].tt_pv = if excluded_move.is_some() {
        st.stack[ply as usize].tt_pv
    } else {
        pv_node || (tt_hit && tt_data.is_pv)
    };

    // YaneuraOu準拠: alpha-beta では ttHit で ttMove を潰さない。
    // probe() 側で to_move 変換に失敗した手は除外済み。
    let tt_move = tt_data.mv;
    let mut tt_value = if tt_hit {
        value_from_tt(tt_data.value, ply)
    } else {
        Value::NONE
    };
    if tt_hit && !is_valid_tt_stored_value(tt_data.value) {
        #[cfg(feature = "tt-trace")]
        maybe_log_invalid_tt_data(InvalidTtLog {
            reason: "invalid_value",
            stage: "ab_probe",
            thread_id: ctx.thread_id,
            ply,
            key,
            depth: tt_data.depth,
            bound: tt_data.bound,
            tt_move,
            stored_value: tt_data.value,
            converted_value: tt_value,
            eval: tt_data.eval,
        });
        tt_value = Value::NONE;
    }
    if tt_hit && !is_valid_tt_eval(tt_data.eval) {
        #[cfg(feature = "tt-trace")]
        maybe_log_invalid_tt_data(InvalidTtLog {
            reason: "invalid_eval",
            stage: "ab_probe",
            thread_id: ctx.thread_id,
            ply,
            key,
            depth: tt_data.depth,
            bound: tt_data.bound,
            tt_move,
            stored_value: tt_data.value,
            converted_value: tt_value,
            eval: tt_data.eval,
        });
        tt_data.eval = Value::NONE;
    }
    #[cfg(feature = "tt-trace")]
    maybe_trace_tt_probe(TtProbeTrace {
        stage: "ab_probe",
        thread_id: ctx.thread_id,
        ply,
        key,
        hit: tt_hit,
        depth: tt_data.depth,
        bound: tt_data.bound,
        tt_move,
        stored_value: tt_data.value,
        converted_value: tt_value,
        eval: tt_data.eval,
        root_move: if ply >= 1 {
            st.stack[0].current_move
        } else {
            Move::NONE
        },
    });
    let tt_capture = tt_move.is_some() && pos.capture_stage(tt_move);

    // TT統計収集
    inc_stat_by_depth!(st, tt_probe_by_depth, depth);
    if tt_hit {
        inc_stat_by_depth!(st, tt_hit_by_depth, depth);
    }

    // YaneuraOu準拠のTTカットオフ条件(yaneuraou-search.cpp:2331-2337)
    // - fail-high時は tt_data.depth > depth を要求(fail-low時は >= depth)
    // - depth<=5ではcutNodeとTT値の方向が一致する場合のみカットオフ許可
    let tt_value_lte_beta = tt_value != Value::NONE && tt_value.raw() <= beta.raw();
    if !pv_node
        && excluded_move.is_none()
        && tt_hit
        && tt_data.depth > depth - tt_value_lte_beta as i32
        && tt_value != Value::NONE
        && tt_data.bound.can_cutoff(tt_value, beta)
        && (cut_node == (tt_value.raw() >= beta.raw()) || depth > 5)
    {
        #[cfg(feature = "tt-trace")]
        maybe_trace_tt_cutoff(TtCutoffTrace {
            stage: "ab_probe_cutoff",
            thread_id: ctx.thread_id,
            ply,
            key,
            search_depth: depth,
            depth: tt_data.depth,
            bound: tt_data.bound,
            value: tt_value,
            beta,
            root_move: if ply >= 1 {
                st.stack[0].current_move
            } else {
                Move::NONE
            },
        });
        return ProbeOutcome::Cutoff {
            value: tt_value,
            tt_move,
            tt_capture,
        };
    }

    // TTカットオフ失敗理由の統計
    #[cfg(feature = "search-stats")]
    if !pv_node && excluded_move.is_none() && tt_hit && tt_value != Value::NONE {
        if tt_data.depth <= depth - tt_value_lte_beta as i32 {
            inc_stat_by_depth!(st, tt_fail_depth_by_depth, depth);
        } else if !tt_data.bound.can_cutoff(tt_value, beta) {
            inc_stat_by_depth!(st, tt_fail_bound_by_depth, depth);
        }
    }

    // 1手詰め判定(置換表未ヒット時のみ、Rootでは実施しない)
    // excludedMoveがある場合も実施しない(詰みがあればsingular前にbeta cutするため)
    if NT != NodeType::Root as u8 && !in_check && !tt_hit && excluded_move.is_none() {
        let mate_move = pos.mate_1ply();
        if mate_move.is_some() {
            let value = Value::mate_in(ply + 1);
            let stored_depth = (depth + 6).min(MAX_PLY - 1);
            #[cfg(feature = "tt-trace")]
            let allow_write = ctx.allow_tt_write
                && helper_tt_write_enabled_for_depth(ctx.thread_id, Bound::Exact, stored_depth);
            #[cfg(not(feature = "tt-trace"))]
            let allow_write = ctx.allow_tt_write;
            if allow_write {
                #[cfg(feature = "tt-trace")]
                maybe_trace_tt_write(TtWriteTrace {
                    stage: "ab_mate1_store",
                    thread_id: ctx.thread_id,
                    ply,
                    key,
                    depth: stored_depth,
                    bound: Bound::Exact,
                    is_pv: st.stack[ply as usize].tt_pv,
                    tt_move: mate_move,
                    stored_value: value,
                    eval: Value::NONE,
                    root_move: if ply >= 1 {
                        st.stack[0].current_move
                    } else {
                        Move::NONE
                    },
                });
                tt_result.write(
                    key,
                    value,
                    st.stack[ply as usize].tt_pv,
                    Bound::Exact,
                    stored_depth,
                    mate_move,
                    Value::NONE,
                    ctx.tt.generation(),
                );
                inc_stat_by_depth!(st, tt_write_by_depth, stored_depth);
            }
            // 1手詰めカットオフではヒストリ更新不要(mate_moveは特殊)
            return ProbeOutcome::Cutoff {
                value,
                tt_move: Move::NONE,
                tt_capture: false,
            };
        }
    }

    ProbeOutcome::Continue(TTContext {
        key,
        result: tt_result,
        data: tt_data,
        hit: tt_hit,
        mv: tt_move,
        value: tt_value,
        capture: tt_capture,
    })
}

// =============================================================================
// 静的評価コンテキスト
// =============================================================================

/// 静的評価と補正値の計算
///
/// # 引数
/// - `pv_node`: PVノードかどうか。PVノードでは必ずNNUE評価を実行する(YaneuraOu準拠)
#[allow(clippy::too_many_arguments)]
pub(super) fn compute_eval_context(
    st: &mut SearchState,
    ctx: &SearchContext<'_>,
    pos: &mut Position,
    ply: i32,
    in_check: bool,
    pv_node: bool,
    tt_ctx: &TTContext,
    excluded_move: Move,
) -> EvalContext {
    let corr_value = correction_value(st, ctx, pos, ply);

    // excludedMoveがある場合は、前回のstatic_evalをそのまま使用(YaneuraOu準拠)
    if excluded_move.is_some() {
        let static_eval = st.stack[ply as usize].static_eval;
        // YaneuraOu準拠: improving/opponentWorsening は VALUE_NONE を含めた生比較で算出する。
        let prev2_eval = if ply >= 2 {
            st.stack[(ply - 2) as usize].static_eval
        } else {
            Value::NONE
        };
        let prev_eval = if ply >= 1 {
            st.stack[(ply - 1) as usize].static_eval
        } else {
            Value::NONE
        };
        let improving = static_eval > prev2_eval;
        let opponent_worsening = static_eval > -prev_eval;
        return EvalContext {
            eval: static_eval,
            static_eval,
            unadjusted_static_eval: static_eval, // excludedMove時は未補正値も同じ
            correction_value: corr_value,
            improving,
            opponent_worsening,
        };
    }

    let mut unadjusted_static_eval = Value::NONE;

    // デバッグ: TTヒット時のeval状態を確認
    #[cfg(feature = "search-stats")]
    {
        use std::sync::atomic::{AtomicU64, Ordering};
        static TT_EVAL_VALID: AtomicU64 = AtomicU64::new(0);
        static TT_EVAL_NONE: AtomicU64 = AtomicU64::new(0);
        static TT_MISS: AtomicU64 = AtomicU64::new(0);
        static TT_PV_NODE: AtomicU64 = AtomicU64::new(0);

        if !in_check {
            if tt_ctx.hit {
                if tt_ctx.data.eval != Value::NONE {
                    if !pv_node {
                        TT_EVAL_VALID.fetch_add(1, Ordering::Relaxed);
                    } else {
                        TT_PV_NODE.fetch_add(1, Ordering::Relaxed);
                    }
                } else {
                    TT_EVAL_NONE.fetch_add(1, Ordering::Relaxed);
                }
            } else {
                TT_MISS.fetch_add(1, Ordering::Relaxed);
            }
        }

        // 一定間隔でログ出力
        let total = TT_EVAL_VALID.load(Ordering::Relaxed)
            + TT_EVAL_NONE.load(Ordering::Relaxed)
            + TT_MISS.load(Ordering::Relaxed)
            + TT_PV_NODE.load(Ordering::Relaxed);
        if total > 0 && total.is_multiple_of(100000) {
            eprintln!(
                "[TT-EVAL-DEBUG] valid={}, none={}, miss={}, pv={}",
                TT_EVAL_VALID.load(Ordering::Relaxed),
                TT_EVAL_NONE.load(Ordering::Relaxed),
                TT_MISS.load(Ordering::Relaxed),
                TT_PV_NODE.load(Ordering::Relaxed),
            );
        }
    }

    // YaneuraOu準拠: TTからのeval取得 + PvNodeでは必ずevaluate()
    // yaneuraou-search.cpp:2680-2706 参照
    // 「🌈 これ書かないとR70ぐらい弱くなる。」
    let mut static_eval = if in_check {
        // YaneuraOu準拠: in-check では (ss-2)->staticEval を継承する。
        // root直下 (ply < 2) は参照先がないため VALUE_NONE を使う。
        if ply >= 2 {
            st.stack[(ply - 2) as usize].static_eval
        } else {
            Value::NONE
        }
    } else if tt_ctx.hit && tt_ctx.data.eval != Value::NONE && !pv_node {
        // TTヒット && eval有効 && 非PVノード → TTからevalを取得
        ensure_nnue_accumulator(st, pos);
        unadjusted_static_eval = tt_ctx.data.eval;

        // デバッグ: TTから取得したevalとNNUE評価を比較
        #[cfg(feature = "search-stats")]
        {
            use std::sync::atomic::{AtomicU64, Ordering};
            static EVAL_MATCH: AtomicU64 = AtomicU64::new(0);
            static EVAL_MISMATCH: AtomicU64 = AtomicU64::new(0);

            let nnue_eval = nnue_evaluate(st, pos);
            if unadjusted_static_eval == nnue_eval {
                EVAL_MATCH.fetch_add(1, Ordering::Relaxed);
            } else {
                EVAL_MISMATCH.fetch_add(1, Ordering::Relaxed);
                // 不一致時の差分を出力(最初の10回のみ)
                static MISMATCH_LOG_COUNT: AtomicU64 = AtomicU64::new(0);
                let log_count = MISMATCH_LOG_COUNT.fetch_add(1, Ordering::Relaxed);
                if log_count < 10 {
                    eprintln!(
                        "[EVAL-MISMATCH] tt_eval={}, nnue_eval={}, diff={}",
                        unadjusted_static_eval.raw(),
                        nnue_eval.raw(),
                        (unadjusted_static_eval.raw() - nnue_eval.raw()).abs()
                    );
                }
            }

            let m = EVAL_MATCH.load(Ordering::Relaxed);
            let mm = EVAL_MISMATCH.load(Ordering::Relaxed);
            let total = m + mm;
            // 毎回出力(デバッグ用)
            if total == 1
                || total == 100
                || total == 1000
                || total == 5000
                || total == 10000
                || total == 18000
            {
                eprintln!(
                    "[EVAL-COMPARE] match={}, mismatch={} (mismatch rate: {:.2}%)",
                    m,
                    mm,
                    if total > 0 {
                        mm as f64 / total as f64 * 100.0
                    } else {
                        0.0
                    },
                );
            }
        }

        unadjusted_static_eval
    } else {
        // PVノード または TTミス/eval無効 → 常にNNUE評価
        unadjusted_static_eval = nnue_evaluate(st, pos);
        unadjusted_static_eval
    };

    if !in_check && unadjusted_static_eval != Value::NONE {
        static_eval = to_corrected_static_eval(unadjusted_static_eval, corr_value);
        // パス権評価を動的に追加(TTには保存されないので手数依存でもOK)
        let pass_rights_eval = {
            #[cfg(feature = "search-no-pass-rules")]
            {
                Value::ZERO
            }
            #[cfg(not(feature = "search-no-pass-rules"))]
            {
                evaluate_pass_rights(pos, pos.game_ply() as u16)
            }
        };
        static_eval += pass_rights_eval;
    }

    // YO準拠: TTミス時は eval のみを BOUND_NONE/DEPTH_UNSEARCHED で保存する。
    #[cfg(feature = "tt-trace")]
    let eval_allow_write = !in_check
        && !tt_ctx.hit
        && ctx.allow_tt_write
        && helper_tt_write_enabled_for_depth(ctx.thread_id, Bound::None, DEPTH_UNSEARCHED);
    #[cfg(not(feature = "tt-trace"))]
    let eval_allow_write = !in_check && !tt_ctx.hit && ctx.allow_tt_write;
    if eval_allow_write {
        #[cfg(feature = "tt-trace")]
        maybe_trace_tt_write(TtWriteTrace {
            stage: "ab_eval_store_none",
            thread_id: ctx.thread_id,
            ply,
            key: tt_ctx.key,
            depth: DEPTH_UNSEARCHED,
            bound: Bound::None,
            is_pv: st.stack[ply as usize].tt_pv,
            tt_move: Move::NONE,
            stored_value: Value::NONE,
            eval: unadjusted_static_eval,
            root_move: if ply >= 1 {
                st.stack[0].current_move
            } else {
                Move::NONE
            },
        });
        tt_ctx.result.write(
            tt_ctx.key,
            Value::NONE,
            st.stack[ply as usize].tt_pv,
            Bound::None,
            DEPTH_UNSEARCHED,
            Move::NONE,
            unadjusted_static_eval,
            ctx.tt.generation(),
        );
        inc_stat_by_depth!(st, tt_write_by_depth, 0);
    }

    // YOの `eval` 相当: static_eval をベースに、TT境界値で補正する。
    let mut eval = static_eval;
    if !in_check && tt_ctx.hit && tt_ctx.value != Value::NONE && {
        if tt_ctx.value > eval {
            tt_ctx.data.bound.is_lower_or_exact()
        } else {
            matches!(tt_ctx.data.bound, Bound::Upper | Bound::Exact)
        }
    } {
        eval = tt_ctx.value;
    }

    // YO準拠: improving / opponentWorsening は ss->staticEval ベースで
    // VALUE_NONE を含めた生比較で計算する。
    st.stack[ply as usize].static_eval = static_eval;

    let prev2_eval = if ply >= 2 {
        st.stack[(ply - 2) as usize].static_eval
    } else {
        Value::NONE
    };
    let prev_eval = if ply >= 1 {
        st.stack[(ply - 1) as usize].static_eval
    } else {
        Value::NONE
    };
    let improving = static_eval > prev2_eval;
    let opponent_worsening = static_eval > -prev_eval;

    EvalContext {
        eval,
        static_eval,
        unadjusted_static_eval,
        correction_value: corr_value,
        improving,
        opponent_worsening,
    }
}