# Twitcher Workbench

Twitcher is a template-switch aligner that detects template switches across a genome. Twitcher Workbench is the viewer/analysis frontend and backend that ingests Twitcher's output CSV, groups repeated events, and lets users filter, inspect, and export them.

## Language

**Repeated-event group**:
A set of observations that share the same grouping key and are treated as the same underlying event. In `group` mode every observation is retained under one expandable representative row; in `collapse` mode only the representative is kept.
_Avoid_: duplicate, dedup group

**Grouping key**:
The pair that decides whether two observations belong to the same repeated-event group. Prefers `(ts_1_4_region_maximal, ts_2_3_max)`, compared for exact string equality, when BOTH are present for a row; falls back to the raw exact `(ts_1_4_region, ts_2_3)` pair when either is missing or could not be computed (e.g. output from an algorithm, such as Twitcher's `--fpa`, that never computes a maximal extent at all). A row where NEITHER rule produces a usable pair is its own unique group. There is no tag distinguishing which rule produced a given key, so a maximal-keyed row and an exact-fallback row that normalize to the same text are treated as the same event -- this is what allows comparing output from different Twitcher algorithms. See ADR 0001, ADR 0002, ADR 0006, ADR 0008.
_Avoid_: cluster_region key, CIGAR key

**duplicate_mode**:
The user-facing setting (`group` / `collapse` / `off`) that controls how repeated-event groups are handled. It decides grouping behavior only; it does not change the grouping key.
_Avoid_: dedup mode

**processing step**:
One of the five independently toggleable stages of full preprocessing: `preprocess` (basic preprocessing), `complexity` (sequence complexity), `tsm_scoring` (TSM interpretation), `gene_context` (gene/exon context), `repeat_mask` (repeat masking). Controlled in the web UI by the CSV processing checkboxes, and from `twb cli` via `--skip-steps`. A processing step is distinct from `duplicate_mode`, which is a mode of a single always-running stage (repeated-event grouping), not a step that can be skipped; and from `already_processed`, which bypasses every processing step at once rather than toggling one.
_Avoid_: processing option, pipeline stage

**Representative row**:
The first observation of a repeated-event group, used as the expandable summary row in the main table.
_Avoid_: group leader, primary row

**ts_1_4_region**:
The genomic region spanned by the template-switch event's 1→4 segments, as emitted by Twitcher (e.g. `chr1:14572-14580`).
_Avoid_: cluster region

**ts_2_3**:
The templated-segment value(s) of the event, as emitted by Twitcher (e.g. `8`, `10|12`). Pipe-separated when an event has multiple switches.
_Avoid_: ts23, templated segment count

**ts_1_4_region_maximal**:
`ts_1_4_region` widened to its maximal genomic extent, one switch block at a time, using that block's breakpoint-uncertainty shift columns (`ts_start_left_shift`/`ts_end_right_shift`). Those columns hold unsigned magnitudes (direction comes from the column name, not a sign), so widening subtracts `ts_start_left_shift` and adds `ts_end_right_shift`. Computed by the workbench (not emitted by Twitcher) and stored as its own visible column. Used as the first half of the preferred grouping key. See ADR 0002.
_Avoid_: widened region, ts_1_4_region_widened

**ts_2_3_max**:
Twitcher's own raw maximal templated-segment-length column, emitted alongside `ts_2_3` and pipe-separated the same way. Used as-is (no further widening) as the second half of the preferred grouping key. See ADR 0002.
_Avoid_: max templated segment, ts23_max

**identity column**:
The per-row field that identifies which biological sample produced the observation: `sample_name`. `sample_name`/`sample_label` is the only supported identity scheme; an old-version `read_id` column (no `sample_name`) is not detected as an identity column and rides through unprocessed. See ADR 0003.
_Avoid_: sample column, ID column, sample_id, read_id

**label column**:
The display-name field derived from the identity column: `sample_label`. The label column is a workbench concept: not emitted by Twitcher itself. It defaults to the raw `sample_name` whenever no explicit label has been set — the label column is never blank once a dataset has gone through full processing. Full post-processing bakes this default into the processed CSV on disk (see `default_missing_identity_labels()` in `preprocess.py`); the same default is also applied at view/export time as a fallback (`add_identity_labels()` in `routes.py`) for CSVs from before that default existed. A user-assigned rename (via the web UI or `POST /rename_identity_label`) permanently overwrites the label column in the processed CSV on disk, so it persists across reloads and is reflected in exports — `sample_name` is never modified by a rename. See ADR 0003.
_Avoid_: display label column, name column, read_label

**sample_name**:
The per-row sample identifier emitted by Twitcher output. The only supported identity column (see "identity column"). Never modified by labeling or renaming.
_Avoid_: sample column, sample_id, read_id

**sample_label**:
The workbench display label derived from `sample_name` (see "label column"). Stored in the browser under `SAMPLE_NAME_LABELS_KEY`. Never emitted by Twitcher; always generated by the workbench.
_Avoid_: sample_id_label, read_label

**demo mode**:
A deployment mode activated by setting the `DEMO_MODE=true` environment variable, intended for public-facing demo/conference deployments where untrusted users interact with the app directly. It (1) caps uploaded CSV file size at 40 MB, (2) disables the reference genome, gene annotation, repeat mask, and BAM/BAI custom upload endpoints (bundled presets remain usable), and (3) runs an hourly in-process cleanup sweep that deletes jobs (status + both CSVs) and JBrowse configs older than 4 hours. The frontend shows a small "Demo mode" indicator at the bottom of the page when active. See ADR 0004.
_Avoid_: public mode, safe mode, restricted mode

## Docker Hub

Image: `aryashta/twb` — tags `latest` and `vX.Y.Z` (current: `v0.7.3`). **amd64-only as of 2026-10-01** (see "Multi-arch decision" below) — older `latest`/tagged images pushed before this date via the podman multi-arch command may be multi-platform manifest indexes; any new push (CI or manual) is single-platform amd64.

### Pushing a new image (podman, current method)

Build and push an amd64 image directly from the Mac with `podman` — no Colima VM hop needed:

    podman build --platform linux/amd64 -t docker.io/aryashta/twb:latest .
    podman push docker.io/aryashta/twb:latest

Repeat with a `:vX.Y.Z` tag (or add `-t docker.io/aryashta/twb:vX.Y.Z` to the build) for a versioned release. `podman machine` (Apple Virtualization/`applehv` backend) provides the Linux kernel podman needs, so this works without sudo on the host, same as the old Colima approach — podman just doesn't have Colima's broken legacy-builder manifest bug, so no VM SSH/tar/scp hop is required.

This supersedes the earlier Colima-VM-buildx workaround (`ssh ... docker buildx build --push`) — that path still works if podman is ever unavailable, but podman is simpler and is the current method.

### Multi-arch decision (2026-10-01): amd64-only, dropped arm64

The image used to be built as a multi-arch (amd64 + arm64) manifest via `podman manifest create` + `podman build --platform linux/amd64,linux/arm64 --manifest ... .` + `podman manifest push`. That workflow is **podman-specific** and does not translate to the GitLab CI build (Kaniko): Kaniko has no built-in multi-arch/manifest support at all (upstream docs say so explicitly) — its only documented path is building separately on native runners of each target arch and stitching the resulting images into one manifest with an external tool (`manifest-tool`/`crane`). This repo's three CI runners (`rhel-node-1`, `rhel-node-2`, `openshift`) are **all `amd64`** per the GitLab runners API (`glab api runners/<id>`) — there is no arm64 runner to build natively on. Cross-building arm64 via QEMU emulation would need `--privileged`/`CAP_SYS_ADMIN` to register binfmt, which is the exact capability already confirmed blocked on both rhel and openshift runners (see "Why Docker Hub push was manual for a long time" below). Decision: CI builds amd64 only; arm64 support is dropped from Docker Hub going forward (not just deferred). If arm64 is ever needed again, it would require either a GitLab admin provisioning an arm64 runner, or reverting to manual podman multi-arch pushes from the Mac for just that release — not a CI change.

Also note: `Dockerfile` hardcodes fetching `twitcher-linux-x86_64` (the amd64 Twitcher binary) regardless of `--platform` — it was never made architecture-aware, so any arm64 image built by the old podman command would silently have shipped the amd64 Twitcher binary (exec format error at container runtime). Moot now that arm64 is dropped, but documented in case multi-arch is revisited.

### Why Docker Hub push was manual for a long time (now superseded by CI)

`podman build`/`buildah`/rootless-container builders need to create a Linux user namespace (`unshare(CLONE_NEWUSER)`) — normally something any unprivileged user can do on bare Linux (that's the whole point of rootless podman, and why it works on this sudo-less Mac: `podman machine`'s VM is a bare, non-nested Linux kernel).

GitLab CI runners run the job **inside a container** (Docker executor on `shared-runner`/`rhel`, Kubernetes pod on `openshift`), and both deny nested namespace creation by default to prevent container-breakout:
- `rhel` runner (Docker executor): default capability set drops `CAP_SYS_ADMIN` → `unshare` fails `Operation not permitted`.
- `openshift` runner (Kubernetes executor): `restricted` SCC strips all capabilities and blocks the syscall outright → `unshare` fails `Function not implemented`.

Verified 2026-09-30 with a throwaway CI branch: a bare `unshare --user --map-root-user` (no podman involved) fails identically on both runners before podman is even invoked, confirming this is a platform-level nested-container restriction, not a podman quirk. dind hits the same wall (needs `--privileged`). Kaniko doesn't need `unshare` at all — it builds by snapshotting the filesystem directly rather than using Linux namespaces — so it was never blocked by this restriction; it was blocked by a separate, unrelated kaniko bug (see below), now worked around.

### CI now does the full build + push (as of 2026-10-01)

`.gitlab-ci.yml` has `test` → `build` → `deploy` stages, running on every push to `master`:
- **build** (`build-image` job): Kaniko (`gcr.io/kaniko-project/executor:debug`) builds the Dockerfile unprivileged and pushes to this project's own GitLab container registry (`${CI_REGISTRY_IMAGE}`), tagged `latest` + the short commit SHA. No Docker socket, no DinD, no `unshare` — this is exactly why Kaniko works where podman/dind don't.
- **deploy** (`deploy-dockerhub` job): `crane` (`gcr.io/go-containerregistry/crane:debug`) copies that already-built image registry-to-registry (GitLab registry → Docker Hub), tagging it `latest` + `IMAGE_VERSION` (a CI variable in `.gitlab-ci.yml`, bump alongside `pyproject.toml`'s `[project].version` on release). A registry-to-registry copy needs no privilege at all, so it runs fine on the same shared runners.

Kaniko previously failed on this Dockerfile with `could not save file: copying file: symlink bzcmp -> bzdiff: file exists` — an open kaniko bug (GoogleContainerTools/kaniko#3371 and related) where `COPY --from=<stage> <symlink-heavy-dir>` makes kaniko try to individually re-save every symlink in the source tree during its cross-stage-dependency snapshot, and conda environments are full of these (coreutils-style multi-call binary symlinks, etc). Fixed by tarring the conda env into one regular file in the builder stage (`RUN tar -czf /opt/conda.tar.gz -C /opt conda`) and `COPY --from=`-ing + extracting that tarball instead of the raw `/opt/conda` directory — a single plain file has no symlinks for kaniko to choke on, and `tar -x` recreates the real symlinks on extraction. Confirmed working end-to-end on a throwaway branch (`ci-kaniko-dockerhub`, merged and deleted) 2026-10-01: Kaniko build succeeded, `which twb`/`RNAfold`/`RNAplot` all resolved post-extraction, and the resulting image was pushed and matched by digest on Docker Hub.

Kaniko's own layer cache (`--cache=true --cache-repo`) was tested and works, but is deliberately left **off** (`--cache=false`) in the committed pipeline: this Dockerfile's conda-tarball cross-stage COPY is the exact pattern the symlink bug hits, and a cold build already finishes in a few minutes on these runners, so the verified-safe choice was kept over the cache speedup.

Manual `podman manifest push` from the Mac (recipe above) is still the right tool for ad hoc rebuilds outside of a `master` push (e.g. testing a Dockerfile change before committing), and is unaffected by any of this.


## Rahti (CSC OpenShift) deployment

Live demo/staging deployment: `https://twb-twitcher-workbench.2.rahtiapp.fi`, OpenShift project `twitcher-workbench` on `https://api.2.rahti.csc.fi:6443`. Deployed manually via the OpenShift web console (Deployment `twb`, ImageStream tracking `aryashta/twb:latest` on Docker Hub, PVC `twb-ref2` mounted at `/app/ref` for reference genomes). **No manifests are checked into this repo** — the Deployment/Service/Route/PVC only exist on the cluster; if the deployment is ever deleted, it must be recreated by hand from the notes below (or better: `oc get deployment,svc,route,pvc -o yaml` should be exported into a `rahti/` directory and committed, per the University wiki's own "Things learned the hard way" advice).

**Demo dataset**: in demo mode `twb serve` preloads `/app/ref/demo/ASH_chr11.csv` (a *processed* CSV, made with `twb cli`) when no `--csv` is given, so the public demo opens with data. It lives on the `twb-ref2` PVC with the reference genomes, not in the image, and is gitignored (`ref/demo/**`). Install or replace it with no rebuild, then restart the pod (it is read once at startup):

    oc rsync ./ref/demo/ $(oc get pod -l app=twb -o name | head -1 | cut -d/ -f2):/app/ref/demo/ --no-perms
    oc rollout restart deployment/twb

`TWB_DEMO_CSV` overrides the path. If the file is missing the server starts normally and logs a warning. In demo mode the COV (coverage/read support) button and server-side BAM routes are disabled.

**OpenShift's default resource `LimitRange`** in this namespace caps unset container resources at `cpu: 500m` / `memory: 1Gi`. Postprocessing large CSVs (specifically: loading a whole-genome GFF3 for gene-context annotation) exceeds 1Gi easily and the pod gets `OOMKilled` (exit 137) — this surfaces in the browser as a 502/503 from the router mid-request, which the frontend's `await r.json()` then fails to parse (`SyntaxError: The string did not match the expected pattern`) because it received the router's HTML error page instead of JSON.

Two fixes were applied, 2026-09-30:

1. **Raised the Deployment's resources** (live cluster-side fix, immediate):

       oc set resources deployment/twb --requests=cpu=400m,memory=2Gi --limits=cpu=2,memory=10Gi

   Note the namespace `LimitRange` also caps `maxLimitRequestRatio: cpu: 5` — a request/limit ratio above 5 (e.g. `300m`/`2` = 6.67) is rejected at pod creation (`FailedCreate: cpu max limit to request ratio ... forbidden`), so cpu request and limit must be raised together.

2. **Fixed the actual memory hog in code** — `load_gene_features()` in `gene_annotation.py`, which for a whole-genome GFF3 (hg38: ~6-7M gene/exon/CDS rows) was building one Python dict per row, converting that to a DataFrame, then deriving a *second* per-chromosome DataFrame (`exons`) plus a *third* copy as `exon_records` (`list[dict]` via `to_dict("records")`) — 3-4 full in-memory copies of the same data held at once. Measured locally against the real hg38 GFF3 before the fix: **3.75 GB peak RSS, ~42s** just to load gene annotations. Rewritten to parse directly into flat columnar lists (no per-row dict objects) and build exactly one DataFrame, deriving numpy array views for both "all features" and "exon-only" lookups without further row-object copies. After the fix: **2.25 GB peak RSS (-40%), ~23s (-45%)**, same file. Full pipeline run (fasta + gene annotation + repeat mask + everything) against the real hg38 refs dropped from ~2.9GB/43s to ~2.1GB/23-28s.

   **Correctness pitfall hit during this rewrite, worth remembering**: the refactor's new sort/groupby order exposed a *pre-existing* bug in `_nearest_exon_fast()`'s fixed `±3` index window around the bisect position. Real genomes commonly have many transcript-isoform exons sharing the exact same `start` coordinate (observed: 12 exons tied at one hg38 locus); a fixed-width window can land entirely inside such a tie run and miss the exon with the truly-nearest `end`, silently picking an arbitrary tied candidate depending on incidental input order — caught by diffing `distance_to_exon`/`nearest_exon` output between an old-code run and a new-code run on the same real data (they disagreed on row 9 of the ASH CSV) rather than by any existing test (no dedicated unit tests cover `gene_annotation.py`'s tie-breaking). Fixed by widening the lookup window to fully cover whatever tied-start run it lands on, rather than stopping at a fixed offset — verified deterministic and stable by re-running the full pipeline twice and diffing outputs (0 diffs).

   This is a resource-usage number specific to hg38 + this particular GFF3 file; if postprocessing is later tested against much larger CSVs and still OOMs at 10Gi, raise the Deployment limit further (namespace max is `memory: 16Gi` per the LimitRange) — the code fix reduces the *baseline* GFF-loading cost, it doesn't cap total job memory (per-row annotation work still scales with CSV size).

**Rolling update gets stuck after a resource-limit change**: the PVC `twb-ref2` is `ReadWriteOnce`, so the default `RollingUpdate` deploy strategy deadlocks — the new pod can't attach the volume while the old pod (being replaced) still holds it (`FailedAttachVolume: Multi-Attach error`). Fixed by switching the Deployment strategy to `Recreate`:

    oc patch deployment twb -p '{"spec":{"strategy":{"type":"Recreate","rollingUpdate":null}}}'

This causes a few seconds of downtime on every redeploy (old pod fully terminates before the new one starts) but is required as long as the ref-data PVC is RWO and only one replica is expected. Keep `replicas: 1` — RWO also prevents horizontal scaling without switching the PVC's access mode or moving ref data to a shared/RWX volume.

**Non-root UID permission warnings (cosmetic, harmless, fixed in image)**: OpenShift/Rahti always runs containers as an arbitrary non-root UID belonging to group `0`, ignoring the image's declared `USER` (see the University Container Platform docs: "OpenShift forces the process ... to be run as a normal user even when the user is not defined in the Dockerfile"). This UID's `$HOME` defaults to `/` (read-only), so matplotlib and gunicorn logged `Permission denied: '/.config'` / `'/.gunicorn'` on every start (functionally harmless — both fall back to `/tmp` — but noisy and worth silencing). Fixed in the Dockerfile: `ENV HOME=/app` + `ENV MPLCONFIGDIR=/app/.cache/matplotlib`, with `/app/.cache` and `/app/.gunicorn` created group-writable (`chgrp 0` + `chmod a+rwX`) alongside the other app data dirs, since `/app` itself is root-owned and not writable by the arbitrary UID. Requires a new image build+push (podman procedure above) and redeploy to take effect — the live fix above (resource limits) is independent and already applied without needing a rebuild.
