TreasureHuntForTwo / order_link.py
princessamygdala's picture
Claude Opus 5
Deploy: no em dashes, in the participant copy too
e8598c4
Raw History Blame Contribute Delete
21.9 kB
"""Task-order counterbalancing for the combined SONA study (task_sl-cu-nicewebrl <->
task_pe-cu-nicewebrl).
Only relevant when ?study=sona is set, standalone/lab runs of this task (the child CU-traits
study) never call this and are completely unaffected.
`first_task` is PREDETERMINED and exactly alternating, the same "systematic guarantee, not
just balanced in expectation" this study's other counterbalancing already uses (block order,
chest colour -- see RANDOMIZATION.md): it reads a small shared log
(gitlab_save.assign_task_order, a GitLab project separate from either task's own data repo)
and hands out "sl"/"pe" by arrival position, not by hashing the participant's own code. A
pre-registered table (like pe-cu's own allocation.py, or this task's own orders.py) isn't an
option for the ASSIGNMENT itself: SONA participants bring their own identifier, unknown in
advance. The shared log is that "table," just filled in as people arrive instead of ahead of
time, and it is idempotent -- either task asking about the same participant, in either order,
on a reload, gets the SAME answer back rather than reassigning. It is keyed on the research
PSEUDONYM, never the raw SONA code -- see assign_task_order's own docstring for why a raw code
in that shared, cross-task-readable log would defeat pid pseudonymisation entirely.
If the shared log is unreachable (not configured, network error, an unresolved write race),
`first_task` falls back to `_hash_fallback` -- a local, keyless hash. IMPORTANT: this fallback
must only ever be used by whichever task the participant is CURRENTLY on when there is no
other way to know -- it must NOT be independently re-resolved by both tasks for the same
participant, because the two resolutions can disagree (one task reaches the shared log, the
other doesn't, right when it matters). The task that resolves order FIRST (whichever the
participant actually starts on) carries its answer forward explicitly in the handoff URL
(other_task_url's first= + fsig=, HMAC-signed with the same SONA_PID_HASH_KEY already shared
for pid pseudonymisation) rather than letting the second task re-resolve and potentially
disagree. The second task only falls back to resolving on its own (log-then-hash) if it is
opened WITHOUT that parameter -- e.g. someone opens the second task's link directly.
This file is duplicated (not shared/imported) into task_pe-cu-nicewebrl, with THIS_TASK/
OTHER_TASK swapped and OTHER_TASK_URL_ENV pointing at this task's own HF Space instead,
matching the existing pattern of independently-duplicated conventions across these two sibling
repos (gitlab_save.py, the *_id_for()-style helpers, etc.), rather than a shared package.
"""
import hashlib
import hmac
import logging
import os
import zlib
from urllib.parse import quote
logger = logging.getLogger(__name__)
THIS_TASK = "sl"
OTHER_TASK = "pe"
#: The other task's base URL (its HF Space), e.g. https://princessamygdala-harvestfortwo.hf.space
#: Set as an env var / HF Space secret, matching how GITLAB_TOKEN etc. are configured.
OTHER_TASK_URL_ENV = "OTHER_TASK_BASE_URL"
#: Where each app serves its own partner avatars, as plain unsigned static images -- the
#: deferred end-of-study belief/liking screen names every partner across both tasks and
#: neither app can draw the other's (an explorer redrawn as a farmer is a different-looking
#: person from the one the participant actually met), so each app serves pictures of its own
#: partners and the screen asking about the OTHER task's partner links to that app's copy of
#: this path instead. `idx` is that app's own palette index (this task's:
#: orders.partner_avatar_for's first return value). Agreed with task_pe-cu-nicewebrl; same
#: format string, duplicated here like everything else in this file.
PARTNER_FACE_PATH = "/static/partner_face_{idx}.png"
#: Same secret used for pid pseudonymisation (web_app._pid_pseudonym) -- reused here to sign
#: the handoff's first= parameter, not because pid secrecy and handoff integrity are the same
#: property, but because it's already the one secret both tasks are guaranteed to share.
_SIGN_KEY_ENV = "SONA_PID_HASH_KEY"
def _hash_fallback(survey_code):
"""Only-approximately-balanced fallback for when the shared allocation log (see module
docstring) isn't configured or isn't reachable. Deliberately keyless/public: it only needs
both tasks to agree on a value, not to resist prediction, and the result is never
persisted."""
n = zlib.crc32(f"task_order|{survey_code}".encode()) % 2
return "sl" if n == 0 else "pe"
def first_task(survey_code, pseudonym):
"""(value, source) -- "sl"/"pe", and "shared_log" or "hash" saying how it was
resolved (record BOTH in the session's own saved data -- see web_app.py -- so an
imbalanced fallback is visible in the data itself rather than something that has to be
reconstructed later). Blocking (does network I/O via the shared allocation log); call via
asyncio.to_thread from async code, and cache the result for the rest of the session rather
than calling this more than once per participant.
Only call this on the task the participant is CURRENTLY visiting when there is no
authoritative answer already available (see verify_signed_first) -- see module docstring
for why re-resolving independently on both tasks is unsafe.
Two DIFFERENT identifiers, used for two DIFFERENT things, and neither is optional:
`pseudonym` -- the already-computed research pseudonym (web_app._pid_pseudonym's
"research" salt) -- is what's sent to the SHARED LOG (gitlab_save.assign_task_order)
as its row key. The raw SONA code must never reach that file: a persisted plaintext
code, combined with SONA_PID_HASH_KEY, would let anyone holding both re-identify every
participant's research data, defeating the whole point of pseudonymising it in the
first place. Callers must compute this BEFORE calling first_task (web_app.py's index()
already does, earlier in the same request).
`survey_code` -- the RAW code -- feeds ONLY the local hash fallback (_hash_fallback),
used when the shared log is unreachable. This one is NOT persisted anywhere by this
function, so there is no privacy gain in pseudonymising it too -- but it MUST be the
SAME raw value both tasks independently derive from the participant's own SONA code,
or the two tasks' fallback hashes can disagree about who's first (see module
docstring). Do not pass the pseudonym here "for consistency" -- that would only add a
second thing that has to match between the two apps for no benefit.
"""
import gitlab_save
assigned = gitlab_save.assign_task_order(pseudonym)
if assigned in ("sl", "pe"):
return assigned, "shared_log"
logger.warning(
f"shared task-order log unavailable for pseudonym={pseudonym!r} -- falling back "
"to a local hash (only approximately balanced, not exactly alternating). Set "
"SONA_GITLAB_PROJECT (+ SONA_GITLAB_TOKEN or GITLAB_TOKEN) to fix.")
return _hash_fallback(survey_code), "hash"
def am_i_first(survey_code, pseudonym):
value, _source = first_task(survey_code, pseudonym)
return value == THIS_TASK
def _sign(survey_code, value):
key = os.getenv(_SIGN_KEY_ENV, "").strip()
if not key:
return ""
return hmac.new(key.encode(), f"order|{survey_code}|{value}".encode(),
hashlib.sha256).hexdigest()[:8]
def verify_signed_first(survey_code, value, sig):
"""True if `value` ("sl"/"pe") is a genuine, untampered handoff from the other task for
this survey_code -- i.e. the SAME secret both tasks share (SONA_PID_HASH_KEY) produces the
same signature. Returns False (never raises) for a missing/wrong signature, a missing key,
or a value that isn't "sl"/"pe"; callers should fall back to first_task() in that case."""
if value not in ("sl", "pe") or not sig:
return False
expected = _sign(survey_code, value)
return bool(expected) and hmac.compare_digest(expected, sig)
def verify_signed_bonus(survey_code, amount_str, sig):
"""True if `amount_str` (a dollar figure as a string, e.g. "6.00") is a genuine bonus1=
handoff from the FIRST task for this survey_code -- same HMAC construction as
verify_signed_first, reusing _sign with a "bonus:"-prefixed value so the two signature
namespaces (task labels vs. dollar amounts) can never collide. Returns False (never raises)
for a missing amount/signature, an unparseable amount, or a missing key; callers then simply
have no other-task bonus to add to this participant's total.
"""
if not sig or not amount_str:
return False
try:
amount = float(amount_str)
except (TypeError, ValueError):
return False
expected = _sign(survey_code, f"bonus:{amount:.2f}")
return bool(expected) and hmac.compare_digest(expected, sig)
def verify_signed_partners(survey_code, pbonus_str, plost_str, sig):
"""(earned, lost) in dollars for the FIRST task's partner(s), if `sig` is a genuine
pbonus1=/plost1= handoff for this survey_code, else (None, None). Never raises.
bonus1=/bsig= already carries the participant's OWN first-task bonus; this is the separate
figure for what their PARTNER(S) in that task received, which the participant never sees
directly (their own final screen there is skipped entirely under a verified handoff) but
the task they finish on should still be able to report. One shared construction
("partners:<earned>:<lost>") across both earned and lost, rather than two separate sigs,
because a task whose mechanic has no distinct loss side (this one) always sends lost=0.00
and a single signature is simpler to verify than two. Agreed with task_pe-cu-nicewebrl,
whose own mechanic DOES have a one-sided loss (their night harvest only ever takes away),
hence carrying both.
"""
if not sig or pbonus_str is None or plost_str is None:
return None, None
try:
earned, lost = float(pbonus_str), float(plost_str)
except (TypeError, ValueError):
return None, None
expected = _sign(survey_code, f"partners:{earned:.2f}:{lost:.2f}")
if not expected or not hmac.compare_digest(expected, sig):
return None, None
return earned, lost
#: Characters allowed in a partner row's id -- kept to the shape both tasks' cover stories
#: actually use, and truncated, signature or no signature: a value that gets RENDERED on a
#: screen is checked before it is rendered, not just HMAC-verified. Byte-identical set to
#: task_pe-cu-nicewebrl's copy.
_ROW_ID_OK = set("abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_, ")
def encode_partner_rows(rows):
""""<id>:<earned>:<lost>:<kind>:<avatar>|..." for the handoff.
One entry per PERSON, not one total, so the task that finishes second can name each
partner across both tasks and say what that person walked away with -- a total cannot say
what any one of them ended up with, which is what the participant actually decided. Order
is the order the participant met them.
`kind` is a short slug (no ":" or "|", since those are the delimiters) saying what kind of
partner this is, because the belief-check wording depends on it: a partner you earned for
is asked whether they'd really RECEIVE it, a partner who only loses (task_pe-cu-nicewebrl's
night harvest) is asked whether they'd really LOSE it. This task's own kind is "hunt".
`avatar` is this app's own palette index for the person (orders.partner_avatar_for's first
return value), or "-" when there isn't one -- see PARTNER_FACE_PATH. The receiving task
uses it to build a URL to THIS app's own hosted picture of them, never to draw the person
itself (it has no art for this app's avatars).
"""
out = []
for r in rows or []:
rid = "".join(c for c in str(r.get("id", ""))[:40] if c in _ROW_ID_OK)
kind = str(r.get("kind", "")).replace(":", "").replace("|", "")[:16]
avatar = r.get("avatar")
avatar_s = str(int(avatar)) if avatar is not None else "-"
out.append(f"{rid}:{float(r.get('earned', 0)):.2f}:{float(r.get('lost', 0)):.2f}:"
f"{kind}:{avatar_s}")
return "|".join(out)
def partner_list_signature(survey_code, rows_str):
return _sign(survey_code, f"partnerlist:{rows_str}")
def verify_partner_rows(survey_code, rows_str, signature):
"""[{"id", "earned", "lost", "kind", "avatar"}] for a genuine encode_partner_rows string,
else [].
Never raises: a missing, unsigned or malformed list means the other task said nothing
about its partners (or is running a version that only sends the pbonus1=/plost1= totals),
and the screen then names only the partners it already knows about.
Accepts the 3-field format (no `kind`/`avatar`, from before either field existed), the
4-field one (`kind`, no `avatar`), and the current 5-field one, so neither side breaks
depending on which deploys first. A missing `kind` reads as "" -- the belief-check wording
then falls back to earned/lost amounts to guess the right phrasing (see
questionnaires._belief_verb). A missing/non-numeric `avatar` is None -- the picture is then
left out rather than built from a guess (see PARTNER_FACE_PATH).
"""
if not rows_str or not signature:
return []
expected = partner_list_signature(survey_code, rows_str)
if not expected or not hmac.compare_digest(expected, str(signature)):
return []
out = []
for part in str(rows_str).split("|"):
bits = part.split(":")
if len(bits) == 3:
bits = bits + [""]
if len(bits) == 4:
bits = bits + ["-"]
if len(bits) != 5:
return []
rid = "".join(c for c in bits[0][:40] if c in _ROW_ID_OK)
kind = bits[3][:16]
avatar = int(bits[4]) if bits[4].isdigit() else None
try:
out.append({"id": rid, "earned": float(bits[1]), "lost": float(bits[2]),
"kind": kind, "avatar": avatar})
except ValueError:
return []
return out
def signed_reference_code(pseudonym, amount_usd):
"""A compact, copy-pasteable, tamper-evident code for the participant's final screen: their
research pseudonym plus the combined bonus total they were just shown, HMAC-signed together
(SONA_PID_HASH_KEY, same shared secret as everything else here) so an RA can read the dollar
amount straight off a reported code without any lookup, and a participant cannot inflate it
by editing the digits before reporting it back -- changing either the pseudonym or the
amount invalidates the signature (see verify_reference_code).
Format: "<pseudonym>-<cents>-<sig>", e.g. "a1b2c3d4e5f67890-00850-9f3a2b1c" for $8.50.
Amount is baked in as integer cents, zero-padded to 5 digits (good up to $999.99, far above
the $12 cap) rather than a decimal string, so there is exactly one way to write a given
amount -- no "8.5" vs "8.50" ambiguity for the signature to trip over.
Returns "" if SONA_PID_HASH_KEY isn't set -- callers should fall back to showing the bare
pseudonym in that case (see web_app.py), same as every other signed value in this module.
"""
cents = round(amount_usd * 100)
sig = _sign(pseudonym, f"refcode:{cents}")
if not sig:
return ""
return f"{pseudonym}-{cents:05d}-{sig}"
def verify_reference_code(code):
"""(pseudonym, amount_usd) if `code` is a genuine, untampered signed_reference_code output,
else (None, None). Never raises. Not needed for the normal payment workflow -- the amount
is already baked into the signature, so an RA can just read it off -- but useful if a
reported code ever looks suspicious and someone wants to double-check it by hand or script.
"""
try:
pseudonym, cents_s, sig = code.strip().split("-")
cents = int(cents_s)
except (ValueError, AttributeError):
return None, None
expected = _sign(pseudonym, f"refcode:{cents}")
if not expected or not hmac.compare_digest(expected, sig):
return None, None
return pseudonym, cents / 100.0
def other_task_url(survey_code, sona_url, first_task_value, own_bonus_usd=None,
partner_bonus_usd=None, partner_lost_usd=0.0, partner_rows=None,
dev=False, dev_trials=None):
"""Where to send the participant next: the other task, carrying their SONA code, the
eventual SONA return URL (if known), and the ALREADY-RESOLVED task order, signed so the
other task can trust it instead of re-resolving (see module docstring for why re-resolving
independently is unsafe). "" if OTHER_TASK_URL_ENV isn't configured -- callers treat that
as "no next task".
`first_task_value` must be the value THIS task already resolved for this participant (its
own app.storage.user["task_first"]), not re-derived here.
`own_bonus_usd`, when given, is THIS task's already-computed, already-capped dollar bonus
for this participant (not their partner's), signed the same way as first_task_value and
carried as bonus1=/bsig= -- so whichever task the participant finishes on SECOND can add it
to its own bonus for one combined total, without re-deriving or trusting an unsigned figure
from the URL. Only meaningful when this call is made by the task that ran FIRST; omit it
(default None) when calling from the second task, which has nothing further to hand off.
`partner_bonus_usd`, when given (only meaningful from the task that ran FIRST, same as
own_bonus_usd), is the dollar total THIS task's own partner received -- never shown on this
task's own final screen, since a verified handoff skips straight past it, so the task the
participant finishes on needs it to report what every partner across both tasks ended up
with. `partner_lost_usd` defaults to 0.00: this task's mechanic has no one-sided loss (a
chest can help or hurt the partner, there's no separate "partner lost" category the way
task_pe-cu-nicewebrl's night harvest has), so it always sends zero rather than omitting the
field -- the receiving side still verifies both together (see verify_signed_partners).
`partner_rows`, when given, is [{"id", "earned", "lost"}, ...] -- the same thing person by
person, carried alongside the totals rather than instead of them: either app may be
running a version that only knows the totals, and then that is what its last screen shows.
Agreed with task_pe-cu-nicewebrl after their user asked for each partner named
individually, not just a combined figure -- a total cannot say what any one person ended
up with.
`dev` and `dev_trials` carry a debug run across the handoff. Without them a shortened
session hands over to a full-length one, so walking the combined study end to end meant
playing the second task's whole block or opening it by hand and never testing the handoff
itself. Both tasks read ?dev=1 and ?trials=N, so this works in the direction the other app
sends too, now that its copy of this file does the same (ported from task_pe-cu-nicewebrl).
"""
base = os.getenv(OTHER_TASK_URL_ENV, "").strip().rstrip("/")
if not base:
return ""
q = f"?pid={quote(str(survey_code), safe='')}&study=sona"
if sona_url:
q += f"&sona={quote(sona_url, safe='')}"
if first_task_value in ("sl", "pe"):
sig = _sign(survey_code, first_task_value)
if sig:
q += f"&first={first_task_value}&fsig={sig}"
if own_bonus_usd is not None:
bsig = _sign(survey_code, f"bonus:{own_bonus_usd:.2f}")
if bsig:
q += f"&bonus1={own_bonus_usd:.2f}&bsig={bsig}"
if partner_bonus_usd is not None:
lost = partner_lost_usd or 0.0
psig = _sign(survey_code, f"partners:{partner_bonus_usd:.2f}:{lost:.2f}")
if psig:
q += f"&pbonus1={partner_bonus_usd:.2f}&plost1={lost:.2f}&psig={psig}"
if partner_rows:
rows_str = encode_partner_rows(partner_rows)
ppsig = partner_list_signature(survey_code, rows_str)
if rows_str and ppsig:
q += f"&pparts1={quote(rows_str, safe='')}&ppsig={ppsig}"
if dev:
q += "&dev=1"
if dev_trials:
q += f"&trials={int(dev_trials)}"
return base + q
if __name__ == "__main__":
import sys
logging.basicConfig(level=logging.INFO)
os.environ.setdefault(_SIGN_KEY_ENV, "local-selftest-key-not-for-prod")
for code in sys.argv[1:] or ["SONA0001", "SONA0002", "SONA0003", "SONA0004"]:
# Stand-in pseudonym for this self-test only -- real callers use web_app._pid_pseudonym.
pseudonym = hashlib.sha256(f"research|{code}".encode()).hexdigest()[:16]
value, source = first_task(code, pseudonym)
sig = _sign(code, value)
ok = verify_signed_first(code, value, sig)
tampered_ok = verify_signed_first(code, "pe" if value == "sl" else "sl", sig)
bsig = _sign(code, "bonus:6.00")
bonus_ok = verify_signed_bonus(code, "6.00", bsig)
bonus_tampered_ok = verify_signed_bonus(code, "12.00", bsig)
print(f" {code}: first={value} ({source}) am_i_first={value == THIS_TASK} "
f"sig={sig} verify_genuine={ok} verify_tampered={tampered_ok} (must be False) "
f"bonus_verify_genuine={bonus_ok} bonus_verify_tampered={bonus_tampered_ok} (must be False) "
f"next_url={other_task_url(code, 'https://sona.example/credit?survey_code=%SURVEY_CODE%', value, own_bonus_usd=6.0) or '(OTHER_TASK_BASE_URL not set)'}")