| Age | Commit message (Collapse) | Author |
|
`POST /compute/gemma` now takes the same `covariates` list `/compute/rqtl`
does -- `{"case_attribute": "Status"}`, an explicit `map`, or per-sample
numbers -- and fits it with `-c` on the association step only. That needed
a covariate file of GEMMA's own, which is not R/qtl's: no header, no sample
names, positional over the genotype panel, numbers only. GEMMA has no
factors, so a categorical covariate is dummy-expanded here into k-1
columns named after their levels (`Status.Live`, the first level being the
reference), where R/qtl's wrapper does that expansion for itself.
The spec shape, the alignment onto the panel and the text coding are now
one module, `src/covariates.rs`, called by both routes; `/compute/rqtl`
behaves as before except that its note also reports the complete cases
(`... 34 with both the trait and the covariate`), which README and the
instructions had been promising all along.
A missing covariate value is written `NA`, which GEMMA treats exactly as
it treats a missing phenotype -- that individual leaves the fit (measured:
one fewer "number of analyzed individuals"). Deliberately not GeneNetwork2's
`-9`, which GEMMA fits as the value minus nine.
Found on live data, not in the fixtures: a level that exists in the panel
but that none of the *fitted* individuals carries becomes an all-zero dummy
column, and GEMMA stops with `LUDecomp ... input domain error` rather than
dropping the term the way R would. Columns that do not vary among the
individuals with both a trait and a covariate are now left out, and the
response names them (`Status.Cyro`, the `Cyro`/`Cryo` typo in BXD); a
covariate left with no columns runs without one, with a note saying so.
Covariates reach only the GWA step, never `-gk`, and gemma-wrapper hashes
its file arguments, so a different covariate set is a different cache entry
while the kinship already computed is still reused. Covariates need a
`group`: individuals are aligned by name, which an explicit
`genotype_file`/`snps_file` request does not carry (`422
covariate_unavailable`), and an attribute the group does not define lists
the ones it has.
* src/covariates.rs (new): `Spec`/`NamedValue` (the request shape, now
`CovariateSpec`/`CovariateValue` in the OpenAPI document), `Level`,
`Covariate`, `code_case_attribute`, `resolve`, `write_covarstruct_file`
(moved out of src/rqtl.rs) and `write_gemma_covariates_file`.
* src/gemma.rs (gwa_args, compute, compute_gwa): the optional covariate
file, `-c` after `-a` and before `-lmm`, and the notes about dropped
individuals and dropped columns.
* src/routes/gemma.rs: the `covariates` field, resolved after the trait
values so the note can count complete cases; `RqtlCovariate` replaced by
the shared spec.
* tests: six new -- the GEMMA file (numerical with `NA`; two and three
levels; inline codes; a dropped degenerate column) and an end-to-end
`compute_gemma_fits_a_case_attribute_as_a_covariate` on BXD/BXD.4 with
`Status`, which also pins that `-c` is in the GWA command and not in the
kinship one, and that the covariate changes the fit rather than reusing
the plain run's cache. The gemma tests now take a lock: the gate answers
a second job from the same caller with 409 instead of queueing it.
* README.md (/compute/gemma covariates rewritten for GEMMA, /compute/rqtl
points at the shared shape and explains `x` vs `NA`), docs/www/
ai-instruction.md (both endpoints; what differs in `notes`).
Also in the instructions: `/version` reporting a `git` value you have not
seen before now says explicitly to pull the repository and re-read
`docs/www/ai-instruction.md` before the next call. This deployment is
updated in place and a stale page does not announce itself -- the API
accepts the request without the new option, or answers with fields the old
text never mentions.
272 tests pass; the four that do not (benchmark, no_db, and two search
parity/proxy replays) fail identically at the parent commit.
|
|
`POST /compute/rqtl` now takes up to `RQTL_MAX_CONCURRENT` slots (default
8, read when the gate is built) with the same one-job-per-caller rule as
GEMMA: a second submission from the same token while its scan is running
or queued is refused `409 compute_busy`; a submission that finds every
slot taken waits for one to come free. Eight because an R/qtl scan is a
single-threaded Rscript on a 96-core box; not more, because a scan on a
3 000-individual cross is minutes of CPU and the same machine serves the
database. Unlike GEMMA's single slot, concurrent scans share no cache
(R/qtl results are uncached), so the only cost is the CPU they take.
Two flaws only appeared once there was more than one slot:
- the "what is running" record was a single `Option<Active>`, so a
refusal quoted whichever job had most recently taken a slot -- robw's
409 named JoM's run id. It is now a map keyed by subject, and
`a_refusal_quotes_the_callers_own_run_id` pins it;
- `Busy::describe` took the endpoint identifier, so the message read
"your rqtl job"; the decorator takes a separate `label` ("R/qtl") from
the status path.
The test suite hit the rule itself: six compute tests in tests/rqtl.rs
share one token, and cargo runs them on several threads, so three were
refused instead of run. They now serialise on a module mutex, with a
comment saying why -- the same lesson clients need, that parallelism
means more tokens, not more requests from one.
* src/compute_gate.rs (rqtl()): eight slots from `RQTL_MAX_CONCURRENT`;
`Gate::new(permits)` was already parameterised. `running` becomes a map
keyed by subject, since one record cannot name N jobs. Module doc talks
about slots rather than a single slot. Tests: eight subjects run and the
ninth waits, a caller still may not take two even with slots free, and a
refusal quotes the caller's own run id.
* src/config.rs: RQTL_MAX_CONCURRENT, default 8, fixed at first use.
* gnauth-macros/src/lib.rs: `label = "…"`, so prose and status path are
independent.
* src/routes/rqtl.rs: the decorator, and `_token` becomes `token`, which
it needs.
* tests/rqtl.rs: compute tests serialised.
* README.md (/compute/rqtl), docs/www/ai-instruction.md (4a),
docs/www/operator-checklist.md: the numbers per endpoint, and that more
parallelism means more tokens.
|
|
Every database-backed endpoint 500'd with `CodecError { IO error: Broken
pipe }` while the process answered /version quite happily. The cause was
ours: `pool()` turns off the driver's `check_health` (a ping at checkout,
dead connections replaced) to save a round trip -- sound against a
database 130 ms away, worth nothing against loopback, and it costs the
pool its self-healing. One server-side close of an idle session then
becomes one failed request per dead socket: ten in a row, until a
restart.
* src/db.rs: `SQL_CHECK_HEALTH` (default true) decides the ping;
`is_connection_loss` recognises the errors that mean the peer went away
(broken pipe, reset, went away, lost connection, closed);
`forget_pool` drops the cached pool so the next call rebuilds it;
`health` probes reachability, cached ten seconds. One pool static shared
by pool()/forget_pool (they had drifted into two).
* src/error.rs (ApiError::from_db): on a connection loss, forget the pool
-- the one place every database error passes through, so recovery does
not depend on each caller.
* src/lib.rs (/version): `"database": "reachable" | "unreachable"`; a
service that answers while nothing behind it works is now visible.
* src/config.rs: the switch, with the trade written down.
* tests/db_recovery.rs: kills every pooled session from a second
connection, then asserts the next twelve requests all succeed -- the
scenario that produced the outage, now a regression test.
* tests/...: unit test for the classifier (its own IO error text and the
"this is a bad query, do not retry" cases).
* README.md ("Database connections"), docs/www/operator-checklist.md:
the knob, why it defaults on, and what /version reports.
|
|
R/qtl has always been able to fit covariates; the API now passes them
through. `covariates` takes one or more specs, each either a case
attribute of the group by name -- which the server reads, aligns onto the
panel and codes -- or explicit per-sample numbers:
{"case_attribute": "Sex"}
{"case_attribute": "Diet", "map": {"HFD": 0, "LFD": 1}}
{"name": "age_days", "kind": "numerical", "values": [...]}
The coding is the server's job because the phenotype file is numeric:
text with 2-20 levels is coded 0..k-1 in sorted order and declared
`categorical` (the wrapper dummy-expands more than two levels), numeric
text goes through as `numerical`, and one level, more than 20 levels, or
an explicit map that misses a value is a 422 asking for a map rather than
an invented ordering. An attribute the group does not define is a 422
that lists the ones it has. Missing values become `x`/NA and R/qtl drops
those individuals.
Everything that decides the model goes into the cache key -- covariate
names *and* kinds, since a categorical covariate's dummy expansion is not
the same model as a numeric one -- and the response says what happened:
Covariate Sex: categorical coded F=0, M=1, 3281 of 3281 samples have a
value, 3281 with both the trait and the covariate
Measured on BXD-Longevity AgeAtDeath (3281 animals, WGS panel, 21056
markers): LOD 23.100 without the covariate, 23.522 with Sex, same peak
(rs30847416, chr 1, 5.0 Mb), ~15s more for the covariate run.
* src/rqtl.rs (Covariate, CovariateKind, code_case_attribute,
write_covarstruct_file): the coding rules, the extra pheno columns, the
covarstruct file, `--addcovar --covarstruct`, and the model's cache key;
five unit tests.
* src/routes/rqtl.rs (RqtlCovariate): the request shape, resolution
through the group's case attributes, duplicate/limit/ambiguity checks
(8 covariates at most), and the per-covariate note.
* tests/rqtl.rs: a real covariate run on UM-HET3 (894 markers, so the
test stays a test) asserting the coding note and the `--addcovar` line,
plus the unknown-attribute 422.
* README.md, docs/www/ai-instruction.md (4a): how to pass them, and that
the note's coding and complete-case count are the things to read.
|
|
The trait-values endpoint stays about trait values; a covariate needs the
study's metadata for the same samples, aligned the same way. So:
GET /groups/{group}/traits/{trait_id}/case-attributes/{attribute}
returns one attribute's values for exactly that trait's samples, **in the
trait's own order**, which is what makes it usable without the caller
re-sorting anything:
/groups/BXD-Longevity/traits/10001/case-attributes/Sex
-> 3281 values in AgeAtDeath's order, F x 3101, M x 180
-> order identical to /traits/10001/values (asserted in the tests)
Alongside the values it reports `distinct` (each value with its count,
commonest first) and `num_values`. That is the check that decides whether
an attribute can serve as a covariate at all -- a constant one cannot --
and it saves a second request just to find out.
Attributes are per group, so an unknown one is a 404 whose `next` is the
group's attribute list: BXD has no Sex, BXD-Longevity does.
* src/db.rs (get_trait_case_attribute, get_group_trait_samples): the
group's attribute values aligned onto the trait's sample list, joining
CaseAttribute/CaseAttributeXRefNew on (InbredSetId, CaseAttributeId) as
the group endpoint does; empty text is reported as no value.
* src/routes/groups.rs: the handler, token-gated, with the response
shapes and the two `next` links (the trait's values, the group's
attributes).
* tests/case_attributes.rs: alignment against an independent /values
response, `distinct` accounting, ordering, and the 404s for BXD (no Sex)
and for a non-existent attribute.
* README.md, docs/www/ai-instruction.md (3. Case attributes): the
endpoint, and "ask per trait rather than sorting the group's attributes
yourself".
|
|
The plot endpoints ran the mapping themselves, which meant the picture
could come from a different run than the one the caller was looking at,
and cost a scan to draw. They now take the mapping's own response -- the
JSON /compute/{rqtl,gemma} returned, posted back -- and hand it straight
to the plotter, which is what the scripts were written for
(`python3 plot-rqtl.py result.json -o out.svg --trait …`).
Validation replaces the run: `/plot/rqtl` needs `data.markers` with
positional 4+ column rows, `/plot/gemma` needs `data` rows *and*
`meta.columns` (its plotter reads the column names to find `p_lrt`), and
anything else is a 422 saying "post that response back". `/plot/rqtl`
also accepts just the `data` member; GEMMA cannot, and says why.
The mapping's `actions` suggestion now describes posting its own response
and carries no body -- duplicating a 21 000-row response into a
suggestion would double the envelope for nothing, and the caller already
holds it.
* src/routes/plot.rs: posted result, shape validation, `?trait`/`?title`
and `?bonferroni=false` passthrough to the scripts; no compute imports.
* src/routes/{rqtl,gemma}.rs: the plot suggestion loses its body.
* tests/plot.rs: canned results instead of real mappings -- the tests now
need only the plotter, no Rscript or gemma; covers both engines, the
bare-`data` form, and the 422 for a body that is a request.
* README.md, docs/www/ai-instruction.md (4a), docs/www/operator-checklist.md:
"post the response back", and why GEMMA needs `meta.columns`.
|
|
The two plotters Pjotr added (scripts/plot-rqtl.py, plot-gemma.py) turn a
saved mapping response into an SVG Manhattan panel. They are now
endpoints, and the mapping that produces the response suggests them:
POST /plot/rqtl same body as /compute/rqtl -> image/svg+xml
POST /plot/gemma same body as /compute/gemma -> image/svg+xml
Taking the mapping's own body rather than the mapping's output means one
call gets you the picture, and the plot cannot describe a run you did not
do: the handlers call the compute handlers and hand the resulting
envelope to the script, exactly as the scripts' docstrings describe
(they read `data.markers`, `data.permutation` and the notes' strain
counts). The mapping is re-run, but through the engines' own caches --
seconds on BXD.
The reply is an SVG, not the JSON envelope: an image is not JSON, and the
plotter's one-line peak summary rides back in `x-plot-summary` so a
caller that cannot see the picture still learns where the peak is.
Both compute responses gain the matching suggestion: `actions` carries
"the same request, plotted" (built from the request that ran, like the
permutation suggestion), so an assistant can map, look, and only then
decide whether the peak is worth the 100-permutation run.
* src/plot.rs: run the configured script over the envelope, read the
SVG back, clean up; a missing script is a 502 naming interpreter and
script, not a panic.
* src/routes/plot.rs: the two handlers (token-gated), delegating to
compute_rqtl/compute_gemma so validation and alignment stay in one
place; `x-plot-summary` sanitised into a header.
* src/routes/{rqtl,gemma}.rs: the plot suggestion, before the
permutation one.
* src/config.rs: PLOT_PYTHON, RQTL_PLOTTER, GEMMA_PLOTTER.
* tests/plot.rs: the suggestion resolves to a complete SVG with a peak
summary, and an invalid mapping request is the mapping's own 422.
* tests/{rqtl,phewas}.rs: find suggestions by href rather than position.
* README.md, docs/www/ai-instruction.md (4a), docs/www/operator-checklist.md
(new "Plotting": python3 must be on the server's PATH).
|
|
A scan gives LOD scores; the thresholds that make them readable come from
permuting the phenotype, which R/qtl supports (nperm) and this API
already ran -- but nothing told a caller to run it. So an unpermuted
R/qtl scan now ends with the same scan at nperm=100 in `actions` (a POST,
so not a `next` link), rebuilt from what actually ran: group + version +
the caller's own named samples, or the genotype file. The description
says what the thresholds are for and that it costs about 100 scans.
GEMMA is the honest half: it has no permutation test, and this endpoint
passes it nothing that would create one, so there is no nperm to suggest.
Its response says so in a note -- judge a peak against the smallest
p_lrt, not a genome-wide threshold -- and its `actions` suggests the
R/qtl permutation run over the same group and values instead. That is
real and runnable rather than a flag that would do nothing.
(gemma-wrapper does have `--permutate n`, which shuffles the phenotype
file and writes a permutation-stats file; wiring it up is a separate
job -- docs/genotypes.md and the README say it is not passed.)
* src/routes/rqtl.rs: the nperm=100 suggestion when nperm was 0, built
from the request that ran (original named samples, not the aligned
panel-length vector -- thousands of entries on a real panel).
* src/routes/gemma.rs: the note, and the cross-engine suggestion.
* tests/rqtl.rs: a path-based scan's suggestion reuses the same files.
* tests/phewas.rs: a group-scoped scan suggests both -- the PheWAS in
`next` (resolved) and the permutation run in `actions`.
* README.md, docs/www/ai-instruction.md (4a): what thresholds are, that
R/qtl offers them and GEMMA does not, and what to do about it.
|
|
PublishXRef records the marker each published trait's QTL peaks at
(Locus) with its LRS, which is a PheWAS waiting to happen: fix a
position, find the markers within a window of it, and ask which traits
peak at those markers.
GET /groups/{group}/phewas?locus=rs30524230&window=10000
GET /groups/{group}/phewas?chr=9&mb=29.940961&window=10000
The window is in base pairs, centred, default 10 kb either side -- the
"10K up and downstream" case. Positions come from the group's genotype
marker table (the endpoint added last round), so `genotype_version`
selects whose markers define the window and the answer reports them
alongside the traits: an empty `traits` list is then readable as
"nothing peaks that close" rather than a failure, and a ten-times wider
window is offered as `next`.
Measured on real data, ±10 kb around rs30524230 (chr 9, 29.94 Mb, a BXD
QTL peak at LRS 460): 4 markers, 10 traits, from LOD 99.9 down to 2.68 --
ANPEP_band, then microbiome/haematology/infectious-disease traits. That
cluster of 99.9s is the 460 LRS cap, not a spectrum, which the notes say.
* src/db.rs (get_phewas_traits): PublishXRef rows for a set of peak
markers, joining Phenotype/Publication through the existing
trait_info_sql, strongest first; marker names are re-validated before
they reach the IN list.
* src/routes/phewas.rs: the endpoint, token-gated; window/centre
validation (422 for none or negative), 404 for an unknown locus, notes
for the empty cases, and a unit test for the version/group helper.
* tests/phewas.rs: markers in the window, traits sorted by LRS with
lod = lrs/4.604, every hit peaking at a listed marker, zero-width window,
the two failure modes, and that the suggested wider window resolves.
* README.md, docs/www/ai-instruction.md (new 4b: how to read a PheWAS),
docs/www/operator-checklist.md: the endpoint and its reading.
|
|
* README.md (/version): the example carries dirty/source_digest/branch,
and the prose says why a stamp can lag a commit -- a binary built from a
dirty tree must not claim that commit -- and that build.rs re-stamps on
a commit because it watches the ref, not just .git/HEAD.
* docs/www/ai-instruction.md: comparing against a clone means comparing
the part before "-dirty", with source_digest for the exact build.
* tests/version.rs: `dirty` mirrors the suffix, branch is non-empty, and
source_digest is 16 hex digits or unknown.
|
|
The listing named versions but not files; a caller could pick one and
still not see what was in it. Three token-gated routes now describe a
version completely, short of the matrix:
GET /groups/{group}/genotypes versions, files, sizes, current
GET /groups/{group}/genotypes/{version} file name, header labels,
individuals, strains, chromosomes
GET /groups/{group}/genotypes/{version}/markers markers (name, chr, cM, Mb), paged
The detail reads the file's own `@`-labels (type, mat, pat, het, unk,
scale) and its panel in column order, and reports both the whole panel
and the strains a mapping uses after the parents/F1s rule -- so a caller
can check a request before sending it and interpret a result after.
Markers come back as positional rows with `meta.columns`, paged with
`?page`/`?limit` and filterable with `?chr`, following /compute/gemma's
shape rather than inventing one.
The genotype calls stay on the server: file_meta() reads the matrix to
skip it, and nothing returns a cell.
* src/genotypes.rs (Marker, FileMeta, file_meta; GenotypeFile::file):
header labels, individuals and marker positions; unit test.
* src/routes/genotypes.rs: the two new handlers, token-gated like the
listing, plus `file` in the listing and counts in the detail.
* tests/genotypes.rs: the listing carries file names but no paths.
* README.md, docs/genotypes.md, docs/www/ai-instruction.md: what the
three routes give, and that the matrix is not among them.
|
|
Until now /compute/{rqtl,gemma} took server paths, so the caller had to
know the deployment's layout, pick a version, and expand a trait's values
onto the panel in the file's order -- none of which the API told it. The
listing endpoint and the group-scoped request remove all three:
GET /groups/{group}/genotypes versions, newest first, no paths
POST /compute/rqtl {group, [genotype_version], samples}
POST /compute/gemma {group, [genotype_version], samples}
The resolver (src/genotypes.rs) applies GeneNetwork2's rule -- the
group's genotype/<Group>.json `genofile` list is newest-first and its
first entry is current; groups with no JSON (HET3-ITP) fall back to the
highest version number, and the listing's notes say which happened --
reads the panel from the .geno header the way GN3 does, and excludes
parents and F1s by default (GN2's `incparentsf1` off, GN3's
`get_sample_list(inc_par=False, inc_f1=False)`).
Excluding them has to subset the genotype matrix, not null-fill the
values: a null keeps an individual out of the fit but not out of GEMMA's
kinship or R/qtl's cross. So `prepare` writes a panel-subset file under
the engine's cache directory, keyed by panel, and reuses it.
Nothing in the listing or the mapping response carries a path: the
endpoint reports versions and sizes, and `notes` names the resolved
version, the panel size and how many values aligned. Explicit
`genotype_file`/`snps_file` remain as an override for files outside the
layout, and the two request shapes are mutually exclusive (422).
* src/genotypes.rs: new. Discovery, resolution, panel parse, parent/F1
exclusion, subset preparation, name alignment; 10 unit tests.
* src/routes/genotypes.rs: new endpoint, with a test that its list has no
path or file name in it.
* src/routes/{rqtl,gemma}.rs: group + genotype_version +
include_parents_f1; named `samples` aligned server-side; notes record
what resolved. gemma also accepts named samples where it used to insist
on positional trait_values.
* src/suggest.rs: suggestions from /groups/{group}/traits/{id}/values now
carry `group` and no placeholders; the dataset-scoped ones keep the
placeholder and say to add the group.
* src/routes/groups.rs: the group record points at /genotypes.
* src/config.rs: GENOTYPE_FILES (default the gn4-data directory).
* tests/genotypes.rs: new integration test (skips without the directory).
* README.md, docs/genotypes.md, docs/www/*: the flow is now "ask for the
versions, map by group" -- measured runs, the parent/F1 rule, the
subsetting requirement, and the restart list unchanged.
|
|
Fetching one trait's value per strain is usually the step before mapping
that trait, and the API can do the mapping. Those calls are POSTs with a
body, so they cannot go in `next` -- a `next` link is a GET that returns
200, which is what makes `next` safe to follow blindly and what
tests/envelope.rs relies on. Hence a fifth envelope member, `actions`,
holding method + href + description + body, and omitted entirely when
there is nothing to suggest (most responses keep the four-member shape).
The three per-trait values endpoints now carry a `POST /compute/rqtl`
and a `POST /compute/gemma` suggestion with the values already in the
body, in the response's own sample order. Genotype/SNP paths stay
bracketed placeholders: they must exist on the server, which the server
cannot know on the caller's behalf.
The instruction page says, in the same breath, never to run R/qtl or
GEMMA locally -- a local scan would use genotypes that are not the
panel's and would disagree with GeneNetwork's own results -- and that
results are cached, so repeat calls are cheap (measured: ~2 s cached
against ~20 s cold on the BXD fixtures).
Also fixes a flake the new test exposed rather than caused:
config::tests read and write process-global env vars and Config::load()
reads all of them, so the RAVANAN_* tests could fail
search_engine_keys_follow_env_over_default_layering on an unrelated
assertion. One module-level lock serialises them.
* src/response.rs (SuggestedCall, Envelope::actions/with_action/
with_actions): the new member, omitted when empty; unit tests for both.
* src/suggest.rs: new. Builds the two suggestions for either value type
(db::TraitValue, db::ProbeSetValue), with its own unit tests.
* src/routes/{traits,groups,datasets}.rs: the three values handlers.
* tests/compute_suggestions.rs: new. Suggestions present with values in
order, on all three routes; absent elsewhere; `next` still GET-only and
still returns 200.
* src/config.rs (tests): env_guard, taken by the 11 config tests.
* README.md (Success responses): the `actions` member, with an example.
* docs/www/ai-instruction.md (4a): never compute locally, why, caching,
and how to use the suggested bodies.
* docs/www/operator-checklist.md: the caching numbers.
|
|
The suite covered each half of /search separately: tests/search.rs pins
the MariaDB side (locus, abbreviation, complete/partial) but through the
gn3 stub engine, and the search_native* tests pin the native engine
against a dev index and never need a database. Native engine + live
db_webqtl -- the combination that actually runs in production -- was
only ever checked by hand.
tests/search_native_db.rs closes that: route level, dataset:bxdpublish
must come back 200 with meta.state complete and annotated hits; at the
engine seam, dataset:BXDPublish must match the same documents as
dataset:bxdpublish; and the match set's ids must be the database's
PublishXRef ids for the BXD group.
The strict id comparison runs only against a full index, selected with
GN4_FULL_INDEX (skipped by default, like GN4_PARITY_FIXTURES). Against
the dev index the ids are printed as reference data instead: it is a
different snapshot, missing 1 772 of the database's traits and holding
349 the database no longer has, which is exactly what made the strict
form worth having.
|
|
# Conflicts:
# src/gemma.rs
# src/rqtl.rs
# src/streaming.rs
|
|
gemma-loco.cwl was a generated artifact (ccwl compile's output), but
was being committed like hand-written source. Remove it, and have
compute_ravanan compile cwl/gemma/gemma-loco.scm to a throwaway CWL
file under its own cache dir on every call instead -- cheap (pure
macro expansion, no Guix build involved), so there's no real cost to
regenerating it fresh each time, and no risk of a stale compiled file
drifting from its ccwl source.
Config gains a ccwl_cmd knob (default "ccwl", resolved via PATH,
alongside ravanan_cmd/gemma_wrapper_cmd); gemma_ravanan_workflow now
names the .scm source, not a .cwl file. Verified end to end by running
the exact compile-then-run sequence compute_ravanan now performs
against the real ccwl/ravanan/gemma-wrapper binaries and the BXD
fixtures: same correctness and timings as before.
|
|
Replace gemma-loco.cwl's single kinship/gwa pair (each one gemma-wrapper
invocation covering all chromosomes, relying on gemma-wrapper's own
internal GNU-parallel fan-out) with one gemma-wrapper invocation PER
CHROMOSOME, restricted via its existing --chromosomes/--no-parallel
flags and scattered by ravanan itself (ScatterFeatureRequirement,
scatterMethod: dotproduct). gemma-wrapper still does the correct
per-chromosome LOCO math (exclude this chromosome from kinship, test
only its markers) against the full genotype/SNP files -- only which
chromosome(s) it loops over changes. compute_ravanan now computes the
chromosome list itself (chromosomes_in, mirroring gemma-wrapper's own
get_chromosomes) and passes it as the workflow's scatter input, and
collates the resulting per-chromosome gwa_json/archive array outputs.
Measured 16.7s wall-clock end-to-end against the BXD fixtures (20
chromosomes), vs. ~19s for /compute/gemma's direct path and ~21s for
the previous sequential ravanan workflow -- confirmed byte-for-byte
identical output (rs31443144's exact values, 7320 total rows).
Also fixes three real, previously-unexercised bugs in compute_ravanan
found getting this to run at all (POST /compute/gemma/ravanan had no
automated test until this commit):
- missing --guix-manifest (ravanan requires it; added
gemma_ravanan_manifest config key and cwl/gemma/manifest.scm)
- missing --store files/logs/data subdirectories (ravanan does not
create them itself)
- --output-directory dropped entirely: every chromosome's gwa archive
shares gemma-wrapper's own content-hash basename (the hash doesn't
factor in --chromosomes), so ravanan's optional flat-symlink step
collides across them; unneeded anyway since results are read
straight from ravanan's --store via its stdout JSON record.
Also found and worked around a ravanan scheduler bug: a step scattered
over exactly one input needs an explicit scatterMethod even though CWL
only requires one for multiple scattered inputs -- ravanan has no
fallback case for a missing one and silently misbehaves.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
|
|
So a caller of /compute/gemma(/ravanan) or /compute/rqtl doesn't need
to count data's rows or columns.len() itself. with_columns now takes
the row count too and derives num_cols from the column list.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
|
|
Same space-saving shape as the gemma commit: /compute/rqtl's markers
are now positional arrays (name, chr, pos, lod, plus any 4-way-cross
extra effect columns trailing) instead of one keyed object per row,
with the fixed column names in meta.columns.
Also fixes tests/gemma.rs, which still asserted the old keyed shape
from the gemma change -- missed in that commit.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
|
|
Pure formatting sweep (import ordering, line wrapping); the tree
had accumulated rustfmt drift. Separated from any semantic change
so it stays reviewable and revertable on its own.
|
|
* src/config.rs (DbMode, Config.db_mode, parse_db_mode): add
GN4_DB_MODE=dev|production in the layered config; dev runs with no
configured DB; fail-closed parse (a typo refuses).
* src/db.rs (DbError, pool, probe), src/error.rs (ApiError::from_db):
mint a typed 503 db_unavailable at the db::pool() choke point,
distinguishing Unavailable from Query.
* src/main.rs: loud no-DB startup line; production refuses to start
(exit non-zero) before axum::serve.
* src/routes/{accessions,datasets,groups,mapping_methods,publications,species,traits}.rs:
route every DB error through ApiError::from_db.
* src/bin/gn-indexer.rs: refuse to build an index when the DB is unreachable.
* tests/no_db.rs: pin no-DB degradation (search 200 partial, DB routes 503).
His ask (DM 2026-10-12): "Make it an option to switch it off for
development machines? I mean mariadb." The no-DB hardening is ours
(review-driven). Default GN4_DB_MODE left unflipped (=dev); the flip needs
owner sign-off.
|
|
Same request/response shape as /compute/gemma: synchronous (no job
queue), ?id= + GET /compute/rqtl/status/{run_id} progress-streaming.
Extracted that streaming infrastructure (run_streaming, create_run_log/
RunLogError, status/StatusError, RunStatus/RunStatusParams,
is_valid_run_id, COMPLETION_MARKER) out of src/gemma.rs into a new
src/streaming.rs so both compute endpoints share it instead of
duplicating it; src/routes/gemma.rs updated to the shared names,
confirmed its own 8 tests still pass unchanged.
scripts/rqtl_wrapper.R is GeneNetwork3's script, copied here verbatim
and run via Rscript -- same reasoning as reusing gemma-wrapper rather
than reimplementing GEMMA. Scope: a single scan (scanone) plus, if
nperm > 0, its permutation thresholds (67th/95th percentile, via a
Rust port of numpy.percentile's default linear interpolation) -- the
common case. Not implemented: covariates, interval mapping,
permutation strata, pair-scan (scantwo) -- scantwo in particular needs
cross-referencing the genotype file for nearest-marker lookups and a
second (MAP_) output file, a materially bigger port than this covers.
One fix relative to GeneNetwork3, found by reading the code (no test
covers the real caller's keys): generate_rqtl_cmd's content hash only
ever looks at kwargs keyed "g"/"p", but gn3/api/rqtl.py's real caller
uses keys "geno"/"pheno" -- they never match, so the genotype/
phenotype file contents never actually enter the cache-key hash in
production, only the other options. Two different phenotypes mapped
with the same other options would get the same cached output filename
and silently reuse each other's result. Fixed here: both files'
contents are always hashed (std DefaultHasher -- a cache key, not a
security boundary, so no need for GeneNetwork3's md5).
guix.scm: r, r-qtl, r-optparse, r-stringi and r-stringr added as
propagated-inputs (same category as gemma-wrapper, and same reasoning:
invoked as a subprocess, not linked). All stock Guix -- confirmed the
existing -L (needed only for gemma-wrapper, from guix-bioinformatics)
is not needed for these; the dev shell has Rscript/R-qtl on PATH from
guix.scm's own propagated-inputs alone.
Test fixture: a small, hand-written, valid BXD riset genotype/
phenotype pair (tests/test_data/rqtl_sample1.*), not GeneNetwork3's
own tests/unit/db/.../genotype_sample1.geno -- that fixture has a
genotype code outside its own header's declared set and duplicate
marker names across chromosomes, harmless for the unrelated parsing
unit it's written for there, but both would break a real R/qtl run.
Verified end to end, not just unit tested: tests/rqtl.rs runs the real
Rscript/R-qtl against that fixture (a real scanone scan, real
permutation thresholds with suggestive <= significant, the run-id-
collision 409 pre-seeded with no Rscript needed, and the completion
marker landing in a real log after the run finishes). cargo test
passes in full.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
|
|
|
|
peak -> peek: the status endpoint's byte-offset query parameter and
everywhere it's documented (code comments, the GemmaStatusParams
field, tests, README). GeneNetwork3's own equivalent
(gn3/api/streaming.py) is spelled "peak"; noted where this now
deliberately differs, not touching the unrelated "peak marker" wording
elsewhere in the README.
Run id uniqueness: the log file is now created with
OpenOptions::create_new(true) instead of a plain truncating write, so
it fails atomically (no separate check-then-write race) if a log
already exists for that id -- another run still in progress, or a
finished one never polled/cleaned up. Added GemmaError::RunIdInUse,
mapped to 409 Conflict in the route, caught before any subprocess
runs. Previously a reused id would have silently truncated whatever
was already there.
Verified: the new compute_gemma_rejects_a_run_id_already_in_use test
pre-seeds a log file for an id and confirms the POST is refused (this
needs no gemma-wrapper, since the check runs before any subprocess
call). cargo test passes in full.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
|
|
/compute/gemma can genuinely take minutes (see the README's ~100K
marker caveat), and until now gave no visibility into a run already
in flight. Same shape GeneNetwork2/3 use for R/qtl
(gn3/computations/streaming.py, gn3/api/streaming.py): the caller
picks a run id, passes it as POST /compute/gemma?id=<id>, and polls
GET /compute/gemma/status/{id}?peak=<offset> on a second connection
while the first is still blocked.
What's actually tailed is gemma-wrapper's stderr, not stdout: under
--json, all of its human-readable progress (banner, chromosome list,
"Executing: ...", per-step info) goes to stderr, and stdout carries
only the one final JSON record, printed once at the very end -- so
there is nothing to stream on stdout. run_streaming() replaces the
old buffered Command::output() call with one that reads stderr line
by line as the process runs, appending each line to a log file if one
was given, across both the kinship and GWA steps into a single
continuous log; stdout is still read in full (unchanged, one JSON
blob). A completion marker ("GN4: computation complete") is appended
once the whole request finishes, the same convention GeneNetwork3
uses ("Done with GN3 Computation" in gn3/api/rqtl2.py) under this
project's own name.
run_id is validated (1-64 ASCII letters/digits/-/_) before it's ever
joined into a path, on both the POST's ?id= and the status endpoint's
path segment -- GeneNetwork3's own /api/stream/{run_id} does no such
check on its equivalent id, which is not knowingly replicated here.
Verified end to end, not just unit tested: the integration test spawns
the POST on its own task and polls the status endpoint from this one
while the ~19s real computation is still running, asserting it
actually observed non-empty progress lines mid-run (not merely after
the fact), then checks the finished log for both real gemma-wrapper
progress text and the completion marker. cargo test passes in full.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
|
|
commands in the response notes
README: added /compute/gemma to the endpoint table and a dedicated
section with a real example response, and the explicit caveat the
user asked for -- not feasible past roughly 100,000 markers at this
point (synchronous, sequential, no parallel LOCO jobs; the BXD
fixtures, 7,320 markers, already take ~19s, and real datasets go up to
~1M markers).
notes: the response now carries the exact gemma-wrapper invocations
used for the kinship and GWA steps ("Kinship: gemma-wrapper ... -gk",
"GWA: gemma-wrapper ... -lmm 9"), not just a generic description.
kinship_args/gwa_args build the argument list once and feed both the
actual subprocess call and the note text, so the two can't drift
apart. Added unit tests asserting -gk and -lmm never appear together,
and extended the real end-to-end test to check both notes' shape.
Verified: cargo test passes in full, including the real gemma-wrapper/
GEMMA run, with the notes field inspected directly against the actual
command lines used.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
|
|
index; INCREMENTAL crawls, hashes each document's complete source,
replaces only changed documents by identity term, deletes vanished
identity terms, and writes nothing when nothing changed.
* src/indexer/schema.rs: the identity/type/prefix/slot definitions
shared by the writer and the native reader.
* src/indexer/rows.rs: the gene and phenotype crawl. Both queries
carry confidentiality < 1 AND public > 0; the Python phenotype query
has no WHERE clause (the metadata leak this closes by construction).
* src/indexer/build.rs: document construction, mirroring index_genes /
index_phenotypes call for call (TermGenerator configuration, prefix
order, value slots, popped-before-storage fields, identity term).
* src/indexer/pyjson.rs: byte-exact reproduction of Python json.dumps
(separators, ensure_ascii escaping, shortest round-trip float repr
with CPython's half-to-even tie-breaking).
* src/indexer/cache.rs: the RDF RIF/wiki dictionaries, reproducing
build_rdf_cache(remove_common_words=True) from the authoritative
cache file; each dictionary is one monolithic hashed input.
* src/indexer/sha256.rs: dependency-free SHA-256 for the source and
cache hashes.
* src/indexer/sidecar.rs, src/indexer/run.rs: per-document source
hashes in a sidecar next to the index (atomic rename strictly after
the index commit), FULL and INCREMENTAL orchestration, identity-term
uniqueness assertion, and the startup key-set mismatch fallback.
* src/lib.rs: register the indexer module.
* tests/data/pyfloat.txt: reference-docdata float-token fixture for the
serializer test (generated read-only from the reference index).
|
|
GeneNetwork2 (wqflask/marker_regression/gemma_mapping.py) and gn-guile
(gn/runner/gemma.scm) both always use -lmm 9 in their working --loco
invocations. Checked by running it: gemma-gn2 accepts 9 fine, and the
resulting .assoc.txt carries p_lrt, not p_wald -- some mapping other
than stock GEMMA's 1-4 scale, not independently verified here, but
consistent with what both of those codebases rely on in production.
Widened validation from a 1-4 range to the explicit set {1, 2, 3, 4,
9}: 9 is now known-good, but 5-8 remain untested and stock-invalid, so
they're still rejected rather than guessed at.
Updated the real end-to-end test to assert on p_lrt (what lmm=9
actually produces) instead of p_wald, and moved the
out-of-range-lmm test from 9 (now valid) to 5.
Verified: cargo test passes in full, including the real gemma-wrapper/
GEMMA run against the BXD fixtures with the new default.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
|
|
Maps a QTL from a genotype file, a SNP annotation file and trait
values, by running gemma-wrapper's K-matrix step then its LMM
association step, both synchronously (axum/tokio awaits the subprocess
directly, no job queue needed) and returning the parsed .assoc.txt
rows in the standard envelope.
Both steps use a bare --loco (gemma-wrapper derives the chromosome
list from the SNP annotation file). This was arrived at empirically,
not from GeneNetwork3's or GeneNetwork2's own gemma code: run for real
against the BXD fixtures,
- GeneNetwork3's gn3/computations/gemma.py composes a GWA command that
always keeps "-gk" alongside "-lmm"; real GEMMA rejects that
combination outright ("only one of -gk ... -lmm ... options is
allowed"), so none of its gwa-compute/k-gwa-compute endpoints can
produce output. Unsurprising: tests/integration/test_gemma.py is
entirely @unittest.skip, so this was never exercised.
- GeneNetwork2's wqflask/marker_regression/gemma_mapping.py correctly
omits "-gk" from the GWA step, but its non-LOCO branch fails too,
the same way my own first (non-LOCO) attempt did: gemma-wrapper only
ever archives a non-LOCO kinship matrix into a .tar.xz, with no
loose file at the path its own non-LOCO GWA code assumes
("Enforce failed for file_kin ... open file"). Only --loco, which
gemma-wrapper's own USAGE banner documents and which does unpack
that archive, actually works.
A --loco run's .assoc.txt files (one per chromosome) are themselves
only ever inside gemma-wrapper's own output archive, never loose, so
gemma.rs shells out to `tar` (one of gemma-wrapper's own propagated
dependencies) to extract them before concatenating all chromosomes'
rows into the response.
guix.scm now depends on (gn packages gemma) from guix-bioinformatics
for gemma-wrapper (propagated-input: it's invoked as a subprocess, not
linked, and this makes it land in a consuming profile too, same as
GeneNetwork3's and GeneNetwork2's own packages do it). That dependency
needed guix-bioinformatics' own gn/packages/gemma.scm fixed first (see
that repo's fix/gemma-which-shadowing branch) -- gemma-gn2 would not
build at all before that fix.
Verified end to end: `cargo test` passes in full, including a real
(non-mocked, non-skipped) run of gemma-wrapper/GEMMA against the BXD
fixtures copied from genenetwork3/tests/test_data, producing exactly
7320 association rows (one per marker in BXD_snps.txt) in ~19s.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
|
|
autocxx-bindgen with libclang 22 mis-parses Xapian 1.4.29: the C++ it
generates for xapian-rs instantiates the abstract Xapian::Weight (via
a bogus std::vector<Xapian::Weight> bridge) and emits an out-of-scope
'::op', so the build failed in the cargo build phase. The xapian-rs
fork was built (and target/ produced) with libclang 13.0.1, whose
parse is correct. Depend on clang-13 and point LIBCLANG_PATH at it in
the set-duckdb-paths phase. (clang-13's package name is "clang", so
it replaces the clang-22 input rather than colliding with it.)
Also create the scratch directory in tests/embedded.rs: the SQLite test
opened test.db under a directory that did not exist yet.
guix build -f guix.scm now completes end to end (Rust check phase and
the Python REST suite), producing
/gnu/store/3avgh789ffy3lrfiql334dghp9sa4sqd-genenetwork4-git-0.1.0.
|
|
Add src/embedded.rs with lmdb/duckdb/sqlite round-trip helpers and
tests/embedded.rs integration tests: an LMDB put/get (surviving a
fresh environment handle), an in-memory DuckDB query, and a SQLite
query.
Depend on the system libraries rather than bundled builds:
duckdb 1.10506.0, lmdb 0.8.0 and rusqlite 0.40.2 with their default
features, so the Guix build reuses libduckdb/liblmdb/libsqlite3 instead
of compiling its own.
Guix wiring (guix.scm): add the duckdb, lmdb and sqlite inputs
((gnu packages duckdb)/(gnu packages databases)/(gnu packages sqlite)),
a set-duckdb-paths phase that points libduckdb-sys at the system
libduckdb via DUCKDB_LIB_DIR/DUCKDB_INCLUDE_DIR (there is no
duckdb.pc), and the 79 new crate sources in rust-package.scm
(regenerated with `guix import crate -f Cargo.lock genenetwork4`).
|
|
tied to dev mode.
The endpoint no longer depends on GENENETWORK4_DEV_MODE or on the bind
address. It decides per request whether to answer.
* src/routes/dev.rs (get_test_token): answers a caller only when the TCP
peer (axum ConnectInfo) is in 127.0.x.x (or ::1, or an IPv4-mapped
127.x) and the request carries no X-Forwarded-For, Forwarded or
X-Real-IP header (a reverse proxy on the same host would otherwise make
every client look local). Anything else, including an unknown peer, is a
403. Local is never established from a header.
* src/main.rs: serve with into_make_service_with_connect_info, which
provides the peer address.
* src/config.rs: remove dev_mode, GENENETWORK4_DEV_MODE and
dev_token_enabled(). Add GENENETWORK4_TEST_TOKEN (on by default); when it
is not a clearly affirmative value (true/1/yes/on) the route is not
registered: a 404, absent from /openapi.json. It fails closed, so a
typo ("flase") turns the endpoint off.
* src/lib.rs: register the route unless that switch is off.
* tests: tests/get_test_token.rs rewritten (remote, unknown and proxied
peers refused; 127.x and ::1 answered; always documented by default);
tests/get_test_token_off.rs for the switch (own process: it sets an
environment variable); common::post_from supplies a peer address to the
in-process requests. Python: test_get_test_token.py rewritten, TOKEN_ENV
is now empty (no setting needed).
* README.md, docs/gn-auth.md, docs/SKILL.md, RELEASE_NOTES.md: document
the check, the switch, and "Behind nginx or in a container" (a bridge
container sees the gateway as the peer; a host-network container behind
nginx sees 127.0.0.1, so block the path in nginx, set X-Forwarded-For,
or switch the endpoint off).
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
|
|
/accessions.
Answers four more questions of aisearch's full_benchmark.csv from
tables the API did not expose.
* src/db.rs (Group, GroupDetail), src/routes/groups.rs: groups gain
`mapping_method`, the name of the MappingMethod row their
mapping_method_id points to (qtlreaper, Rqtl, ...), or null.
* src/db.rs (Dataset): datasets gain `tissue`, the Tissue their
ProbeFreeze points to (e.g. "Brain mRNA").
* src/routes/mapping_methods.rs: GET /mapping-methods lists the
MappingMethod table, including tools no group uses (PLINK, FastMap).
* src/routes/accessions.rs: GET /accessions/{accession} resolves a
GeneNetwork accession number (GN602, gn602 or 602) via InfoFiles to the
dataset's name, title, category (publish/probeset) and group.
* docs/genenetwork_datatypes.md: MappingMethodId is a key into the
MappingMethod table (the authoritative reading); GN2's code-based reading
is noted as superseded.
* tests/benchmark.rs, test/data/benchmark_search.json: add the 60 new
full-benchmark rows that pass (full rows 0..114; search rows run against
recorded production gn3, the rest need the database), and full rows 33
(mapping tools), 34 (Rqtl for outbred sets), 35 (GN602) and 44 (only
GTEx v8 has TPM datasets). The untested rows are listed in the file's
header comment with the reason for each.
* tests, test/python: tests for the new fields and endpoints; both
endpoints added to the OpenAPI and next-link crawl tests.
* README.md, RELEASE_NOTES.md: document the new fields and endpoints.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
|
|
Breaking: every success body is now {"data", "meta": {"state",
"took_ms", "request_id"}, "notes", "next"}; clients read `data`. Only
`/` (plain text) and `/openapi.json` are unwrapped.
* src/response.rs (Envelope, Meta, State, Ctx, RequestInfo): handlers
take Ctx first and build the response with ctx.envelope(data), so
timing and the request id are never filled in by hand. `state` is
`complete` or `partial`; notes are server-authored only; `next` are
concrete relative hrefs (path_segment percent-encodes names).
* src/routes/*.rs, src/lib.rs (version): every handler returns
Envelope<..> with next links; /search is `partial` when the locus
lookup fails or a sorted 1000-hit window may be truncated, and
/publications/{pubmed_id}/traits when datasets were left out for
authorization.
* src/error.rs (ApiError): add `took_ms`, an RFC 7807 extension member.
* src/auth.rs (AuthToken): the 401 now carries request_id and took_ms
(it never had a request_id); Ctx stores RequestInfo in the request
extensions for it.
* tests: common::data / envelope_data parse every success body through
the envelope; tests/envelope.rs and test/python/test_envelope.py check
the shape, errors, and that every `next` link resolves;
tests/envelope_partial.rs checks the `partial` search without a
database; tests/openapi.rs fails if a JSON success response is not an
Envelope_* schema.
* README.md, docs/SKILL.md, docs/gn-auth.md, RELEASE_NOTES.md: document
the envelope and took_ms on errors.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
|
|
* tests/search_native.rs (step 8): page 2 must return the match set
from rank 11 onward, page keys must be disjoint from page 1, and a
page past the match set must be empty — origin/main's pagination
contract through the native engine, pinned before the C4 flip (his
route tests cover the forwarder path). RED-verified: breaking the
mset offset fails the window assertion; restored and green.
|
|
Composes the new main above the search engine seam:
* src/routes/search.rs (page): parsed and threaded through the seam;
the gn3 forwarder passes page to gn3 unsorted (sorted fetches the
wide first page), the native engine takes the mset window. Ranked
pages slice the sorted list, as before.
* src/routes/search.rs (add_publish_annotations): enrichment now
fills locus and abbreviation in one PublishXRef/Phenotype lookup.
* src/search/mod.rs (Engine::search): page parameter; SearchHit
gains abbreviation and pubmed_id (gn3's future fields flow via
extra, as before).
* src/db.rs (LRS_PER_LOD): 4.604 — lod shifts accordingly everywhere.
All 34 test binaries green; parity replay and shape gates pass
against the dev index with the new lod constant (grading compares
identifier sets, not lod); page disjointness, abbreviation and locus
verified live (native engine, dev index, SQL_URI set).
|
|
Lists the published traits (across groups) a publication reports.
Datasets the caller may not view are left out, using the same check as
GET /traits/{dataset} (traits.rs is_authorised is now pub(crate)).
* src/db.rs (TraitInfo, trait_info_sql): TraitInfo gains `dataset`,
`abbreviation` (Phenotype.Post_publication_abbreviation, else Pre) and
`url` (the GeneNetwork show_trait page). The three TraitInfo queries
now share one SELECT. New get_group_traits_by_abbreviation and
get_publication_traits.
* src/routes/groups.rs (group_traits): add ?abbreviation= filter.
* src/db.rs (Group), src/routes/groups.rs (groups): groups carry
`family` and `species`; add family, species and q filters.
* src/routes/search.rs (search): add `page` (gn3's page unsorted, a
page of the ranked list with `sort`); declare `pubmed_id`; hits gain
`abbreviation` next to `locus` (get_publish_annotations).
* src/db.rs (LRS_PER_LOD): LOD = LRS / 4.604, the divisor the
benchmark's RDF data uses (was 4.61).
* tests, test/python, test/data/benchmark_search.json, README.md: cover
all of the above; tests/benchmark.rs now also answers rows 11, 16, 25,
30, 34 and 37 of small_benchmark.csv, and compares LOD exactly.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
|
|
client recovers from the typed 422 by machine-repairing the query
from the error body alone. Two malformed loops (dangling AND; the
recorded mean:abc..def compound) -> assert the blessed body fields
(error.type/param/message/detail.xapian_error_type) -> derive the
fix from those fields -> resend -> 200 with recorded hits. Hermetic
(stub gn3 + stub JWKS, forwarder forced): CI-safe, no index needed.
|
|
Records all 54 shapes from the DEVELOPMENT index through the NATIVE
engine — the same parser configuration as src/search/native.rs by
construction, because it IS that engine — producing a full dev corpus in
the production recordings' format: JSON arrays of hit bodies for match
shapes, gn3-style {"error", "error_type"} diagnostic objects for the
error shapes (the typed payloads from C3.7), and [] for the surface
shapes (an empty query parses to an empty query and matches nothing,
which is what gn3 recorded for them too).
No-drift discipline: the shape table is parsed from the harness source
itself (include_str!("search_parity.rs"), a quote-aware scanner that
handles rustfmt's multi-line rows and the parenthesized Q46 query), and
the recorder FATALs on any class/outcome mismatch and on any hit
lacking the (dataset, name) strings the parity comparison — and the
committed reduce_fixtures.py — require. Env-gated on XAPIAN_DB_PATH +
GN4_DEV_CORPUS_DIR; skips loudly otherwise so hermetic runs stay green.
The corpus itself lives OUT of git at
~/spikes/port-execution-r2/dev-corpus/{full,reduced} + README.md (the
numbers are DEV-TRUTH on the 2025-02-18 public data, not production
counts — the README says so and every run's fixture_dir points at it),
like the 105 MB production full corpus.
Gate evidence (~/spikes/port-execution-r2/logs/): recording
RECORD_EXIT=0, 54/54 with per-shape dev counts printed
(devcorpus-record.log; e.g. Q01 alcohol=2330 dev vs 1197 production,
Q32 position=1, Q53 position:=1017, Q42 recorded as its typed
diagnostic); reduce via the committed reduce_fixtures.py 128,068,128 B
-> 5,237,910 B (4.1%); the DEV FLOOR as a separate report
(GN4_PARITY_FIXTURES at the reduced dev corpus, GN4_PARITY_REPORTS at
logs/dev-parity-reports; the production corpus untouched):
DEV_FLOOR_EXIT=0, 54/54 PASS, FLOOR: PASS, min J = 1.000 (clause-b over
the 26 dev shapes with >= 10 dev hits — dev-truth, not a production
count). FULL pinned cargo test --release EXIT=0 (31 suites, the
recorder skips hermetically). rustfmt --edition 2024 clean.
|
|
One commit, both halves of AMENDMENT E / the 2026-10-06 contract:
(i) The 422 invalid_query body gains the blessed typed shape. The
SearchError::InvalidQuery payload becomes {message, xapian_error_type},
threaded from every producer:
- native parser rejects (parse_query_checked): the ParseError's own
class, e.g. QueryParserError for Q51/Q52;
- the C3.4 numeric-range guard: QueryParserError ("Unknown range
operation", Q52's recorded production diagnostic);
- the C3.6 invalid-location guard: InvalidOperationError — the class
production actually threw for Q42;
- the gn3 forwarder: gn3's error_type field, with the bytes-repr leak
normalized (b'QueryParserError' -> QueryParserError — the binding-
report R1 / OPEN-16 wrapper-layer normalization), or the exception
class name itself for gn3's escaping-exception 500 bodies.
The route's engine_error builds the typed body inside the existing
ApiError envelope, under "error": {type: "invalid_query", message,
param: "query", detail: {xapian_error_type}} — the envelope's existing
fields (code, detail, ...) keep their meaning, so every current 422
(Q51/Q52 parser rejects, Q42's invalid-location class, mean:abc..def)
emits it and the harness's body["code"] grading is untouched.
The forwarder additionally maps gn3's malformed-processor-value 500s
(the escaping xapian exceptions — Q42's recorded
{"error": "InvalidOperationError", ...} body, the parity-metric
amendment's curl-verified ValueError) onto InvalidQuery, scoped to the
exception-class shape (a bare CamelCase ...Error name, or "Class:
message"): the blessed contract folds all malformed input into 422,
while prose 500 diagnostics ("gn3 exploded") keep the 502
backend_error class — pinned by both the rust and python route tests.
(ii) The harness comparator's Q42 mapping rule changes: recorded
production 500 -> expected 422 invalid_query. The recorded fixture
itself stays untouched as production truth (recorded_status 500,
served verbatim by the stub); only grade_error_class's Server500 arm
re-baselines, with its doc comments and the comparator unit tests.
Gate evidence (~/spikes/port-execution-r2/logs/c37-*): production
floor 54/54 PASS with the NEW rule — Q42 rec=500 gn4=422
code=invalid_query through the real route + forwarding engine + stub
(match200 49/49, clause-b 36/36, min J 1.000, parity-report.json
floor PASS); FULL pinned cargo test --release EXIT=0 (30 suites,
incl. the re-based comparator unit tests and the route unit tests
pinning the typed body's presence for invalid_query and absence for
backend errors); shape-class gate 52/52 unchanged; hermetic lib 23
green incl. the typed-payload assertions (Q51 message byte-identical,
QueryParserError classification). rustfmt --edition 2024 clean on all
nine touched files.
|
|
(C3.6)
gn3's species-location shorthands (search.py:246-272), WITHOUT the Hs
liftover OR-branch (OPEN-4, owner-decided; a C3.6b commit would add
it): `Hs:chr<N>:<pos>` / `Mm:...` expand to the gn3 triplet (search.py:
185-193) — AND of the species boolean term (XShuman / XSmouse), the
chromosome term (XC + chromosome number, value lowercased before the
split exactly like gn3's split_query, search.py:178-183) and the slot-2
position range (the C3.5 machinery: SI suffixes, point +/-50 kb clamp,
one-sided VALUE_GE/VALUE_LE, bases->megabases).
THE INVALID LEAF (Q42, AMENDMENT E): every condition where gn3 raises
ValueError (search.py:179-180, 197-201) — a value not splitting into
exactly chr<chromosome>:<position-spec>, a chromosome not starting
with "chr", or an unparseable position spec — emits the sentinel term
GN4InvalidLocationLeaf (verified absent from the dev index; untypeable
as free text under STEM_ALL_Z). The engine then detects the sentinel in
the parsed query's unique terms and reports SearchError::InvalidQuery
BEFORE the index is opened and any mset call — the blessed 422 for the
recorded production mset crash (Q42's 500 InvalidOperationError), via
the app-level guard (evidence-backed option (b), PORT-DESIGN C3.6,
OPEN-31 closed by AMENDMENT E). The C++ try/catch shim is deliberately
NOT extended; no crash-mimicry. An invalid leaf anywhere in the tree
poisons the whole query, exactly as gn3's mset-time OP_INVALID
rejection did (search.py:293-301 has no try/except).
Gate evidence (~/spikes/port-execution-r2/logs/c36-*): hermetic pins
green (23 lib tests: Q40/Q41 triplet forms XShuman+XC2 / XSmouse+XC1 +
slot-2 VALUE_RANGE, value lowercasing, the 7-case invalid matrix,
OR-combined poisoning, and the guard firing InvalidQuery with NO index
configured — gn3's parse-before-open order preserved); shape-CLASS
gate 52/52 cumulative vs the dev index (Q40/Q41 parse Ok with dev
count 0 — REFERENCE ONLY per AMENDMENT B; probe evidence the triplet
machinery is live: species:mouse AND chr:1 AND mb:1..200 matches, the
4.95..5.05 Mb chr1 window is genuinely empty in the 2025-02 dev data;
Q42 -> InvalidQuery); route-level scenarios: Q52 AND Q42 both
422 invalid_query through the real app with SEARCH_ENGINE=native.
rustfmt --edition 2024 clean on the touched files.
|
|
The gn3 SI-suffix FieldProcessor on slot 2 (search.py:237-241), for both
the `position` prefix and its `pos` alias, sharing one processor type
(each registration Box::leaks its own instance inside the binding; the
one-per-process parser absorbs that).
Ported faithfully from search.py:136-165:
- apply_si_suffix (136-142): trailing k/m/g (case-insensitive) multiply
by 10^3/6/9; an UNSUFFIXED value must be an integer (`int(location)`)
— `position:1.5` declines exactly where gn3 raises ValueError.
- parse_position (145-155): a `..` spec is a range with either side
optionally empty; a point expands to +/-50 000 bases clamped at 0.
- the slot-2 query (158-165): sides convert bases->megabases and keep
gn3's one-sided C++ NumberRangeProcessor semantics (VALUE_GE /
VALUE_LE for an empty side, measured identical to the bridge forms);
the degenerate both-empty range is MatchNothing (binding-report R3's
documented ("","") divergence, no production shape).
AMENDMENT A verified end-to-end: the fork's decline->MatchNothing bridge
(aa915af) is IN the dependency and behaves as documented — an
unparseable spec (`position:abc`) parses to an empty-match query and
serves 200 with 0 hits (POSABC gate row, dev index), never an <INVALID>
leaf, never a process abort; `position:abc OR alcohol` keeps its real
OR arm (xapian documents MatchNothing as boolean false). The
registration-only job was the lane's plan; no re-fixing of the library.
Q53 `position:` never reaches the processor (empty value -> free text,
recorded production 200 with 576 hits; dev reference count printed).
Gate evidence (~/spikes/port-execution-r2/logs/c35-*): hermetic pins
green (21 lib tests — slot-2 VALUE_RANGE/VALUE_GE/VALUE_LE forms, SI
case-insensitivity, point clamp, decline matrix incl. MatchNothing OR
semantics); shape-CLASS gate 49/49 cumulative vs the dev index
(Q32=1, Q33=2, Q34=1 dev gene hits at 1.05-1.06Mb/7.45-7.55Mb, Q53=1017
free-text hits, POSABC=0 — dev counts REFERENCE ONLY per AMENDMENT B).
rustfmt --edition 2024 clean on the touched files.
|
|
(C3.4)
NumberRangeProcessor on mean (slot 0), peak (1), peakmb (3), additive
(4), year (5) per search.py:234-243 (slots verified literal at
index-genenetwork:293-299); the markers carry the colon exactly like
gn3's `NumberRangeProcessor(i, prefix + ":")`.
The fork's processor parses bounds as f64 (commit 2673115, Amendment A:
the C3.4 "apply the f64 fix" workload is done at the library level) and
its bridge maps empty sides onto gn3's one-sided VALUE_LE / VALUE_GE
semantics natively — measured on the pinned toolchain before coding
(probe/, logs): `mean:10..20` -> VALUE_RANGE 0, `mean:..15` ->
VALUE_LE 0, `mean:10..` -> VALUE_GE 0. The skeleton-era 0.0/1e18
substitution is therefore superseded for these registrations by the
strictly more faithful one-sided forms.
AMENDMENT A nuance measured and handled: the fork's decline->MatchNothing
bridge (aa915af) also swallows NON-NUMERIC range bounds at the parser
level (`mean:abc..def` parses Ok to MatchNothing — probe evidence), so
the recorded production 400 "Unknown range operation" (Q52, graded 422
invalid_query) can no longer come from the parser. The engine therefore
re-checks the C++ NumberRangeProcessor contract itself (guard_numeric_
ranges): unquoted `<prefix>:` runs containing ".." must have f64-parse-
able non-empty sides, else SearchError::InvalidQuery("Unknown range
operation") before the index is opened. Residuals documented in the
guard's doc comment (inf/nan forms, the degenerate both-empty range —
binding-report R3's ("","") divergence, no production shape).
Gate evidence (~/spikes/port-execution-r2/logs/c34-*): hermetic lib pins
green incl. per-slot VALUE_RANGE/VALUE_LE/VALUE_GE parse forms (a
wrong-slot registration goes red) and the guard accept/reject matrix;
shape-CLASS gate 44/44 vs the dev index (Q28-Q31,Q35-Q39,Q44 parse Ok
with dev counts printed as REFERENCE ONLY per AMENDMENT B: mean:10..20
=1741, mean:..15=23132, peak:5..15=21857, year:2010..2020=22081, Q44
=332; Q52 -> InvalidQuery "Unknown range operation"); wide-range probe
proves slots 0/3/4/5 live on the dev index so the 0-hit shapes are
data-truth; new route-level native scenarios (tests/search_native_
route.rs) pin Q52's STATUS CLASS at the route: 422 invalid_query, with
a valid range serving 200. rustfmt --edition 2024 clean on every file
this commit touches.
|
|
full-set equality at the ENGINE seam; keep status classes, error
bodies and clause (b) top-10 at the ROUTE level (harness v2).
The route gained hits.truncate(limit) in e912c87 (documented limit
contract: default 20, cap 100), which blocked the floor at 85b63ab:
36 shapes DIFFed with rec=200/<full> gn4=200/20 missing=<full-20>.
Root cause was never the route: route-level full-set grading only ever
worked because the calibration stub serves the full recorded body
regardless of the forwarded per_page — real gn3 caps server-side.
The truncate is the route-side piece of the per_page invariant
(PORT-DESIGN §5: the engine retrieves the full match set; the route
keeps its limit logic), so set-equality moved below it, to the seam.
Match200 grading now: replay through the route exactly as before (200
check, top-10 clause (b) off the truncated response — first-ten-in-
recorded-order survives the truncate; upstream-call accounting), then
call genenetwork4::search::search(q, type, ENGINE_FETCH_LIMIT =
1_000_000) directly, in process, against the same stub gn3, and grade
the returned Vec<SearchHit> (dataset, name) identifier set against the
fixture for clause (a). A match shape now makes exactly 2 stub
requests (route + engine); error/surface shapes are unchanged.
replayed_hits reports the engine-level full-set size, so the report
line keeps its meaning (Q01: rec=200/1197 gn4=200/1197 missing=0).
Floor after the fix: 54/54 PASS — match200 49/49, clause-(b) 36/36,
min Jaccard 1.000, report written (target/parity-reports/).
Negative controls (fixture mismatch RED/restore GREEN, truncated stub
body RED/restore GREEN, top-10-breaking stub order RED/restore GREEN)
ran on this commit via a throwaway uncommitted stub hook; evidence in
~/spikes/harness-fix/HARNESS-FIX-REPORT.md and logs/.
|
|
native-search-engine.
Resolution: his route-level additions compose above the engine seam —
the handler now validates sort/order, asks the engine for
SORT_FETCH_LIMIT (1000) when ranking, maps SearchError via the seam's
engine_error, then computes lod, sorts, truncates to limit and fills
loci; lod/locus join SearchHit in src/search/mod.rs. His tests pass
through the seam.
KNOWN at this commit: the parity floor is BLOCKED (36 shapes) — the
route's new truncate(limit) exposes that route-level full-set grading
was a calibration-stub artifact (real gn3 caps at per_page; the stub
ignored it). Harness fix queued: set-equality moves to engine level,
status + top-10 stay route level. Landed together with that fix.
|
|
Checks the 30 of the 39 questions in aisearch/data/small_benchmark.csv
that the API can answer today against the benchmark's own answers:
species and group metadata, group datasets, trait metadata, and
search-based trait questions (marker, additive effect, PubMed id, mean,
LOD within 0.5%). The benchmark's LOD is LRS / 4.604, ours LRS / 4.61.
The uncovered questions are listed in the file's header comment.
* test/data/benchmark_search.json: recorded production gn3 search
responses for those questions (2026-10-07, trimmed to the relevant
hits), so the test needs no network. Database-backed checks skip when
no usable database is reachable.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
|
|
Search hits gain `lod` (lrs / 4.61) and `locus` (the peak marker name,
looked up in PublishXRef in one batched query; null when the database
is unavailable). `sort=lrs|lod` with `order=asc|desc` ranks hits: gn3
is asked for its first 1000 matches, those are ranked, then `limit`
applies.
* src/db.rs (LRS_PER_LOD, lod, get_publish_loci): add the shared
LRS-to-LOD constant and the locus lookup; TraitInfo and ProbeSetInfo
gain `lod`, computed in SQL from the same constant.
* tests/search.rs, test/python/test_search.py: add the "highest LOD,
locus marker and additive effect for serotonin in BXD male midbrain"
scenario over a recorded production fixture, plus sort/order tests.
* tests/group_trait_info.rs, tests/dataset_probeset_info.rs and their
Python mirrors: assert lod (and locus for trait 17985).
* README.md (Endpoints): document sort, order, lod and locus.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
|
|
rustfmt to the native engine code (lane round-1 files were not
rustfmt-clean; pre-existing drift in config.rs, routes/search.rs,
tests/search_engine.rs is untouched — the parked house question).
|
|
Per-strain metadata beyond genotype/phenotype data (age, sex,
treatment, etc.), backed by MariaDB CaseAttribute/CaseAttributeXRefNew.
Combines GeneNetwork3's separate /case-attribute/{id}/names and
/case-attribute/{id}/values (gn3.api.case_attributes) into one
response -- neither list is large enough on its own to need splitting.
This is the only one of GeneNetwork2/3/gn-guile with the concept at
all: GeneNetwork2 delegates to GeneNetwork3 rather than storing case
attributes itself, and gn-guile doesn't have it.
db::get_group_case_attributes returns {names: [...], values: [{strain,
case_attributes: {...}}]}; values is built by folding adjacent
(strain, attribute, value) rows (ordered by strain name) rather than
grouping afterwards, since SQL already guarantees the adjacency.
Found and fixed a real bug while verifying this live: GeneNetwork3's
own query joins CaseAttribute to CaseAttributeXRefNew on
CaseAttributeId alone, but CaseAttributeId is not unique across groups
-- it's a shared vocabulary (id 37 means "Epoch" for dozens of
unrelated groups simultaneously); the actual key is
(InbredSetId, CaseAttributeId). Confirmed against this database:
without also joining on InbredSetId, BXD's result included a spurious
"Strain": "Live" attribute belonging to a different, unrelated group.
Fixed on genenetwork4's side by adding the missing join condition.
A group with no case attributes defined returns 200 with both lists
empty, not a 404 (the group itself exists) -- verified against LXS,
a real group with zero CaseAttribute rows.
tests/group_case_attributes.rs and its Python mirror cover BXD's 4
real attributes (asserting each strain has exactly those 4, not more,
to catch the join bug above), the empty-group case, missing token, and
unknown group.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XDDpXvZBQat9uSgDeEMJ8d
|
|
All four 403-deny tests so far used UTHSC_BXD_Cochlea_0225, which was a
real non-public, non-embargoed dataset when first used as a fixture but
is now ~20 months old -- still correctly denied (under the 5-year
embargo threshold), but no longer actually tests "freshly added,
private" data specifically, only "not yet old enough to auto-expire."
Found UTHSC_BXD_2wk_Cochlea_0926 (public=1, confidentiality=1, created
2026-09-01, the most recently added ProbeSetFreeze in the database as
of this writing) and added a parallel test alongside each existing
UTHSC_BXD_Cochlea_0225 test -- dataset_probeset_info, its /values
sibling, the dataset_probesets listing, and the unified /traits
endpoint, in both Rust and Python -- confirming the deny path holds for
data that's actually less than a year old, not just data that merely
hasn't aged past 5 years yet. Verified live against the real database
before adding (is_publicly_readable's two conditions -- flags and age
-- both still correctly deny for this dataset; values/probeset data
exists for it, so the test exercises the authorization check rather
than a 404).
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XDDpXvZBQat9uSgDeEMJ8d
|