TreasureHuntForTwo / gitlab_save.py
princessamygdala's picture
Claude Opus 5
Deploy: record the quiz and questionnaire screens, and fix the dyad log row
a081612
Raw History Blame Contribute Delete
24.3 kB
"""
Push a participant's data files to a GitLab repo via the API.
Configured by environment variables (set locally in .env or as Hugging Face Space secrets):
GITLAB_TOKEN -- a project/personal access token with `write_repository` (or `api`) scope
GITLAB_PROJECT -- the repo path, e.g. "princessamygdala/task_sl-cu-data"
GITLAB_URL -- default "https://gitlab.com"
GITLAB_BRANCH -- default "master"
If GITLAB_TOKEN / GITLAB_PROJECT are unset, push_to_gitlab() is a no-op (returns False),
so local-only runs keep working.
Combined-SONA-study only, separate from the above (assign_task_order, submit_payment): a THIRD
project, shared with task_pe-cu-nicewebrl, for study-level state that belongs to neither task's
own data repo:
SONA_GITLAB_PROJECT -- required for assign_task_order/submit_payment; no fallback (must name
the shared project explicitly)
SONA_GITLAB_TOKEN -- falls back to GITLAB_TOKEN if unset (one token can cover several
projects)
SONA_GITLAB_URL -- falls back to GITLAB_URL
SONA_GITLAB_BRANCH -- falls back to GITLAB_BRANCH's default-branch lookup
"""
import base64
import csv
import io
import os
from urllib.parse import quote
try:
import requests
except Exception: # pragma: no cover
requests = None
#: Where the data repo actually is. This defaulted to gitlab.pavlovia.org, inherited from
#: the task this was forked from, and this project has never been on Pavlovia. With
#: GITLAB_URL unset, every push authenticated a gitlab.com token against Pavlovia, was
#: refused, and returned False -- which nothing looked at (see _loud below). A Space with
#: its token and project both set, reporting healthy, saving nothing, on a filesystem that
#: does not survive a restart.
GITLAB_URL_DEFAULT = "https://gitlab.com"
def _loud(msg):
"""Report to the app log if there is one, and to stdout regardless, which is what a
HuggingFace Space's logs capture."""
print(f"[gitlab] {msg}", flush=True)
try:
import logging
logging.getLogger("main").warning(f"[gitlab] {msg}")
except Exception:
pass
def _env():
return (os.getenv("GITLAB_TOKEN", "").strip(),
os.getenv("GITLAB_PROJECT", "").strip(),
os.getenv("GITLAB_URL", GITLAB_URL_DEFAULT).strip().rstrip("/"),
(os.getenv("GITLAB_BRANCH", "") or "").strip())
def _sona_env():
"""A SEPARATE GitLab project (SONA_GITLAB_*), shared with task_pe-cu-nicewebrl, for
combined-study-level state that belongs to neither task's own data repo -- the task-order
allocation log (assign_task_order) and the payment queue (submit_payment). Falls back to
GITLAB_URL/GITLAB_TOKEN if SONA_GITLAB_TOKEN/URL aren't set (same token, different project),
since a single access
token often covers several projects; SONA_GITLAB_PROJECT has no such fallback -- it must
name the shared project explicitly, or the functions below no-op."""
token = os.getenv("SONA_GITLAB_TOKEN", "").strip() or os.getenv("GITLAB_TOKEN", "").strip()
project = os.getenv("SONA_GITLAB_PROJECT", "").strip()
base = (os.getenv("SONA_GITLAB_URL", "").strip()
or os.getenv("GITLAB_URL", GITLAB_URL_DEFAULT)).strip().rstrip("/")
branch = (os.getenv("SONA_GITLAB_BRANCH", "") or "").strip()
return token, project, base, branch
def _get_raw(base, pid, token, branch, path):
try:
r = requests.get(
f"{base}/api/v4/projects/{pid}/repository/files/{quote(path, safe='')}/raw",
params={"ref": branch}, headers={"PRIVATE-TOKEN": token}, timeout=20)
return r.text if r.status_code < 400 else None
except Exception:
return None
#: Columns that identify a row, per log file. A BEAR dyad shares one pid on purpose, so
#: pid alone names a FAMILY there, not a person, and upserting on it lets whoever saves
#: second delete the other's row. Role splits the family into its two players.
LOG_KEYS = {"bear_randomization_log.csv": ("pid", "role")}
#: Columns a later save may never lower. A session that is reopened and abandoned saves
#: houses_done 0, and without this it would overwrite the finished run with a zero. Seen
#: on 2026-11-03: a second tab on one BEAR link replaced a complete 12-house row.
MONOTONIC = ("houses_done", "completed")
def append_to_log(row, path="randomization_log.csv", key=None):
"""Upsert one participant row in a growing CSV in the repo (read-modify-write).
One row per participant: a new one is appended, an existing one is UPDATED in place so
the latest progress is reflected. Skips the commit when nothing changed.
`key` is the columns that identify a participant, defaulting to LOG_KEYS[path] and
then to ("pid",). Progress columns in MONOTONIC only ever go up, so reopening a
finished session cannot erase it.
"""
key = tuple(key or LOG_KEYS.get(path, ("pid",)))
token, project, base, branch = _env()
if not token or not project or requests is None:
_loud("missing GITLAB_TOKEN / GITLAB_PROJECT (or requests) -> NOT LOGGING")
return False
pid_id = quote(project, safe="")
branch = branch or _default_branch(base, pid_id, token) or "main"
existing = _get_raw(base, pid_id, token, branch, path)
if existing:
rdr = list(csv.DictReader(io.StringIO(existing)))
cols = list(rdr[0].keys()) if rdr else []
for k in row: # add any new columns, preserving order
if k not in cols:
cols.append(k)
def _same(r):
return all(str(r.get(k, "")) == str(row.get(k, "")) for k in key)
idx = next((i for i, r in enumerate(rdr) if _same(r)), None)
if idx is not None: # update this participant's row in place
merged = {**rdr[idx], **row}
for k in MONOTONIC: # progress never goes backwards
if k in rdr[idx] and k in row:
try:
merged[k] = max(int(rdr[idx][k] or 0), int(row[k] or 0))
except (TypeError, ValueError):
pass
if all(str(rdr[idx].get(k, "")) == str(merged.get(k, "")) for k in cols):
return True # nothing changed -> no commit needed
rdr[idx] = merged
else:
rdr.append(row)
rows = rdr
action = "update"
else:
cols = list(row.keys())
rows = [row]
action = "create"
buf = io.StringIO()
w = csv.DictWriter(buf, fieldnames=cols)
w.writeheader()
for r in rows:
w.writerow({k: r.get(k, "") for k in cols})
content = base64.b64encode(buf.getvalue().encode()).decode("ascii")
r = _commit(base, pid_id, token, branch, "randomization log",
[{"action": action, "file_path": path, "content": content, "encoding": "base64"}])
ok = r.status_code < 400
if not ok:
# Loud whether or not the caller checks: web_app.py's finish_experiment() calls
# append_to_log and discards the return value entirely, so a silent False was the
# only trace this row was never written.
_loud(f"append_to_log FAILED: host={base.split('//')[-1].split('/')[0]} "
f"project={project} branch={branch} status={r.status_code} {r.text[:200]}")
return ok
def _file_exists(base, pid, token, branch, path):
"""Is `path` already in the repo on `branch`?
HEAD, not GET: the answer needed here is one bit, not the file's content.
None means the question could not be asked (a network error), which the
caller treats as "unknown" and resolves by trying both verbs.
"""
try:
r = requests.head(
f"{base}/api/v4/projects/{pid}/repository/files/{quote(path, safe='')}",
params={"ref": branch}, headers={"PRIVATE-TOKEN": token}, timeout=15)
if r.status_code == 404:
return False
if r.status_code < 400:
return True
return None
except Exception:
return None
def _commit(base, pid, token, branch, message, actions):
url = f"{base}/api/v4/projects/{pid}/repository/commits"
return requests.post(
url, headers={"PRIVATE-TOKEN": token},
json={"branch": branch, "commit_message": message, "actions": actions},
timeout=30,
)
_ORDER_COLS = ["survey_code", "first_task", "assigned_utc"]
_ORDER_MAX_RETRIES = 5
def _get_file_meta(base, pid, token, branch, path):
"""The file's content + last_commit_id (for compare-and-swap), or (None, None) if it
doesn't exist yet. Unlike _get_raw, this hits the (non-/raw) file-metadata endpoint, which
is the only one that returns last_commit_id."""
try:
r = requests.get(
f"{base}/api/v4/projects/{pid}/repository/files/{quote(path, safe='')}",
params={"ref": branch}, headers={"PRIVATE-TOKEN": token}, timeout=20)
if r.status_code >= 400:
return None, None
j = r.json()
content = base64.b64decode(j["content"]).decode("utf-8")
return content, j.get("last_commit_id")
except Exception:
return None, None
def assign_task_order(pseudonym, path="task_order_log.csv"):
"""Predetermined, exactly-alternating task-order assignment for the combined SONA study,
shared with task_pe-cu-nicewebrl via SONA_GITLAB_* (a project separate from either task's
own data repo -- see _sona_env). NOT a hash of the participant's code: SONA codes are
assigned by SONA, not by us, so a hash of one only balances order in expectation, the same
gap that motivated this study's other counterbalancing fixes (block order, chest colour --
see RANDOMIZATION.md). This reads a shared log and alternates by arrival position instead,
which is exact for any completed prefix, not just in the limit.
`pseudonym` MUST be the already-computed research pseudonym (web_app._pid_pseudonym's
"research" salt), never the raw SONA code -- this value is what actually gets WRITTEN and
PERSISTED as the log's row key (unlike order_link.first_task's hash-fallback input, which
is never written anywhere). A raw code here would sit in this shared, cross-task-readable
log in plaintext indefinitely; combined with SONA_PID_HASH_KEY, that would let anyone
holding both re-identify every participant's research data, which is exactly what
pseudonymising that data was for. (This function itself has no way to tell a raw code from
a pseudonym -- both are just strings -- so this is a caller discipline requirement, not
something checkable here; see order_link.first_task's docstring, which is the one caller.)
Idempotent: a pseudonym already in the log returns its existing assignment rather than
reassigning, whichever task asks (this task or the other one, on a reload, in either
order). Returns "sl" or "pe", or None if the shared project isn't configured/reachable, OR
if a genuine write race couldn't be resolved within _ORDER_MAX_RETRIES -- callers fall back
to a local hash (order_link._hash_fallback), which keeps the flow working but is no longer
exactly alternating; logged loudly so real imbalance can be caught by hand. None is
preferred over a silently-wrong guess: "systematic guarantee" and "best effort under a
write race" cannot both be true of the same returned value.
Blocking (does network I/O) -- call via asyncio.to_thread from async code, exactly like
push_to_gitlab/append_to_log elsewhere in this module.
Race-safe via GitLab's per-file compare-and-swap (last_commit_id on PUT, and POST's
create-only semantics for the very first write): two participants landing in the same
read-modify-write window will have ONE of their writes rejected (the file changed since
they read it, or already existed when they tried to create it) rather than one silently
overwriting the other -- unlike append_to_log's bulk-commit approach, which has no such
check. The loser re-reads (picking up whatever the winner wrote, which may already be
their own pseudonym if the winner was resolving the SAME participant) and retries, up to
_ORDER_MAX_RETRIES times.
"""
token, project, base, branch = _sona_env()
if not token or not project or requests is None:
return None
pid = quote(project, safe="")
branch = branch or _default_branch(base, pid, token) or "main"
# Column name "survey_code" is unchanged (kept for the shared file's existing schema, read
# by both tasks) even though the VALUE stored under it is now the pseudonym -- renaming the
# column would need a simultaneous, coordinated change on task_pe-cu-nicewebrl's side too
# (their own DictReader/DictWriter expect this exact header), which is a bigger, separately-
# decided change than the security fix this function makes.
def _lookup(text):
rows = list(csv.DictReader(io.StringIO(text))) if text else []
for r in rows:
if str(r.get("survey_code")) == str(pseudonym):
return rows, r.get("first_task")
return rows, None
def _serialize(rows):
buf = io.StringIO()
w = csv.DictWriter(buf, fieldnames=_ORDER_COLS)
w.writeheader()
for r in rows:
w.writerow({k: r.get(k, "") for k in _ORDER_COLS})
return base64.b64encode(buf.getvalue().encode()).decode("ascii")
for _attempt in range(_ORDER_MAX_RETRIES):
text, last_commit_id = _get_file_meta(base, pid, token, branch, path)
rows, found = _lookup(text)
if found in ("sl", "pe"):
return found
next_first = "sl" if len(rows) % 2 == 0 else "pe"
rows.append({"survey_code": str(pseudonym), "first_task": next_first,
"assigned_utc": _now_iso()})
content = _serialize(rows)
# encoding=base64 is required: without it GitLab's single-file API defaults to "text"
# and stores our base64 STRING literally as the file's content, rather than decoding
# it -- the file then contains base64-encoded gibberish instead of the CSV.
body = {"branch": branch, "content": content, "encoding": "base64",
"commit_message": f"task-order assignment: {pseudonym}"}
url = f"{base}/api/v4/projects/{pid}/repository/files/{quote(path, safe='')}"
if text is None:
# first-ever write: POST is create-only and fails if the file now exists (someone
# else created it since our read a moment ago), which is exactly the check we want.
r = requests.post(url, headers={"PRIVATE-TOKEN": token}, json=body, timeout=30)
else:
# last_commit_id makes this a compare-and-swap: GitLab rejects the update if the
# file's actual last commit no longer matches what we read.
body["last_commit_id"] = last_commit_id
r = requests.put(url, headers={"PRIVATE-TOKEN": token}, json=body, timeout=30)
if r.status_code < 400:
return next_first
# lost the race -- someone else (this task or the other one) wrote in between; loop
# back and re-read, which will either find OUR pseudonym already assigned (the winner
# was resolving the same participant) or a higher row count to alternate from.
return None
_PAYMENT_COLS = ["payment_code", "email", "method", "amount_owed_usd", "status", "submitted_utc"]
_PAYMENT_MAX_RETRIES = 5
def submit_payment(payment_code, email, method, amount_usd, path="payment_log.csv"):
"""Record one participant's real-money bonus payment details in the shared bear-sona
project (SONA_GITLAB_* -- see _sona_env), in a store completely separate from either task's
own research-data repo.
`payment_code` must be a SEPARATE one-way pseudonym of the raw SONA code from the one used
for research records (see web_app._pid_pseudonym's "payment" salt / SONA_PAYMENT_HASH_KEY,
a DIFFERENT secret from SONA_PID_HASH_KEY) -- so nobody holding only the research pid key
can look up a participant's email/payment info, and nobody holding only the payment key can
look up their research responses.
Idempotent by payment_code: a participant who reaches this screen twice (e.g. a reload
right after submitting, before payment_submitted was recorded client-side) UPDATES their
existing row instead of creating a duplicate. An existing non-empty `status` is preserved
across an update rather than reset to "pending" -- this function only ever sets "pending"
for a brand-new row; a human updates it to "paid" by hand once actually disbursed (see
module docstring: this is a payment QUEUE, not a payment execution mechanism -- nothing here
ever moves real money).
Race-safe via the same GitLab compare-and-swap pattern as assign_task_order (two
participants submitting close together must not silently clobber one another). Returns
True/False; never raises.
"""
token, project, base, branch = _sona_env()
if not token or not project or requests is None:
_loud("missing SONA_GITLAB_* (or requests) -> payment NOT LOGGED")
return False
pid = quote(project, safe="")
branch = branch or _default_branch(base, pid, token) or "main"
def _serialize(rows):
buf = io.StringIO()
w = csv.DictWriter(buf, fieldnames=_PAYMENT_COLS)
w.writeheader()
for r in rows:
w.writerow({k: r.get(k, "") for k in _PAYMENT_COLS})
return base64.b64encode(buf.getvalue().encode()).decode("ascii")
for _attempt in range(_PAYMENT_MAX_RETRIES):
text, last_commit_id = _get_file_meta(base, pid, token, branch, path)
rows = list(csv.DictReader(io.StringIO(text))) if text else []
idx = next((i for i, r in enumerate(rows)
if str(r.get("payment_code")) == str(payment_code)), None)
row = {"payment_code": str(payment_code), "email": email, "method": method,
"amount_owed_usd": f"{amount_usd:.2f}",
"status": (rows[idx].get("status") if idx is not None and rows[idx].get("status")
else "pending"),
"submitted_utc": _now_iso()}
if idx is not None:
rows[idx] = row
else:
rows.append(row)
content = _serialize(rows)
body = {"branch": branch, "content": content, "encoding": "base64",
"commit_message": f"payment submission: {payment_code}"}
url = f"{base}/api/v4/projects/{pid}/repository/files/{quote(path, safe='')}"
if text is None:
r = requests.post(url, headers={"PRIVATE-TOKEN": token}, json=body, timeout=30)
else:
body["last_commit_id"] = last_commit_id
r = requests.put(url, headers={"PRIVATE-TOKEN": token}, json=body, timeout=30)
if r.status_code < 400:
return True
# lost the race -- someone else wrote in between; loop back, re-read, retry.
_loud(f"submit_payment FAILED after retries: host={base.split('//')[-1].split('/')[0]} "
f"project={project} branch={branch}")
return False
def _now_iso():
from datetime import datetime, timezone
return datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S")
def _default_branch(base, pid, token):
"""Ask GitLab what the repo's default branch is (so master/main 'just works')."""
try:
r = requests.get(f"{base}/api/v4/projects/{pid}",
headers={"PRIVATE-TOKEN": token}, timeout=15)
if r.status_code < 400:
return r.json().get("default_branch")
except Exception:
pass
return None
def _commit_one_by_one(base, pid, token, branch, msg, actions, verbose=False):
"""Commit each action on its own, create then update, and report whether
every one of them landed.
The fallback for a combined commit that was refused: a participant's data
file is worth more than the tidiness of one commit, and a single path the
server will not take must not take the rest down with it.
"""
all_ok = True
for a in actions:
r = _commit(base, pid, token, branch, msg, [a])
if r.status_code >= 400:
flipped = dict(a, action=("create" if a["action"] == "update" else "update"))
r = _commit(base, pid, token, branch, msg, [flipped])
if r.status_code >= 400:
all_ok = False
_loud(f"push FAILED for {a['file_path']}: status={r.status_code} {r.text[:200]}")
elif verbose:
print(f"[gitlab] {a['file_path']} status={r.status_code}")
return all_ok
def push_to_gitlab(file_paths, subdir="data", verbose=False):
"""Commit the given local files into <repo>/<subdir>/. Returns True on success."""
# .strip() guards against trailing newlines/spaces pasted into env vars or
# HF Space secrets (a newline in a token makes the HTTP header invalid).
token = os.getenv("GITLAB_TOKEN", "").strip()
project = os.getenv("GITLAB_PROJECT", "").strip()
base = os.getenv("GITLAB_URL", GITLAB_URL_DEFAULT).strip().rstrip("/")
if not token or not project or requests is None:
_loud("missing GITLAB_TOKEN / GITLAB_PROJECT (or requests) -> NOT SAVING")
return False
pid = quote(project, safe="")
branch = (os.getenv("GITLAB_BRANCH", "") or "").strip() or _default_branch(base, pid, token) or "master"
actions = []
for fp in file_paths:
if not os.path.exists(fp):
continue
with open(fp, "rb") as fh:
content = base64.b64encode(fh.read()).decode("ascii")
dest_path = f"{subdir}/{os.path.basename(fp)}"
# A session pushes its msgpack and CSV every couple of minutes, so by
# the end those two already exist in the repo; the metadata JSON,
# written once at the end, does not. A commit is atomic, so one
# "create" list is refused for the two that exist and one "update"
# list for the one that doesn't -- which silently dropped the final
# push of every session (the only one carrying the post-task
# questionnaires). Checking each file's own state picks the right
# verb per file instead of guessing one verb for all of them.
exists = _file_exists(base, pid, token, branch, dest_path)
actions.append({
"action": "update" if exists else "create",
"file_path": dest_path,
"content": content,
"encoding": "base64",
})
if not actions:
return False
msg = f"data: {subdir}"
r = _commit(base, pid, token, branch, msg, actions)
if r.status_code >= 400:
# The existence check and the commit disagree -- flip every verb and
# try once more, then fall back to one commit per file so a single
# unwritable path cannot discard the rest.
flipped = [dict(a, action=("create" if a["action"] == "update" else "update"))
for a in actions]
r = _commit(base, pid, token, branch, msg, flipped)
if r.status_code >= 400 and len(actions) > 1:
ok = _commit_one_by_one(base, pid, token, branch, msg, actions, verbose)
if not ok:
_loud(f"push_to_gitlab: one or more files FAILED even per-file: "
f"host={base.split('//')[-1].split('/')[0]} project={project} "
f"branch={branch}")
return ok
ok = r.status_code < 400
if verbose:
print(f"[gitlab] branch={branch} status={r.status_code} {r.text[:300]}")
if not ok:
# Loud whether or not the caller asked. web_app.py's finish_experiment() calls
# this without verbose and only logs a bare "skipped/failed" -- no host, no status,
# no reason -- so a wrong host, expired token, or branch-protection 403 all produced
# the same uninformative line. This is the participant's actual data file.
_loud(f"push_to_gitlab FAILED: host={base.split('//')[-1].split('/')[0]} "
f"project={project} branch={branch} status={r.status_code} {r.text[:200]}")
return ok