File size: 5,158 Bytes
c8a6ce6
 
bf22a94
 
 
 
c8a6ce6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""Three patches that stop one unserializable value from stranding a participant.

What happened on 2026-10-22, to one participant and to another before them, both
identified in the Box admin folder: both finished all 192 trials and all 12 house
ratings, and then the page stopped advancing. It kept logging their clicks for
another 40 minutes while the stage never ended.

The chain, confirmed from the Space logs and reproduced locally:

1. Reloading the page mid-game sends EnvStage.activate down its "load stage state
   from memory" branch, which restores the state with flax's
   serialization.from_bytes. flax restores arrays as numpy, not jax. nicewebrl
   ships match_types() for exactly this and does not apply it here.
2. custom_data_fn then indexes those arrays (s.outcomes[cb, 0, 0, ct] and
   friends). Indexing a numpy array returns a numpy SCALAR, np.int32.
3. nicewebrl's make_serializable converts np.ndarray and jnp.ndarray, and a numpy
   scalar is neither, so it passes through untouched. msgpack.packb then raises
   TypeError: can not serialize 'numpy.int32' object.
4. That raise happens inside EnvStage._process_save_queue, before its
   queue.task_done(). The queue's unfinished-task count never returns to zero.
5. At the end of the stage, run_experiment awaits stage.finish_saving_user_data(),
   which awaits queue.join(). It can never return. Every later page load re-enters
   the same stage and blocks at the same join, so the participant has no way out.

Each patch below breaks the chain at a different link. Any one of them is enough
on its own, which is the point: step 5 turns a lost data record into a lost
two-hour session, and that should not be possible however the record goes bad.
"""
import asyncio

import numpy as np
from nicewebrl import stages as _stages
from nicewebrl.logging import get_logger
from nicewebrl.nicejax import match_types

logger = get_logger(__name__)


def to_python(obj):
    """Numpy scalars and arrays to plain Python, recursively. Link 2 of the chain.

    make_serializable's blind spot is the numpy scalar: np.generic is not
    np.ndarray, so isinstance misses it. .item() covers both that and a 0-d array,
    and .tolist() covers the rest.
    """
    if isinstance(obj, np.generic):
        return obj.item()
    if isinstance(obj, np.ndarray):
        return obj.item() if obj.ndim == 0 else obj.tolist()
    if isinstance(obj, dict):
        return {k: to_python(v) for k, v in obj.items()}
    if isinstance(obj, (list, tuple)):
        return [to_python(v) for v in obj]
    return obj


def install():
    """Apply all three patches. Idempotent, so importing twice is harmless."""
    if getattr(_stages, "_savequeue_fix_installed", False):
        return
    _patch_state_restore()
    _patch_save_queue()
    _stages._savequeue_fix_installed = True
    logger.info("savequeue_fix installed")


def _patch_state_restore():
    """Link 1: hand back jax arrays after a reload, the way a fresh reset does.

    match_types walks the fresh state alongside the restored one and rebuilds each
    leaf at the fresh leaf's dtype, so everything downstream sees the types it saw
    before the reload. Without it, a reloaded participant runs the rest of their
    session on numpy arrays.
    """
    original = _stages.get_latest_stage_state

    async def get_latest_stage_state(example, name):
        loaded = await original(example=example, name=name)
        if loaded is None:
            return None
        try:
            return match_types(example, loaded)
        except Exception as e:
            # A structure mismatch here would mean the saved state no longer fits
            # the current task. Keep the participant playing on the restored state
            # instead of raising inside activate(), and let patch 2 absorb any
            # serialization failure that follows.
            logger.warning(f"match_types failed for stage {name}: {e}")
            return loaded

    _stages.get_latest_stage_state = get_latest_stage_state


def _patch_save_queue():
    """Links 4 and 5: a failed record must not outlive its queue slot.

    task_done() moves into a finally, so the unfinished count always falls back to
    zero and queue.join() always returns. The record is lost and said so in the
    log; the session continues. The task also drains whatever arrived while it was
    awaiting a save, which the original loop's `while not queue.empty()` check
    could skip.
    """
    async def _process_save_queue(self):
        queue = self.get_user_queue()
        while True:
            try:
                args, timestep, user_stats = queue.get_nowait()
            except asyncio.QueueEmpty:
                return
            try:
                await self.save_experiment_data(
                    args, timestep=timestep, user_stats=user_stats,
                )
            except Exception as e:
                logger.error(
                    f"'{self.name}': dropped one save record ({type(e).__name__}: {e})"
                )
            finally:
                queue.task_done()

    _stages.EnvStage._process_save_queue = _process_save_queue