"""Per-variant experiment parameters — the single home for anything that differs between variants (D23). Why this file exists at all: the revote delay has to be quoted in three places — the training explainer, the training practice, and the live revote pages in `voting` — and K8 records what happened last time a quantity lived in three places with nothing linking them (the money penalty drifted to two different scales and needed an English sentence to reconcile them). One module, imported by both apps, is the whole defence against that recurring. What lives here: the revote delay, the score->cents scale, the voting rule, and since Stage 2 the VARIANTS table itself. The test for belonging is simple -- if a quantity is quoted in both apps, or differs between conditions, it belongs here. """ # ── The revote delay ───────────────────────────────────────────────────────── # Seconds a participant must wait, robot buttons greyed out, before they may cast # a revote. Applies to V1 and V2 in `voting`, and to the practice revote in # `training` at the SAME value, deliberately: the pilot hypothesis is that people # revote less because the wait is annoying, so they have to have actually felt it # before round 1 rather than merely read about it. # # CHANGE THIS NUMBER to change the delay everywhere. REVOTE_DELAY_SECONDS = 5 # Ceiling check, not a knob: 60 rounds x up to 2 revotes x this value is the # worst-case unpaid time added to a session. At 5s that is 10 minutes; at 30s it # is an hour. Whatever ladder the pilot uses, the top rung is set by session # length and fair pay, not by how large an effect would be convenient. MAX_REVOTES_PER_ROUND = 2 def revote_delay_seconds(participant=None) -> int: """Seconds of enforced wait before a revote may be cast, for this person. Reads the delay off their VARIANT (2026-09-02), which is what makes a 5s-vs-10s comparison possible at all. Falls back to REVOTE_DELAY_SECONDS when there is no participant or no variant yet -- training's module-level constants are built at import, before anyone has consented. WHY THE VARIANT AND NOT THE PARTICIPANT. The wait is served by the whole group at once: four people staring at the same locked buttons. Two members on different delays is not a condition, it is a bug. Since D39 a study's arms are asserted to share one delay and grouping buckets on the training profile, so a mixed-delay group stays impossible by construction rather than by a check nobody runs. """ if participant is None: return REVOTE_DELAY_SECONDS name = getattr(participant, 'variant', None) if not name: return REVOTE_DELAY_SECONDS return spec_of(name).get('revote_delay', REVOTE_DELAY_SECONDS) def spec_of(name): """The entry for a variant name, whether it is a real condition or a training POOL (D39). Pools live outside VARIANTS on purpose -- they carry a training profile and nothing else -- so this is the only lookup that accepts both. Anything that needs actual leader behaviour indexes VARIANTS directly and so raises on a pool, which is the guard, not an oversight.""" try: return VARIANTS[name] except KeyError: return POOLS[name] # ── The score → cents scale ────────────────────────────────────────────────── # Stage 3b (REDESIGN.md section 9.5b), the human's request 2026-09-01. Before # this, the participant-facing pay scale lived in four unlinked places and no # formula produced its numbers -- F31 has the full statement. It is now one line. # # CALIBRATION (2026-09-01). Target given by the human: a participant averaging # 50 points a round over the 60-round experiment is paid $9/hour for a 45-minute # session, i.e. $6.75 total, i.e. 11.25 cents a round. # # BASE_CENTS + CENTS_PER_POINT * 50 == 11.25 <- what fixes the pair # # 11.25 is not a whole number of cents, and that matters: rounding it per round # and multiplying by 60 pays $6.60, not $6.75. So the two uses are separated. # `score_to_cents` rounds, because it feeds quiz answers and printed tables that # a participant has to be able to read. `session_payment_cents` does NOT round # until the very end, because it is the money -- and it hits $6.75 exactly. # Participants are shown POINTS every round and the cent scale only in training, # so they never see the per-round rounding and cannot accumulate it. # # The split between the two is a floor-vs-incentive trade, NOT arithmetic: the # floor protects a group that plays badly, the rate rewards a group that plays # well, and the target above is met by any pair on that line. R18 is the open # question; the table of candidates is in REDESIGN.md section 9.5b. # # CHANGE THESE TWO NUMBERS to change what a point is worth, everywhere: the # training quiz answers, the scale strip on PayExplanation, the payoff table on # the pay-comprehension pages, `player.payoff`, and the external bonus script. CENTS_PER_POINT = 0.165 BASE_CENTS = 3.0 # Reference points for the LIVE score table, measured not assumed -- # check_pay_and_rule.py recomputes all three from voting.C.PAYOFFS on every run, # so they cannot go stale against the table the way they did after Stage 3: # worst option every round 1821 pts -> $4.80 ($6.40/hr) # random play 3161 pts -> $7.02 ($9.36/hr) # best option every round 4530 pts -> $9.27 ($12.36/hr) # The worst case is theoretical -- it needs a group to pick the WORST of four # options sixty times running. FROZEN 2026-09-02: Stage 3 regenerated the table # and these numbers survived it, so REDESIGN section 9.1's fourth quantity is # settled and must not move before control data is collected. TARGET_HOURLY_USD = 9.00 TARGET_MINUTES = 45 TARGET_MEAN_SCORE = 50 def score_to_cents(score) -> int: """The participant-facing pay scale: what one round's score is worth. Whole cents, because every number this feeds is shown to a participant as a cent amount and a quiz answer of 11.25 is not answerable. This is the single authority. The training quiz derives its correct answers AND its distractors from it, the templates interpolate it, `player.payoff` scales by it, and the bonus script must import it -- that last one is what finally closes O6, and until it does the promised scale and the paid scale still agree only by coincidence (D6). """ return round(BASE_CENTS + CENTS_PER_POINT * score) def cents_to_dollars_per_point() -> float: """`real_world_currency_per_point` for oTree, derived so it cannot drift. Note this is the SLOPE only: oTree's payoff machinery is linear with no intercept, so it cannot represent BASE_CENTS. `player.payoff` is decorative (D6) and the bonus script pays the real money, so the mismatch is recorded rather than fixed -- see F31. """ return CENTS_PER_POINT / 100.0 def session_payment_cents(total_points, n_rounds) -> int: """What the participant is actually paid for the experiment, in whole cents. The money, as opposed to `score_to_cents`'s display value. Rounded ONCE, at the end, from unrounded arithmetic -- summing 60 rounded per-round figures loses about 15c against the calibration target, which is a real fraction of an hourly wage this small. This is the function the external bonus script should call (O6). It is the whole of the payment: the floor is per ROUND, so a participant who plays all n_rounds is guaranteed n_rounds * BASE_CENTS however badly the group does. """ return round(n_rounds * BASE_CENTS + CENTS_PER_POINT * total_points) # ── What the participant is TOLD they earn ────────────────────────────────── # 2026-09-09, the human's request: "can all the dollar amounts in text be # variables so these are easier to change in future?" They can, and now are. # Every dollar figure on Consent.html and Commitment.html is interpolated from # this block -- there is no dollar sign followed by a digit left in either file, # and check_pay_and_rule.py asserts that. # # WHY THIS IS NOT PEDANTRY. Before this, four money claims were typed by hand # across the two pages and they had drifted from the pay scale AND from each # other: the experiment was advertised at "$7-$13.75" against a scale that tops # out near $9.23, training was "$1.50" on one page and "$2.50" on the other, and # a "total potential" line added up neither pair. F44 is how one of those halves # stayed wrong invisibly for so long. # # THE ONLY HAND-SET FIGURE HERE IS THE TRAINING FEE. The experiment range is # COMPUTED from SCORE_MEANS and the pay scale above, so it cannot go stale # against them; the waiting fee lives with the wait it pays for. # # WHOEVER CHANGES A FIGURE must repoint the matching CloudResearch link, which # is the thing that actually pays: 'traininglink' for the training fee, # 'waitedlink' for the waiting fee, 'bonuslink' plus the external bonus script # (O6) for the experiment. TRAINING_PAY_USD = 1.50 # ~10 minutes -> $9.00/hour def usd(amount) -> str: """A dollar amount as a participant should read it: "$1.50".""" return f"${amount:.2f}" def experiment_pay_bounds_usd(): """(low, high) dollars for the experiment alone, over a REAL run. Derived from the option means and the pay scale, so the advertised range and the amount the bonus script computes cannot disagree. The bounds are what a group scoring the WORST option every round and the BEST option every round would earn -- the honest extremes of the mechanism. Deliberately N_EPOCHS * ROUNDS_PER_EPOCH_FULL, never num_rounds(): the short-run pin must not quietly rewrite the advertised payment into the fraction a four-round debug session pays. Same reasoning as wait_limit_text(), and check_pay_and_rule.py stays red under the pin anyway. NOTE the realistic range is much narrower than these bounds. The measured control pilot scored 95% of the structural maximum (D41/R23) -- good groups all converge on the best option -- so almost nobody lands near the floor. """ n = N_EPOCHS * ROUNDS_PER_EPOCH_FULL lo = session_payment_cents(SCORE_MEANS[0] * n, n) / 100 hi = session_payment_cents(SCORE_MEANS[-1] * n, n) / 100 return lo, hi def training_pay_text() -> str: return usd(TRAINING_PAY_USD) # ── The ADVERTISED range: rounded, and floored at what was promised ───────── # 2026-09-09, the human's request: "round the numbers... I want to avoid the # precise values." The computed bounds above are $4.77 - $9.22, which reads like # a spreadsheet and invites a participant to work out their own arithmetic # mid-study. What they are shown is a round TOTAL range instead. # # $7.50 - $10.50 total = $1.50 training + $6.00 - $9.00 experiment # # WHY THE FLOOR IS RAISED, and why that is honest rather than generous. The # computed floor, $6.27 total, is what a group scoring the WORST of four options # in all 60 rounds would earn. No individual can produce that: the group needs # 3 of 4 votes to act (VOTING_THRESHOLD), so one participant choosing badly on # purpose cannot drag the payment down, and a timeout submits the previous # round's winner (D26) rather than a fresh bad draw. To land under $7.50 a whole # GROUP must average below 42.4 points a round -- worse than always taking the # SECOND-worst option -- when the lowest CALIBRATED arm, bad_leader, targets # 47.1. $7.50 is also the figure the CloudResearch listing promises, so the # advertised floor and the recruitment promise are now the same number. # # THIS IS NOT A GUARANTEE THE CODE ENFORCES. session_payment_cents will still # compute less than $6.00 for a group that plays that badly, and the money is # paid by the human's external script (O6) rather than by oTree. If the floor # must be literally true, that script applies it -- max(computed, $6.00) on the # experiment portion. check_pay_and_rule.py asserts the design cannot reach it, # which is the next best thing. # # THE CEILING SLIGHTLY UNDER-PROMISES, deliberately. A group taking the best # option all 60 rounds earns $10.77, $0.27 above the advertised $10.50. Paying # more than advertised is safe; the round number is worth it. ADVERTISED_TOTAL_MIN_USD = 7.50 ADVERTISED_TOTAL_MAX_USD = 10.50 def points_per_round_for_total(total_usd) -> float: """The score/round a group must average to earn this total, training incl. The inverse of session_payment_cents, over a real run. It exists so the advertised floor can be checked against the DESIGN rather than against a comment: check_pay_and_rule.py asserts every calibrated arm sits above it, so lowering a leader target below the advertised floor turns the suite red. """ n = N_EPOCHS * ROUNDS_PER_EPOCH_FULL cents = (total_usd - TRAINING_PAY_USD) * 100 return (cents - n * BASE_CENTS) / CENTS_PER_POINT / n def experiment_pay_text() -> str: """The experiment range alone, rounded: "$6.00 - $9.00".""" return (f"{usd(ADVERTISED_TOTAL_MIN_USD - TRAINING_PAY_USD)} - " f"{usd(ADVERTISED_TOTAL_MAX_USD - TRAINING_PAY_USD)}") def total_if_grouped_text() -> str: """Training + experiment, which is what a participant who plays earns.""" return f"{usd(ADVERTISED_TOTAL_MIN_USD)} - {usd(ADVERTISED_TOTAL_MAX_USD)}" def total_if_waited_text() -> str: """Training + waiting, for someone who commits but is never grouped.""" return usd(TRAINING_PAY_USD + WAIT_PAY_USD) # ── The quality scale the training TEACHES ────────────────────────────────── # 2026-09-08, the human's request. The pay-comprehension table used to teach the # four scores 25 / 50 / 75 / 90 and draw distractors from an eight-value list # that was likewise typed by hand. Two things were wrong with that pair of # lists, and neither was visible from inside training/: # # 1. ASYMMETRY. 25/50/75/90 is evenly spaced for three steps and then jumps 15 # instead of 25, so the taught scale bends at the top. The distractor list # (30,35,40,45,60,70,80,85) is denser below 50 than above it. A participant # reading either one is being taught a scale whose shape is an accident. # 2. NO LINK TO THE EXPERIMENT. The numbers were free-floating. Nothing stopped # the training table from teaching a range NARROWER than the scores the # voting app can actually produce, which would leave a participant # extrapolating off the end of a table they were told to look values up in. # # Both are fixed by deriving the taught values from the real ones. The two # constants below are the ground truth of the experiment's quality scale, and # check_score_table.py asserts the LIVE CSV realises them, so they cannot go # stale against the table the way a hand-copied number would. # # CHANGE THESE to change what the training table teaches -- and regenerate the # score table to match, because these describe it, they do not create it. SCORE_MEANS = (30, 45, 60, 75) # the four option means, voting/Generate_Scores.py SCORE_NOISE_HALF_WIDTH = 5 # uniform +-this around a mean # The absolute scale a Sample Quality Score is presented on. Not a knob: it is # what "a score out of 100" means to a participant, and PayExplanation's strip # already runs 0..100. SCORE_SCALE_MIN = 0 SCORE_SCALE_MAX = 100 def score_scale_centre() -> float: """The midpoint of the presented 0-100 scale. The taught values are mirrored about THIS, not about the midpoint of the option means -- the participant is being taught to read a 0-100 scale, and a table centred on 52.5 would teach them the experiment's own asymmetry as if it were the scale's.""" return (SCORE_SCALE_MIN + SCORE_SCALE_MAX) / 2 def taught_scale_bounds(): """(low, high) for the training pay table: symmetric about the scale centre and strictly wider than the range of the real option means. The half-span is the furthest any option MEAN sits from the centre, plus one noise half-width. That second term is what makes the table wider than the means rather than merely as wide: it is exactly the amount by which a single realised draw can exceed its own mean, so every score a participant can actually see falls inside the table's span, and both ends of the table lie outside the range of the means (which is what was asked for). With SCORE_MEANS = (30,45,60,75) and a half-width of 5 this is (20, 80) against a mean range of (30, 75) and a realised range of (25, 80). """ centre = score_scale_centre() half = max(abs(mu - centre) for mu in SCORE_MEANS) + SCORE_NOISE_HALF_WIDTH low = max(SCORE_SCALE_MIN, centre - half) high = min(SCORE_SCALE_MAX, centre + half) return int(round(low)), int(round(high)) def taught_class_averages(n=4): """The n scores the pay-comprehension table lists, low to high. Evenly spaced across taught_scale_bounds(), so the list is symmetric about the scale centre in both senses that matter: value i and value n-1-i are equidistant from it, and consecutive gaps are equal. Integers, because they are printed to participants and looked up in a table. """ low, high = taught_scale_bounds() step = (high - low) / (n - 1) return [int(round(low + i * step)) for i in range(n)] def distractor_class_averages(step=5): """Scores used only to generate WRONG options for the pay quiz. Every multiple of `step` inside the taught bounds that is not itself a taught row. Derived rather than listed, so the pool is automatically symmetric about the centre and automatically inside the table's span -- which is the property that matters for the item: each distractor is the correct payment for some OTHER score on the same scale, so the question tests whether the participant read the table, not whether they can spot an implausible figure. """ low, high = taught_scale_bounds() taught = set(taught_class_averages()) first = low + (-low) % step return [s for s in range(first, high + 1, step) if s not in taught] # ── The voting rule ───────────────────────────────────────────────────────── # Stage 1 (REDESIGN.md section 9.3), 2026-09-01. Two numbers, in one place, # because they are quoted in BOTH apps: `voting` enforces them and `training` # teaches them, and F6 is what happened last time only one of the two moved (the # constant went to unanimity, two icon pages kept saying "3/4 or 4/4", and the # participant-facing rule and the enforced rule disagreed for months). # # This also kills K1. VOTING_THRESHOLD used to be DEFINED as N_GROUP, so the # group size silently *was* the voting rule and changing one changed the other. # They are now independent numbers that happen to describe the same group. N_GROUP = 4 VOTING_THRESHOLD = 3 # 3 of 4. Was 4 (unanimous) until Stage 1. N_STRATEGIES = 4 # robot options per round; voting.C.N_STRATEGIES reads this # Why 3 and not 4. Unanimity exists to make stalling reachable (I9) and that is # still the point -- but at 4/4 a single unresponsive participant can veto every # round, and the forced-submit fallback then decides for the whole group. At 3/4 # a group can absorb one silent member and still act, while three-way splits # still fail and still cost a revote. Coordination failure stays observable; # it stops being hostage to one person's attention. # ── The grouping wait ─────────────────────────────────────────────────────── # 2026-09-09, the human's request: the release moved from 10 minutes to 20. # # Seconds a participant may sit on voting.Grouping_WaitPage before they are # released alone, paid the waiting rate, and routed past the experiment. Lives # here rather than in voting.C because BOTH apps quote it: `voting` enforces it # and prints the live countdown from it, and `training` promises it three times # on Commitment.html and once on Consent.html. That is the F6/K1/K8 pattern # exactly -- a number one app enforced and the other typed by hand -- and this # is the file that exists to stop it recurring. # # CHANGE THIS NUMBER to change the wait everywhere. Two couplings come with it: # # 1. K10. settings.GBAT_INACTIVE_SECONDS_UNTIL_PROMPT must comfortably outlast # this, or oTree's "are you still there?" modal bounces a waiter off the # page before the release can fire and nobody is ever let go (F38). It is # held at 3x this value; check_long_wait.py asserts the inequality. # 2. The advertised session length. 20 minutes of waiting on top of a ~35 # minute experiment is what a participant may now be asked to sit through. GROUPING_WAIT_SECONDS = 20 * 60 # What the waiting participant is told they get, and what `voting` books onto # player.payoff when it releases them. PLACEHOLDER, and deliberately so: oTree # does not pay anyone here (player.payoff is decorative -- CLAUDE.md, "the shape # of the thing"). The money is the CloudResearch completion link the participant # is redirected to, plus the human's external bonus script, and those two alone # decide the real amount. This number exists so the participant-facing sentences # and the release have one source instead of four hand-typed dollar signs. # # WHOEVER CHANGES IT must repoint settings.SESSION_CONFIGS['waitedlink'] to a # CloudResearch link that actually pays the new figure, or the study promises # one number and pays another. # # 2026-09-09: $3.00, which is what the CloudResearch listing actually offers -- # "an additional $3.00 ($4.50 for approx. 10 minute training + 20 minute # waiting)". It was briefly written here as a $4.00 placeholder; the listing is # the authority, because it is the thing that pays. WAIT_PAY_USD = 3.00 def countdown_text(seconds) -> str: """A number of seconds as a participant should read it: "20 minutes". D33 -- a page states the limit it is actually running, so the short-wait pin (voting.QUICK_WAIT_SECONDS) cannot leave a template promising twenty minutes while the code releases after thirty seconds. Whole minutes read as minutes; anything else reads as seconds, which is only ever the pin. """ seconds = int(round(seconds)) if seconds % 60 == 0 and seconds >= 60: minutes = seconds // 60 return f"{minutes} minute" + ("" if minutes == 1 else "s") return f"{seconds} second" + ("" if seconds == 1 else "s") def wait_limit_text() -> str: """The REAL limit as prose, for training's Consent and Commitment. Deliberately not pin-aware: voting.QUICK_WAIT_SECONDS lives in `voting` and training cannot see it without importing the app. Under the pin these two pages therefore over-promise -- accepted, because the pin already declares that the run collects no groups and pays everyone the waiting rate. The voting wait page itself still prints the pinned number, which is the page D33 was written about. """ return countdown_text(GROUPING_WAIT_SECONDS) def wait_pay_text() -> str: """The waiting payment as a participant should read it: "$4.00".""" return f"${WAIT_PAY_USD:.2f}" # ── The admin Report tab: when to pause recruitment (D53, 2026-09-15) ──────── # Read ONLY by voting.vars_for_admin_report, the research assistant's traffic # light. No participant sees these numbers and no pay depends on them. # # "Active" = in training + waiting for a group + in a group still playing. Every # overlapping CloudResearch study feeds the ONE room, so this is the server's # total, which the per-study cap of 16 on CloudResearch cannot see. # # Why 16, from the pilot page-time exports (arrived and not yet at Pay/noPay): # 2026-09-09 froze with 16-20 active (12 in the experiment, 7 in training) # 2026-09-13 peaked at 17, no freeze # 2026-09-10 peaked at 15, no freeze # 2026-09-06 peaked at 13, no freeze # ONE freeze, and F48 says a wedged thread rather than load. So 16 is a cautious # rule of thumb chosen by the human, not a measured capacity. A pause only stops # NEW arrivals: anyone already in training stays on the server for another # ~40-50 minutes, and people who accepted on CloudResearch but have not opened # the link are invisible here. Hence the gap below the resume line. REPORT_PAUSE_AT = 16 # active >= this: pause every study REPORT_RESUME_BELOW = 12 # active < this: studies may be resumed; between: hold # After how long without a page request a participant is shown as "probably # left" and stops counting. Training has no page timeouts, so a participant who # closed the tab on Consent would otherwise count for the rest of the night. # Ten minutes is about one whole training run (median 8-13 minutes). A group is # still playing while ANY member made a request within the voting limit; voting # pages time out after 30-90 s, so three minutes of silence means nobody is there. # The same limit covers someone waiting for a group: oTree's wait page reloads # itself every 10-70 s, so a live waiter is never silent for three minutes. REPORT_TRAINING_IDLE_SECONDS = 10 * 60 REPORT_VOTING_IDLE_SECONDS = 3 * 60 # ── The robot labels ──────────────────────────────────────────────────────── # The four options, named. One home because THREE files quote them: voting.C, # training.C, and (since 2026-09-02) training's scenario generator. # # Training used to relabel them "Robot 1..4" on purpose, to stop a participant # carrying a named favourite out of a practice scenario and into round 1. The # human judged the two label sets more confusing than the anchoring risk, and # the risk is small in any case: each practice scenario names a robot drawn at # random per participant (`random.choice` in `_voting_vars`), so any anchoring is # idiosyncratic rather than systematic. Reversing this is one line: give # training's ROBOTS its own list again. BUTTON_LABELS = ["Robot K3M", "Robot N7P", "Robot V2X", "Robot Z5B"] # ── The round structure ───────────────────────────────────────────────────── # The voting app is N_EPOCHS epochs of ROUNDS_PER_EPOCH_FULL rounds. Both live # here because BOTH apps quote them: `voting` builds its round plan from them and # `training`'s PayExplanation tells the participant how many rounds they play. # # Read this before touching it: voting.C.EPOCH did NOT drive the round structure # (F36). The real epoch length was however many distinct Index values the CSV # happened to hold per epoch -- 15 -- and C.EPOCH was a constant nothing read. # Editing it looked like shortening an epoch and did precisely nothing. It is now # derived from rounds_per_epoch() and the round plan truncates to it, so the # named length and the actual length cannot drift apart again. N_EPOCHS = 4 # Simple1, Complex1, Simple2, Complex2 ROUNDS_PER_EPOCH_FULL = 15 # distinct CSV Index values per epoch -- the real run # ── Debugging pin: the short run ──────────────────────────────────────────── # Set to an int to shorten every epoch, so the whole voting app can be clicked # through in minutes. 1 gives a four-round experiment with an epoch boundary at # EVERY round, which is the point of it: nothing on any participant page names # the epoch, and the only observable consequence of a boundary is that the best # option silently becomes a different option. A walkthrough that wants to see # the rotation needs the boundaries close together and the terminal trace on. # # QUICK_TEST_ROUNDS_PER_EPOCH = 1 <- 4 rounds, one per epoch # QUICK_TEST_ROUNDS_PER_EPOCH = None <- the real 60-round run # # A PIN, not a knob -- and a louder one than FORCE_VARIANT, because it is worse. # FORCE_VARIANT only makes data worthless; this also changes what participants # are PAID: session_payment_cents scales with the round count, so a run left # pinned pays a fraction of the advertised amount to a real person. So # check_pay_and_rule.py FAILS while it is set and `voting` shouts at import. # # 2026-09-09: pinned at 1 for a click-through walkthrough, then UNPINNED the same # day for data collection. # 2026-09-13: PINNED AT 1 AGAIN for the human's devserver walkthrough of D48/D49 # (4 rounds, an epoch boundary every round). # 2026-09-13: UNPINNED the same evening at the human's request, for the build # that collects data. # 2026-09-15: PINNED AT 1 for the human's devserver click-through of the # good_bad study and the Report tab (D53/D54). The RA zip was built BEFORE this # (Shkelqim_15_09_good_bad, unpinned). Unset before any further build -- # check_zip.py is red while it is set, so make_zip.py refuses. # 2026-09-15: UNPINNED after the human clicked one group of four through it # successfully, for that night's data collection. QUICK_TEST_ROUNDS_PER_EPOCH = None def rounds_per_epoch() -> int: """Rounds in one epoch: the pin when set, otherwise the real length.""" if QUICK_TEST_ROUNDS_PER_EPOCH is None: return ROUNDS_PER_EPOCH_FULL return QUICK_TEST_ROUNDS_PER_EPOCH def num_rounds() -> int: """Total rounds in the voting app. voting.C.NUM_ROUNDS reads this, and training quotes it to the participant.""" return N_EPOCHS * rounds_per_epoch() def is_quick_test() -> bool: """Whether the short-run pin is set. Guards and banners read this.""" return QUICK_TEST_ROUNDS_PER_EPOCH is not None # ── The variants ───────────────────────────────────────────────────────────── # Stage 2 (REDESIGN.md section 8.2 / 9.4), 2026-09-02. The experimental # condition, keyed by name, replacing the retired 2x2 of bribery x # complexity-order (`group.treatment_bribed_leader` / `.treatment_simple_complex`, # the four C.*_SIM_COM quotas, the four session counters and the five bribe_* # setters -- all of which F16 recorded as confounded with arrival order anyway). # # HOW LEADER QUALITY IS EXPRESSED, and why adding a level is one line. # THIS PARAGRAPH DESCRIBES THE MECHANISM AS OF STAGE 2 AND IS SUPERSEDED BY D48 # BELOW -- the draw is no longer 50/50. It is kept because its closing caveat is # exactly what happened, and because the ranks half of it is still true. # The leader was never handed a score: it is handed TWO options, fixed for the # whole epoch, and drew between them 50/50 each round it acted. The two are # picked by RANK in that epoch's option ordering, best first: # # rank 0 = best option this epoch, rank 3 = worst # # So a leader's quality just IS a pair of ranks. With epoch means {30,45,60,75} # that fixes its expected score exactly: # # ranks (0,1) -> (75+60)/2 = 67.5 ranks (0,2) -> (75+45)/2 = 60.0 # ranks (0,3) -> (75+30)/2 = 52.5 ranks (1,2) -> (60+45)/2 = 52.5 # ranks (1,3) -> (60+30)/2 = 45.0 ranks (2,3) -> (45+30)/2 = 37.5 # # CAVEAT worth knowing before Stage 6: those six values are ALL the mechanism can # produce. If control turns out to average, say, 57, no pair hits it. Getting an # arbitrary target needs an unequal draw instead of the 50/50 in # ThreeVotes_WaitPage -- a small change, but a change. Do not pre-build it; just # do not assume the calibration will land on one of the six. # <- IT DID NOT. D37 added an unequal draw; D48 (below) now solves it. # Every entry carries `revote_delay`. All four are REVOTE_DELAY_SECONDS today, # so the delay is currently a constant wearing a variant's clothes -- nothing # about behaviour changes until two entries disagree. See the block below this # dict for how to run a 5s-vs-10s pilot and what it costs. # ── The leaders (D48, 2026-09-13) ──────────────────────────────────────────── # REPLACES D37's calibration (unequal draw + a 3-round adjustment lag, solved by # hand against M_CONTROL). The human's rule, in full: # # * NO LAG. Every leader switches to the new epoch's ranking on its first round. # * GOOD sends the epoch's best option every round. # * EQUAL scores what a no-leader control group scores: EQUAL = M_CONTROL. # * BAD sends the epoch's THIRD-best option every round (D54, 2026-09-15). # # D54 REPLACED D48's bad rule, BAD = 2*EQUAL - GOOD (50.13, a 33/67 mix of the # second- and third-best options), at the human's request: both leaders the # 2026-09-15 build runs are now deterministic, one option each. The two gaps are # no longer equal (good - equal = 12.7, equal - bad = 17.4), and bad-leader data # from before 2026-09-15 is not poolable with data after. # # The ONE number a person sets is M_CONTROL below, and since D54 it moves only # the equal leader; the good and bad leaders' scores come from the score table. # Every rank pair and probability is SOLVED here at import. Nothing below # M_CONTROL is typed by hand, so nothing can go stale. # # HOW A LEADER HITS A SCORE THAT IS NOT AN OPTION'S MEAN. It mixes the two # adjacent options that bracket it. E.g. a target of 62.8 lies between the best # (75.47) and second-best (59.75) option, so the leader sends the best option # with p = (62.8 - 59.75) / (75.47 - 59.75) = 0.19 and the second-best otherwise. # Adjacent ranks are the smallest mix that reaches the target, which keeps the # leader as consistent as its score allows. A target exactly on an option's mean # gives that rank with p = 1.0: a deterministic leader (good_leader and, since # D54, bad_leader -- R27). # # THE MEANS ARE THE TABLE'S REALISED ONES, not the idealised 75/60/45/30: the # noise the generator drew moves them by up to half a point, and a leader is paid # what the table pays. check_leader_calibration.py re-derives every score through # voting's own draw function, from voting's own reading of the CSV. # # WHAT THE RULE COSTS (D48, D54): # * A group that always follows the bad leader scores the third-best mean, # 45.44, and is paid $6.30 -- above the advertised $6.00 floor (D46), but # only by 30 cents. check_pay_and_rule.py goes red if a table change pushes # it under. (Under D48 an M_CONTROL error was doubled in BAD; since D54 it # cannot reach BAD at all.) # And a target outside the table (above the best option, or below the worst) # has no solution: importing this file then raises, naming the number. # The payoff table `voting` plays. ONE home for the filename: voting loads it # from here, and the leader solve below reads the same file. SCORE_TABLE = 'voting/Scores_Sept_2026-09-03.csv' # ▶▶ SET THIS: the average points per group-round a NO-LEADER control group # scores, over all 60 rounds. It is the equal leader's score, and it moves # the bad leader with it. Run check_leader_calibration.py after changing it. # # 62.8 CURRENT VALUE, kept from D37 -- a guess: the midpoint of 65.19 # (measured under the retired rotation) and 60.36 (a projected floor). # 71.77 MEASURED on this table, session yhg5qqht, 2026-09-06, but n = 2 # groups (73.33 and 70.21). NOT adopted -- see C10 and D41. # 62.6 PROXY: the three 2026-09-10 leader-study groups that never delegated # (65.0, 64.7, 58.1). Not a control -- they could have delegated. M_CONTROL = 62.8 def _realised_rank_means(): """Mean score of the best, second, third and worst option, averaged over every (score set, epoch) slice of SCORE_TABLE. Within a slice an option's quality is its mean over every row, which is voting.epoch_option_means' definition; the ranks are taken per slice, because the best option is a different option in each epoch. Read with the csv module so this file keeps no third-party imports.""" import csv, os path = os.path.join(os.path.dirname(os.path.abspath(__file__)), SCORE_TABLE) sums = {} with open(path, newline='') as f: for row in csv.DictReader(f): key = (row['treatment'], row['epoch'], int(row['Option'])) s, n = sums.get(key, (0.0, 0)) sums[key] = (s + float(row['Feedback_Score']), n + 1) slices = {} for (treatment, epoch, option), (s, n) in sums.items(): slices.setdefault((treatment, epoch), []).append(s / n) by_rank = [sorted(means, reverse=True) for means in slices.values()] return tuple(sum(col) / len(col) for col in zip(*by_rank)) RANK_MEANS = _realised_rank_means() # best first; about (75.47, 59.75, 45.44, 30.08) def solve_leader(target, rank_means=RANK_MEANS): """(ranks, p) for a leader that averages `target` points a round: the two adjacent ranks bracketing it, and the probability of sending the better one.""" for better in range(len(rank_means) - 1): if target == rank_means[better]: # Exactly one option's mean: send THAT option every round, named as # the better rank of its pair so the trace reads (2, 3) p=1.0 for # "always third-best" rather than the equivalent (1, 2) p=0.0. # A separate pass, so the bracket below cannot claim it first. return (better, better + 1), 1.0 for better in range(len(rank_means) - 1): hi, lo = rank_means[better], rank_means[better + 1] if lo <= target <= hi: return (better, better + 1), (target - lo) / (hi - lo) raise ValueError( f'No leader can average {target:.2f} points a round: the options in ' f'{SCORE_TABLE} average {rank_means[0]:.2f} (best) to ' f'{rank_means[-1]:.2f} (worst). Check M_CONTROL ({M_CONTROL}).') GOOD_LEADER_SCORE = RANK_MEANS[0] # the best option, every round EQUAL_LEADER_SCORE = M_CONTROL BAD_LEADER_SCORE = RANK_MEANS[2] # the third-best option, every round (D54) def _leader(target): ranks, p = solve_leader(target) return dict(has_leader=True, leader_ranks=ranks, leader_p=float(p), leader_target=float(target), revote_delay=REVOTE_DELAY_SECONDS) VARIANTS = { # The control. No governance question, no leader, every round is a vote. 'no_leader': dict(has_leader=False, leader_ranks=None, leader_p=None, revote_delay=REVOTE_DELAY_SECONDS), 'bad_leader': _leader(BAD_LEADER_SCORE), 'equal_leader': _leader(EQUAL_LEADER_SCORE), 'good_leader': _leader(GOOD_LEADER_SCORE), } # Sanity: every variant with a leader must name two adjacent ranks in range, a # probability on the first of them, and the score it was solved for. for _name, _spec in VARIANTS.items(): if _spec['has_leader']: _r = _spec['leader_ranks'] assert _r is not None and len(_r) == 2 and _r[1] == _r[0] + 1, _name assert all(0 <= r < N_STRATEGIES for r in _r), _name _p = _spec['leader_p'] assert isinstance(_p, float) and 0.0 <= _p <= 1.0, _name assert isinstance(_spec['leader_target'], float), _name else: assert _spec['leader_ranks'] is None and _spec['leader_p'] is None, _name assert _spec.get('leader_target') is None, _name assert isinstance(_spec.get('revote_delay'), int), _name assert _spec['revote_delay'] >= 0, _name assert len(RANK_MEANS) == N_STRATEGIES # ── Running a 5s-vs-10s delay pilot (REDESIGN.md section 9.6, Stage 4) ─────── # The machinery is in place: give two variants different `revote_delay` values # and everything downstream follows -- training rehearses the right number, # quizzes on the right number, V1/V2 wait the right number, and the page timeout # is extended by the right number. # # To split the control by delay, replace the 'no_leader' entry above with: # # 'no_leader_5s': dict(has_leader=False, leader_ranks=None, revote_delay=5), # 'no_leader_10s': dict(has_leader=False, leader_ranks=None, revote_delay=10), # # and update any `== 'no_leader'` comparison to `not has_leader(...)`. # # WHAT IT COSTS, because this is not free: # # Grouping. A group must be four people on the SAME delay, so splitting one # condition in two doubles the number of buckets four arrivals have to land in # (R10). Sixteen completers becomes two conditions of eight, and eight is two # groups, which is not enough of either to say anything. # # Session length. Worst case is NUM_ROUNDS x MAX_REVOTES_PER_ROUND x delay of # unpaid waiting: 10 minutes at 5s, 20 at 10s. The pay calibration (D27) has no # term for it, so the 10s arm is paid the same for a longer session -- which is # the manipulation, but it is also a fairness question, and TARGET_MINUTES = 45 # is currently a promise made to both arms. # # The DV. If the delay changes revoting, it changes how long a round takes, # which changes how many rounds fit an attention span. Rounds-to-switch (R15) # is measured in rounds, not minutes, so this is a confound to state, not to # discover afterwards. # ── Debugging pin ──────────────────────────────────────────────────────────── # Set to a variant name to force EVERY participant into that condition, bypassing # the deal entirely. For walking one condition through a devserver run. # # FORCE_VARIANT = 'no_leader' <- pin the control # FORCE_VARIANT = None <- deal normally (the only setting for data) # # This is a PIN, not a knob. While it is set the experiment has one condition and # any data collected is worthless, so `check_variants.py` FAILS while it is set -- # deliberately, the same way the DRAFT TEXT badge (D25) makes draft prose # impossible to run with participants by accident. A suite that stayed green here # would be a check passing for the wrong reason. FORCE_VARIANT = None def variant_of(participant) -> str: """The variant this participant is in. One string, assigned once at consent.""" return participant.variant def has_leader(participant) -> bool: """Whether a leader exists at all for this participant. This is the ONE predicate that decides whether the governance question is asked, whether the leader training block is shown, and whether ThreeVotes_WaitPage tallies governance. Everything else about the control condition follows from it. Defined for a training POOL as well as a real condition (D39): a participant carries their study's pool through training and only receives an arm when their group forms, and every page before that still has to know whether it is teaching a leader. """ return has_leader_of(participant.variant) def has_leader_of(variant_name) -> bool: """`has_leader` by NAME rather than by participant -- the form grouping and `Experiment_WaitPage` need, since both reason about a name before any participant carries it.""" return spec_of(variant_name)['has_leader'] def played_with_leader(participant) -> bool: """Whether this participant played the main experiment in a group that had a Mission Commander -- the audience for the bot disclosure (D49). Read off the ARM, not the training pool: `participant.variant` only becomes an arm name ('bad_leader', ...) when Experiment_WaitPage deals the group its condition (D39), so an arm with a leader is proof of having been grouped with one. `voting` has no early exit, so anyone who reaches Pay or noPay carrying such an arm has been through all its rounds. `.vars.get` because this is read on exit pages that people excluded in training also pass through, where the fields were never written (F45).""" v = participant.vars arm = v.get('variant') return (arm in VARIANTS and VARIANTS[arm]['has_leader'] and not v.get('is_single', False)) def leader_ranks(variant_name): """The two option ranks (0 = best this epoch) the leader draws between, or None for a variant with no leader.""" return VARIANTS[variant_name]['leader_ranks'] def leader_p(variant_name) -> float: """Probability the leader sends the FIRST (better) of its two ranks, per round. Solved from leader_target by solve_leader (D48); 1.0 means the leader is deterministic.""" return VARIANTS[variant_name]['leader_p'] def leader_target(variant_name): """The points per round this variant's leader averages: GOOD_LEADER_SCORE, EQUAL_LEADER_SCORE or BAD_LEADER_SCORE (D48). None for no_leader.""" return VARIANTS[variant_name]['leader_target'] # ── The study, and how a group gets its condition (D39, 2026-09-04) ────────── # THE ONE VARIABLE. `STUDY` says which experiment this deployment is running. # Everything else -- what training teaches, which conditions exist, how groups # are formed -- follows from it. # # STUDY = 'control' <- the no-leader benchmark, one condition # STUDY = 'leader' <- the three leader qualities, rotated across groups # STUDY = 'good_bad' <- good and bad leaders only, alternating (D54) # # WHY TWO STUDIES AND NOT ONE. Grouping needs four people on the wait page at # once. Under the retired design a group also had to share a CONDITION, dealt at # consent in contiguous blocks of 8 -- and since training runs 4 to 43 minutes, a # block arrived smeared far wider than the wait (ten minutes at the time; twenty # since D45, which widens the window but does not change the argument). The paused pilot # (session io0jtu90, 2026-09-03) is the measurement: 16 arrivals, 6 separate # moments with four people waiting together, ONE group. Replayed variant-blind # the same arrivals give three. Resampled, the rule as built groups ~47 % of # arrivals against ~72 % blind, and the gap does not close with volume. # # Splitting the control out is what makes blindness possible, because the # CONTROL IS THE ONLY CONDITION WHOSE TRAINING DIFFERS: `has_leader` decides # whether the governance question is taught, demonstrated and asked. The three # leader qualities differ only in the leader's draw, which nothing before # `voting` touches -- so within the leader study every participant is # interchangeable at the wait page and any four of them make a group. # # THE COST, accepted by the human 2026-09-04: condition is confounded with # recruitment wave, because control and leader arms are now collected in # separate sessions. That lands on H1 (control vs leader), which is the contrast # M_CONTROL calibrates. It is C8. It is not free and it is not hidden; it buys # the ordering the calibration actually needs -- run 'control' first, measure # M_CONTROL for real, re-solve every leader_p, then run 'leader'. STUDY = 'good_bad' # What each study teaches and what conditions it rotates through. # # `pool` the variant name every participant of this study carries THROUGH # TRAINING. It fixes has_leader and the revote delay -- the only two # things training reads off a variant -- and nothing else. # `arms` the conditions groups are dealt, IN THIS ORDER, one per group. # # The control study's pool is a real variant because it has only one condition; # the leader study's is a placeholder, resolved when a group forms. STUDIES = { 'control': dict(pool='no_leader', arms=('no_leader',)), 'leader': dict(pool='leader_pool', arms=('bad_leader', 'equal_leader', 'good_leader')), # D54 (2026-09-15): the leader study without its equal arm. Same pool, so the # same training, and groups alternate bad -> good -> bad ... 'good_bad': dict(pool='leader_pool', arms=('bad_leader', 'good_leader')), } # Placeholder variants: a training profile with no leader behaviour attached. # Deliberately NOT in VARIANTS -- a pool has no ranks, no p and no target, and # keeping it out means check_leader_calibration.py and check_variants.py still # iterate exactly the four real conditions, and `leader_ranks('leader_pool')` # raises rather than silently returning None on a live round. POOLS = { 'leader_pool': dict(has_leader=True, revote_delay=REVOTE_DELAY_SECONDS), } # ── The stopping rule (D56, 2026-09-20) ────────────────────────────────────── # The prereg (../Prereg/"Josh - Leader - OSF Preregistration v5.txt", *Starting # and stopping rules*) is the authority: # # "Data will be collected until we have 30 analysable groups in each # condition, plus an additional three groups, per condition, to account for # data withdrawal upon the debrief of minor deception. ... If one condition # reaches 30 analysable groups first, subsequent groups are assigned to the # remaining condition." # # 30 + 3 = 33. (The v3 copy under ../Data/Prereg_dummy/ says "a further 5% of # groups (12 subjects)" TOTAL, i.e. ~31.5 an arm. It is superseded; v5 says # twelve subjects PER CONDITION. Do not re-derive 31.5 from the old file.) TARGET_GROUPS_PER_ARM = 33 # 30 analysable + 3 withdrawal buffer # ANALYSABLE groups already collected, per arm, over every PREVIOUS night. # # HAND-SET. <- SET THIS # Source since D59 (2026-09-22): the TESTED set, i.e. the per-arm row count of # ../Data/Full_good_bad_5n/Analysis/out/keep_i40/idx_group.csv. These are the # groups that survive EVERY prereg v6 exclusion, over all five good_bad nights: # (a) no member who had completed an earlier game -- that member had been # debriefed that the leader is a bot (D13 there); (b) >= 3 of 4 members active # (<= 40 % of ballots auto-submitted); and, NEW IN D59, (c) the leader decided at # least one round. # # (c) IS THE D59 CHANGE. D58 deliberately left it out and counted kept FORMED # groups instead -- ../Data/Full_good_bad_5n/Sample_size/prior_groups.py, which # still prints 33/32 and is now the wrong figure to paste. Prereg v6 stops on # "30 analysable groups in each condition" and lists "groups in which the leader # never decided a round are excluded" among its inclusion criteria, so analysable # means after that rule too. Before D58 the source was # ../Data/leader_good_bad_18_09/census.py, which knew nothing of returners. # # RE-RUN prior_groups.py AND UPDATE THIS BEFORE EVERY BUILD. It is the only thing that # carries a total across nights: `session.variant_queue` is a SESSION_FIELD and # is zeroed in training.creating_session, so a new session knows nothing about # the last one. A stale figure here silently over-collects one arm and # under-collects the other, and nothing downstream can tell. # # WHAT IT COUNTS vs WHAT THE ROTATION COUNTS (C14). These are ANALYSABLE groups; # the in-session tally `next_arm` adds to them counts groups FORMED, because # mid-night nothing knows whether a group will reach round 60 with three # responsive members. So a night can finish a group or two short of the target. # That self-corrects -- re-run prior_groups.py, update this, the next night continues # from the true figure -- but it means the last night is the one to over-recruit. PRIOR_GROUPS = { 'bad_leader': 25, 'good_leader': 29, } # as of 2026-09-22 (D59): + gmid1tkk, five nights # Groups to collect ON TOP of the shortfall, because some of the NEW groups will # be excluded too. D59. <- SET THIS # # A group whose leader never decided a round is dropped (prereg v6), and 11 of # the 65 groups collected so far went that way. Unlike a withdrawal, this is # knowable only after 60 rounds, so it cannot be dealt around -- it can only be # over-collected against. # # ONE RATE FOR BOTH ARMS, at the human's request (2026-09-22), and the data # agrees: 8/33 bad against 3/32 good is Fisher p = .185, no evidence of a # difference. The mechanism is the reason to expect none -- leader quality is # revealed only BY delegating, so a group that never delegates has received # nothing that could distinguish a good leader from a bad one. The event is # causally upstream of the manipulation. Do not re-split this per arm on the # strength of an observed imbalance; that is fitting noise. # # So: pooled 11/65 = 16.9 % (95 % CI 9.7-27.8), and each arm's shortfall is # grossed up by 1/(1 - 0.169) and rounded UP -- bad 8 -> 9.63 -> 10, good # 4 -> 4.81 -> 5. The allowance is the difference. # # IT IS AN EXPECTATION, NOT A GUARANTEE. At the CI bounds the bad arm needs # anywhere from 9 to 12, so a night can still finish short and need one more # top-up. Re-derive both dicts from the analysis after every night. EXTRA_FOR_EXCLUSIONS = { 'bad_leader': 2, # 8 short -> collect 10 'good_leader': 1, # 4 short -> collect 5 } assert STUDY in STUDIES, f"STUDY={STUDY!r} is not a study; choose one of {sorted(STUDIES)}" assert isinstance(TARGET_GROUPS_PER_ARM, int) and TARGET_GROUPS_PER_ARM > 0 # Every count must name a real condition, and every arm of the LIVE study must # have a count -- otherwise flipping STUDY would deal against a missing figure # and `groups_needed` would read it as "none collected yet". assert set(PRIOR_GROUPS) <= set(VARIANTS), sorted(set(PRIOR_GROUPS) - set(VARIANTS)) assert all(isinstance(_n, int) and _n >= 0 for _n in PRIOR_GROUPS.values()), PRIOR_GROUPS assert set(EXTRA_FOR_EXCLUSIONS) <= set(VARIANTS), sorted( set(EXTRA_FOR_EXCLUSIONS) - set(VARIANTS)) assert all(isinstance(_n, int) and _n >= 0 for _n in EXTRA_FOR_EXCLUSIONS.values()), EXTRA_FOR_EXCLUSIONS for _s, _spec_ in STUDIES.items(): assert _spec_['pool'] in VARIANTS or _spec_['pool'] in POOLS, _s assert _spec_['arms'] and all(a in VARIANTS for a in _spec_['arms']), _s # Every arm of a study must teach the same training, or its groups would be # built from people who were taught different experiments. assert len({VARIANTS[a]['has_leader'] for a in _spec_['arms']}) == 1, _s assert len({VARIANTS[a].get('revote_delay') for a in _spec_['arms']}) == 1, _s _pool_spec = VARIANTS.get(_spec_['pool']) or POOLS[_spec_['pool']] assert _pool_spec['has_leader'] == VARIANTS[_spec_['arms'][0]]['has_leader'], _s # Studies that teach DIFFERENT training must be distinguishable by pool, since # `has_leader` is what stops a stale browser from one study being grouped into # the other. Studies sharing a pool ('leader', 'good_bad') teach the same # training, so their participants are interchangeable at the wait page. _pools = {s['pool'] for s in STUDIES.values()} assert len({(VARIANTS.get(p) or POOLS[p])['has_leader'] for p in _pools}) == len(_pools) # Checked for the LIVE study only: 'control' and 'leader' are not being collected # against a target, and demanding a count for their arms would make switching # STUDY for a debug run fail at import. assert all(a in PRIOR_GROUPS for a in STUDIES[STUDY]['arms']), ( f"STUDY={STUDY!r} has arms {list(STUDIES[STUDY]['arms'])} but PRIOR_GROUPS " f"only counts {sorted(PRIOR_GROUPS)}") def study_arms(study=None): """The conditions this study rotates through, in rotation order.""" return STUDIES[study or STUDY]['arms'] def training_variant(study=None) -> str: """The variant every participant of this study carries through training. Replaces the retired `next_variant`, and takes no session: there is nothing left to deal at consent. The condition is dealt to a GROUP now (`next_arm`), which is both the unit of analysis and the unit that can actually be balanced -- see the D39 block above. """ return STUDIES[study or STUDY]['pool'] def groups_needed(dealt=None, study=None, prior=None, target=None, extra=None) -> dict: """How many more groups each arm of this study still needs, never below zero. `prior` is the carried-over ANALYSABLE count (PRIOR_GROUPS by default) and `dealt` the groups FORMED so far in the current session -- see the C14 note on PRIOR_GROUPS for why those are two different things. Both are read, never written, so the admin Report tab can call this on every refresh (F50). `extra` (EXTRA_FOR_EXCLUSIONS by default) is D59's over-collection allowance: the target is on groups that SURVIVE the exclusions, and some of what is collected from here will not, so each arm is driven to `target + extra`. Pass `extra={}` to drive the bare target, which is what the suites do when they are testing the rotation rather than the allowance. """ arms = study_arms(study) prior = PRIOR_GROUPS if prior is None else prior dealt = dealt or {} target = TARGET_GROUPS_PER_ARM if target is None else target extra = EXTRA_FOR_EXCLUSIONS if extra is None else extra return {a: max(0, target + extra.get(a, 0) - prior.get(a, 0) - dealt.get(a, 0)) for a in arms} def next_arm(session, study=None, dealt=None, prior=None, target=None, extra=None) -> str: """Deal the next condition to a group that has just formed. STRICTLY SEQUENTIAL, at the human's request (2026-09-04): the arms cycle in the order `STUDIES[STUDY]['arms']` lists them, so consecutive groups are always different leader qualities and the arms stay exactly balanced at every multiple of the cycle length. `session.variant_queue` holds what is left of the current cycle -- the same SESSION_FIELD the retired consent-time deal used, now counting GROUPS instead of people. WHAT SEQUENTIAL COSTS. Condition is a deterministic function of the order groups happen to form in, so it correlates with time within a session. That is C9. Shuffling each cycle would break the correlation but could put two groups of the same quality back to back across a cycle boundary, which is exactly what the human asked not to happen; the rotation is the choice. Assignment cannot see the group: the queue is advanced by arrival of a complete foursome, never by anything observed about who is in it. D56 (2026-09-20) ADDS THE STOPPING RULE, and it is a SKIP, not a reordering: an arm that has reached TARGET_GROUPS_PER_ARM is dropped from the queue and the rotation carries on with what is left. So the alternation above holds for exactly as long as both arms are still short, and the run ends with a tail of consecutive groups in whichever arm is behind. That tail is the prereg's own rule ("subsequent groups are assigned to the remaining condition") and is the reason this is a skip rather than "deal whichever arm is furthest behind": the latter would deal the deficit down immediately, putting same-arm groups back to back from the FIRST group of the night, which is the thing D39 chose the strict rotation to avoid. ORDERING vs THE PREREG. The prereg switches arms when one reaches 30; this switches at 33. Both land on 33/33 and both need the same number of groups in each arm from any starting point -- only the interleaving differs. D56. `dealt` is the per-arm count of groups already formed THIS SESSION; the caller supplies it because this module deliberately imports nothing from oTree. `prior`/`target` are overridable so the suites can drive the pure rotation without the live figures moving underneath them. THIS CANNOT STOP COLLECTION. Four people who have consented and finished training are owed the experiment, so once every arm is full the rotation resumes and only warns. Stopping is a human closing the CloudResearch listings, watching the Report tab's progress row (RUNBOOK section 2). """ arms = study_arms(study) if FORCE_VARIANT is not None: if FORCE_VARIANT not in arms: raise ValueError( f"FORCE_VARIANT={FORCE_VARIANT!r} is not an arm of STUDY={STUDY!r} " f"({list(arms)}). Change STUDY, or pick one of those.") print(f"*** FORCE_VARIANT={FORCE_VARIANT} -- every group is in this " f"condition. Debugging only; NOT valid for data collection. ***") return FORCE_VARIANT needed = groups_needed(dealt, study, prior, target, extra) open_arms = [a for a in arms if needed[a] > 0] if not open_arms: # Every arm is at target and people are still arriving. Deal from the # full rotation so the extra groups stay balanced, and say so loudly -- # this print is the night's record, in the Heroku log. _t = TARGET_GROUPS_PER_ARM if target is None else target _x = EXTRA_FOR_EXCLUSIONS if extra is None else extra print(f"[TARGET] every arm of {study or STUDY} has reached its full count " f"({', '.join(f'{a} {_t + _x.get(a, 0)}' for a in arms)}) " f"-- close the CloudResearch listings. Still dealing: {list(arms)}") open_arms = list(arms) # Drop only arms that are FULL, never arms that merely are not arms of this # study: check_variants.py pins a condition by pre-seeding the queue and # drives all four through Experiment_WaitPage, which calls this with the live # STUDY, so a seeded 'no_leader' has to survive a 'good_bad' rotation. full = {a for a in arms if a not in open_arms} queue = [a for a in (session.variant_queue or []) if a not in full] if not queue: queue = list(open_arms) chosen = queue.pop(0) session.variant_queue = queue # reassign: session vars are a JSON blob return chosen def next_arm_preview(dealt=None, study=None, prior=None, target=None, extra=None): """Which arm the NEXT group will be dealt, and which phase the rotation is in. D58, for the admin Report tab. It REPLAYS `next_arm` on a stub session, from the empty queue `training.creating_session` starts every session with, one call per group already formed -- so this is the rotation itself, not a second copy of its rule that could drift. It never touches the real session, whose `variant_queue` is a SESSION_FIELD the report must not read (F50). Returns dict(arm, phase, open_arms), phase being 'alternating' while more than one arm still needs groups, 'single' once only one does (the prereg's "subsequent groups are assigned to the remaining condition"), and 'done'. Returns None if the replay does not reproduce `dealt` -- FORCE_VARIANT, or a queue pre-seeded by a suite -- rather than guess. """ import contextlib, io if FORCE_VARIANT is not None: return None arms = study_arms(study) dealt = {a: (dealt or {}).get(a, 0) for a in arms} class _Stub: variant_queue = [] stub, replayed = _Stub(), {a: 0 for a in arms} with contextlib.redirect_stdout(io.StringIO()): # past target, next_arm prints for _ in range(sum(dealt.values())): replayed[next_arm(stub, study, replayed, prior, target, extra)] += 1 if replayed != dealt: return None arm = next_arm(stub, study, replayed, prior, target, extra) open_arms = [a for a, n in groups_needed(dealt, study, prior, target, extra).items() if n > 0] phase = 'done' if not open_arms else 'single' if len(open_arms) == 1 else 'alternating' return dict(arm=arm, phase=phase, open_arms=open_arms) print(f"[STUDY] {STUDY} -- training profile {training_variant()!r}, " f"groups rotate through {list(study_arms())}") # D56: the one line that says how much of this study is left. Printed at import, # beside the [STUDY] banner, so the server log records what the deployed build # believed had already been collected -- which is the figure a stale # PRIOR_GROUPS would get wrong, and nothing downstream could catch. print(f"[TARGET] {TARGET_GROUPS_PER_ARM} ANALYSABLE groups an arm; collected " + ", ".join(f"{a} {PRIOR_GROUPS.get(a, 0)}" for a in study_arms()) + "; still needed " + ", ".join(f"{a} {n}" for a, n in groups_needed().items()) + " (includes D59 over-collection for groups whose leader never decides: " + ", ".join(f"{a} +{EXTRA_FOR_EXCLUSIONS.get(a, 0)}" for a in study_arms()) + ")")