feat(evidence): project skill evidence from confirmed assessments

This commit is contained in:
shira committed 2026-10-09 11:25:19 +03:00
1 parent 4761508f13
commit c2a8d17195
94 files changed
+10077 -151

No files matched your search

+125
View File
@@ -0,0 +1,125 @@
package db
import (
"os"
"path/filepath"
"regexp"
"slices"
"strings"
"testing"
)
var (
evidenceTableName = regexp.MustCompile(`(?i)\bskill_evidence_(facts|skills)\b`)
// evidenceReaders are the only queries that may name the evidence tables.
evidenceReaders = []string{"ListCandidateEvidenceFacts", "ListCandidatePreviewEvidence", "ListOrganizationVisibleEvidence"}
// evidenceForbiddenSources are tables whose content must never reach the
// evidence reads: raw answers and items, results with their scores,
// attempts, signals, and the anti-cheat review band.
evidenceForbiddenSources = []string{
"assessment_attempt_results", "assessment_attempt_items", "assessment_attempts",
"assessment_attempt_reviews", "assessment_attempt_origin_marks", "assessment_answer_observations",
"assessment_answer_fingerprint_holders", "assessment_answer_family_totals",
"assessment_signal_events", "assessment_signal_batches", "assessment_signal_idempotency_outcomes",
"assessment_attempt_idempotency_outcomes", "candidate_assessment_categories",
"assessment_synthetic_category_reviews", "candidate_profile_claims", "candidate_questionnaires",
}
)
// evidenceStatements returns the statement of every query of the query files
// by name, with comments removed.
func evidenceStatements(t *testing.T) map[string]string {
t.Helper()
files, err := filepath.Glob("queries/*.sql")
if err != nil || len(files) == 0 {
t.Fatalf("list the query files = %v, %v", files, err)
}
statements := make(map[string]string)
for _, file := range files {
content, err := os.ReadFile(file)
if err != nil {
t.Fatalf("read %s: %v", file, err)
}
text := string(content)
headers := queryHeaderPattern.FindAllStringSubmatchIndex(text, -1)
for index, header := range headers {
end := len(text)
if index+1 < len(headers) {
end = headers[index+1][0]
}
statement := lineComment.ReplaceAllString(blockComment.ReplaceAllString(text[header[1]:end], ""), "")
statements[text[header[2]:header[3]]] = strings.ToLower(strings.Join(strings.Fields(statement), " "))
}
}
return statements
}
// Only the evidence reads name the projection, and the projection reads
// reach no table of raw answers, scores, failures, or anti-cheat data.
func TestEvidenceReadsNameOnlyTheProjection(t *testing.T) {
statements := evidenceStatements(t)
var found []string
for name, statement := range statements {
if evidenceTableName.MatchString(statement) {
found = append(found, name)
}
}
slices.Sort(found)
want := slices.Clone(evidenceReaders)
slices.Sort(want)
if !slices.Equal(found, want) {
t.Fatalf("queries that name the evidence tables = %v, want only %v", found, want)
}
for _, name := range evidenceReaders {
statement := statements[name]
for _, forbidden := range evidenceForbiddenSources {
if regexp.MustCompile(`\b` + forbidden + `\b`).MatchString(statement) {
t.Errorf("%s reads %s: %s", name, forbidden, statement)
}
}
}
}
// The organization read goes through the effective publication view, excludes
// the candidates that hide the organization, requires the categories field,
// and returns an allowlist of columns with no identifier.
func TestOrganizationEvidenceReadUsesTheVisibilityBarrier(t *testing.T) {
statement := evidenceStatements(t)["ListOrganizationVisibleEvidence"]
if statement == "" {
t.Fatal("the organization evidence query is missing")
}
for _, required := range []string{
"from candidate_effective_publications as effective",
"from candidate_hidden_organizations as hidden",
"not exists",
"hidden.organization_id = sqlc.arg(organization_id)",
"'categories' = any(effective.fields)",
"fact.visibility = 'visible'",
"effective.user_id = sqlc.arg(candidate_id)",
"select distinct on (skill.skill_code)",
"(skill.skill_code || '/' || fact.grade) = any(sqlc.arg(categories)::text [])",
"fact.kind = 'measurement'",
} {
if !strings.Contains(statement, required) {
t.Errorf("organization evidence query lacks %q: %s", required, statement)
}
}
selected := statement[len("select"):strings.Index(statement, " from candidate_effective_publications")]
for _, private := range []string{"fact.id", "event_id", "result_id", "candidate_id", "visibility"} {
if strings.Contains(selected, private) {
t.Errorf("organization evidence query selects %q: %s", private, selected)
}
}
// The columns are exactly the skill, the grade, the trust level, and the
// year, with the basis and calibration of the method: nothing else of the
// fact leaves.
const wantSelected = " distinct on (skill.skill_code) skill.skill_code as skill, fact.grade, fact.trust, " +
"fact.basis, fact.calibration_status, " +
"extract(year from fact.occurred_at at time zone 'utc')::integer as observed_year"
if selected != wantSelected {
t.Errorf("organization evidence query selects %q, want %q", selected, wantSelected)
}
if strings.Contains(statement, "candidate_publications") {
t.Errorf("organization evidence query reads the publication table directly: %s", statement)
}
}
@@ -0,0 +1,314 @@
-- +goose Up
-- Skill evidence is a projection of immutable assessment results. One fact is
-- one source event; the skills of that event are tags of the fact, so several
-- tags never multiply the fact. A fact is written by the database in the same
-- transaction as the result that qualifies it, and migration backfills the
-- results that already exist. The projection holds no answer, score, item,
-- failure, or anti-cheat data: reads of the evidence never touch the result,
-- attempt, or review tables.
CREATE TABLE skill_evidence_facts (
id uuid NOT NULL DEFAULT gen_random_uuid(),
candidate_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
-- A claim is a statement that nothing confirmed separately (trust 0); a
-- measurement is an observed result (trust 1 to 3). Only assessments feed
-- this table today, so every stored fact is a measurement.
kind text NOT NULL,
source_type text NOT NULL,
-- The source event and the immutable result of that event. For an
-- assessment both are the attempt, because a result is keyed by its attempt.
event_id uuid NOT NULL,
result_id uuid NOT NULL,
attribution text NOT NULL,
trust smallint NOT NULL,
-- The grade that was passed, the basis of the measurement, and its
-- calibration, copied from the category decision of the result.
grade text NOT NULL,
basis text NOT NULL,
calibration_status text NOT NULL,
occurred_at timestamptz NOT NULL,
-- The candidate may hide a fact; hiding never edits the result.
visibility text NOT NULL DEFAULT 'visible',
recorded_at timestamptz NOT NULL DEFAULT clock_timestamp(),
-- The transaction that created the fact. Tags are added only in that
-- transaction, so a stored fact is never widened afterwards.
created_txid bigint NOT NULL DEFAULT (pg_current_xact_id()::text::bigint),
CONSTRAINT skill_evidence_facts_pkey PRIMARY KEY (id),
CONSTRAINT skill_evidence_facts_event_key UNIQUE (source_type, event_id),
CONSTRAINT skill_evidence_facts_result_fk FOREIGN KEY (result_id, candidate_id)
REFERENCES assessment_attempt_results (attempt_id, user_id) ON DELETE CASCADE,
CONSTRAINT skill_evidence_facts_kind CHECK (kind IN ('claim', 'measurement')),
CONSTRAINT skill_evidence_facts_source CHECK (source_type IN ('assessment_result')),
CONSTRAINT skill_evidence_facts_attribution CHECK (attribution IN ('personal', 'team_role', 'team_unattributed')),
CONSTRAINT skill_evidence_facts_trust CHECK (
(kind = 'claim' AND trust = 0) OR (kind = 'measurement' AND trust BETWEEN 1 AND 3)
),
-- An online assessment has no proctoring, so it never reaches the level of
-- an in-person check. Level 1 is the level without a reliable identity
-- confirmation; level 2 is reserved for a result tied to a confirmed identity.
CONSTRAINT skill_evidence_facts_assessment_shape CHECK (
source_type <> 'assessment_result'
OR (kind = 'measurement' AND trust BETWEEN 1 AND 2 AND attribution = 'personal' AND event_id = result_id)
),
CONSTRAINT skill_evidence_facts_grade CHECK (grade IN ('intern', 'junior', 'middle', 'senior')),
CONSTRAINT skill_evidence_facts_basis CHECK (basis IN ('synthetic_demo')),
CONSTRAINT skill_evidence_facts_calibration CHECK (calibration_status IN ('uncalibrated')),
CONSTRAINT skill_evidence_facts_visibility CHECK (visibility IN ('visible', 'hidden'))
);
CREATE INDEX skill_evidence_facts_candidate_idx
ON skill_evidence_facts (candidate_id, occurred_at DESC, id DESC);
CREATE TABLE skill_evidence_skills (
fact_id uuid NOT NULL REFERENCES skill_evidence_facts (id) ON DELETE CASCADE,
skill_code text NOT NULL,
CONSTRAINT skill_evidence_skills_pkey PRIMARY KEY (fact_id, skill_code),
-- The specialization codes of the catalog and the closed technology
-- taxonomy of the anonymous card.
CONSTRAINT skill_evidence_skills_code CHECK (
skill_code IN (
'backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre',
'data_analyst', 'ds_ml', 'information_security', 'qa',
'go', 'postgresql', 'kafka', 'docker'
)
)
);
-- The single rule that decides which result is qualifying evidence: a real
-- (root or corrective) result of the basic mode, confirmed, and carried by a
-- reviewed category decision that either assigned the grade or left a higher
-- one in force. An express training run, a failed attempt, and a result without
-- a reviewed source never qualify.
-- +goose StatementBegin
CREATE FUNCTION skill_evidence_result_qualifies(source_result assessment_attempt_results) RETURNS boolean
LANGUAGE sql IMMUTABLE AS $$
SELECT source_result.schema_version = 2
AND source_result.kind IN ('root', 'corrective')
AND source_result.mode = 'demo_basic'
AND source_result.outcome = 'confirmed'
AND source_result.category_decision ->> 'status' IN ('assigned', 'unchanged')
$$;
-- +goose StatementEnd
-- A fact must match the immutable result it names, so no write path can store
-- evidence for an express run, a failed attempt, or another candidate.
-- +goose StatementBegin
CREATE FUNCTION skill_evidence_facts_guard_insert() RETURNS trigger
LANGUAGE plpgsql AS $$
DECLARE
source_result assessment_attempt_results%ROWTYPE;
BEGIN
SELECT * INTO source_result
FROM assessment_attempt_results
WHERE attempt_id = NEW.result_id AND user_id = NEW.candidate_id;
IF NOT FOUND OR NOT skill_evidence_result_qualifies(source_result) OR
source_result.category_decision ->> 'attempted_grade' IS DISTINCT FROM NEW.grade OR
source_result.category_decision ->> 'source' IS DISTINCT FROM NEW.basis OR
source_result.category_decision ->> 'calibration_status' IS DISTINCT FROM NEW.calibration_status OR
source_result.decided_at <> NEW.occurred_at THEN
RAISE EXCEPTION USING
ERRCODE = '23514', CONSTRAINT = 'skill_evidence_facts_source_result',
MESSAGE = 'skill evidence does not match a qualifying assessment result';
END IF;
RETURN NEW;
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER skill_evidence_facts_guard_insert
BEFORE INSERT ON skill_evidence_facts
FOR EACH ROW EXECUTE FUNCTION skill_evidence_facts_guard_insert();
-- A stored fact never changes except its visibility, and is removed only with
-- its owner or its result.
-- +goose StatementBegin
CREATE FUNCTION skill_evidence_facts_refuse_change() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP = 'DELETE' THEN
IF pg_trigger_depth() > 1 THEN
RETURN OLD;
END IF;
ELSIF ROW(
NEW.id, NEW.candidate_id, NEW.kind, NEW.source_type, NEW.event_id, NEW.result_id,
NEW.attribution, NEW.trust, NEW.grade, NEW.basis, NEW.calibration_status,
NEW.occurred_at, NEW.recorded_at, NEW.created_txid
) IS NOT DISTINCT FROM ROW(
OLD.id, OLD.candidate_id, OLD.kind, OLD.source_type, OLD.event_id, OLD.result_id,
OLD.attribution, OLD.trust, OLD.grade, OLD.basis, OLD.calibration_status,
OLD.occurred_at, OLD.recorded_at, OLD.created_txid
) THEN
RETURN NEW;
END IF;
RAISE EXCEPTION USING
ERRCODE = '23000', CONSTRAINT = 'skill_evidence_facts_immutable',
MESSAGE = 'skill evidence facts are immutable except for their visibility';
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER skill_evidence_facts_refuse_change
BEFORE UPDATE OR DELETE ON skill_evidence_facts
FOR EACH ROW EXECUTE FUNCTION skill_evidence_facts_refuse_change();
-- A fact without a skill cannot be read or matched, so the check runs at
-- commit, after the tags of the same transaction are in place. A fact that the
-- same transaction already removed needs no tag.
-- +goose StatementBegin
CREATE FUNCTION skill_evidence_facts_require_skill() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF EXISTS (SELECT 1 FROM skill_evidence_facts WHERE id = NEW.id) AND
NOT EXISTS (SELECT 1 FROM skill_evidence_skills WHERE fact_id = NEW.id) THEN
RAISE EXCEPTION USING
ERRCODE = '23514', CONSTRAINT = 'skill_evidence_facts_require_skill',
MESSAGE = 'skill evidence fact has no skill';
END IF;
RETURN NULL;
END;
$$;
-- +goose StatementEnd
CREATE CONSTRAINT TRIGGER skill_evidence_facts_require_skill
AFTER INSERT ON skill_evidence_facts
DEFERRABLE INITIALLY DEFERRED
FOR EACH ROW EXECUTE FUNCTION skill_evidence_facts_require_skill();
-- +goose StatementBegin
CREATE FUNCTION skill_evidence_skills_refuse_change() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF TG_OP = 'DELETE' AND pg_trigger_depth() > 1 THEN
RETURN OLD;
END IF;
RAISE EXCEPTION USING
ERRCODE = '23000', CONSTRAINT = 'skill_evidence_skills_immutable',
MESSAGE = 'skill evidence tags are immutable';
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER skill_evidence_skills_refuse_change
BEFORE UPDATE OR DELETE ON skill_evidence_skills
FOR EACH ROW EXECUTE FUNCTION skill_evidence_skills_refuse_change();
-- A tag joins a fact only in the transaction that created the fact: the
-- skills of an event are fixed when the event is recorded, and a later write
-- cannot widen what an organization may read about it.
-- +goose StatementBegin
CREATE FUNCTION skill_evidence_skills_require_new_fact() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF NOT EXISTS (
SELECT 1 FROM skill_evidence_facts
WHERE id = NEW.fact_id AND created_txid = pg_current_xact_id()::text::bigint
) THEN
RAISE EXCEPTION USING
ERRCODE = '23000', CONSTRAINT = 'skill_evidence_skills_fact_sealed',
MESSAGE = 'skills can only be added in the transaction that created the fact';
END IF;
RETURN NEW;
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER skill_evidence_skills_require_new_fact
BEFORE INSERT ON skill_evidence_skills
FOR EACH ROW EXECUTE FUNCTION skill_evidence_skills_require_new_fact();
-- Projects one stored result. A result that does not qualify writes nothing,
-- and a repeat writes nothing, so the function serves both the trigger and the
-- backfill. Level 1 is the trust of an online result without a reliable
-- identity confirmation.
-- +goose StatementBegin
CREATE FUNCTION skill_evidence_project_assessment_result(projected_attempt_id uuid) RETURNS void
LANGUAGE plpgsql AS $$
DECLARE
source_result assessment_attempt_results%ROWTYPE;
new_fact_id uuid;
BEGIN
SELECT * INTO source_result
FROM assessment_attempt_results
WHERE attempt_id = projected_attempt_id;
IF NOT FOUND OR NOT skill_evidence_result_qualifies(source_result) THEN
RETURN;
END IF;
INSERT INTO skill_evidence_facts (
candidate_id, kind, source_type, event_id, result_id, attribution, trust,
grade, basis, calibration_status, occurred_at
) VALUES (
source_result.user_id, 'measurement', 'assessment_result', source_result.attempt_id,
source_result.attempt_id, 'personal', 1,
source_result.category_decision ->> 'attempted_grade',
source_result.category_decision ->> 'source',
source_result.category_decision ->> 'calibration_status',
source_result.decided_at
)
ON CONFLICT (source_type, event_id) DO NOTHING
RETURNING id INTO new_fact_id;
IF new_fact_id IS NOT NULL THEN
INSERT INTO skill_evidence_skills (fact_id, skill_code)
VALUES (new_fact_id, source_result.category_decision ->> 'specialization');
END IF;
END;
$$;
-- +goose StatementEnd
-- +goose StatementBegin
CREATE FUNCTION skill_evidence_project_result_trigger() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
PERFORM skill_evidence_project_assessment_result(NEW.attempt_id);
RETURN NULL;
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER skill_evidence_project_result
AFTER INSERT ON assessment_attempt_results
FOR EACH ROW EXECUTE FUNCTION skill_evidence_project_result_trigger();
SELECT skill_evidence_project_assessment_result(attempt_id)
FROM assessment_attempt_results
ORDER BY decided_at, attempt_id;
-- +goose Down
-- The facts are a projection: the results they were derived from stay, and the
-- migration projects them again when it is applied again. Hiding a fact is the
-- candidate's own decision and cannot be derived from a result, so a rollback
-- refuses while any such decision, or any source other than an assessment
-- result, would be lost.
-- +goose StatementBegin
DO $$
BEGIN
IF EXISTS (
SELECT 1 FROM skill_evidence_facts
WHERE visibility = 'hidden' OR source_type <> 'assessment_result'
) THEN
RAISE EXCEPTION USING
ERRCODE = '23000', CONSTRAINT = 'skill_evidence_retained',
MESSAGE = 'skill evidence uses migration 00035 and must be retained';
END IF;
END;
$$;
-- +goose StatementEnd
DROP TRIGGER skill_evidence_project_result ON assessment_attempt_results;
DROP FUNCTION skill_evidence_project_result_trigger();
DROP FUNCTION skill_evidence_project_assessment_result(uuid);
DROP TRIGGER skill_evidence_skills_require_new_fact ON skill_evidence_skills;
DROP FUNCTION skill_evidence_skills_require_new_fact();
DROP TRIGGER skill_evidence_skills_refuse_change ON skill_evidence_skills;
DROP FUNCTION skill_evidence_skills_refuse_change();
DROP TRIGGER skill_evidence_facts_require_skill ON skill_evidence_facts;
DROP FUNCTION skill_evidence_facts_require_skill();
DROP TRIGGER skill_evidence_facts_refuse_change ON skill_evidence_facts;
DROP FUNCTION skill_evidence_facts_refuse_change();
DROP TRIGGER skill_evidence_facts_guard_insert ON skill_evidence_facts;
DROP FUNCTION skill_evidence_facts_guard_insert();
DROP FUNCTION skill_evidence_result_qualifies(assessment_attempt_results);
DROP TABLE skill_evidence_skills;
DROP TABLE skill_evidence_facts;
+105
View File
@@ -0,0 +1,105 @@
-- Skill evidence reads. The projection tables hold no answer, score, item,
-- failure, or anti-cheat data, and none of these statements names the result,
-- attempt, or review tables: evidence is read from its own facts only.
-- The candidate's own facts, hidden ones included, newest event first. Every
-- statement is scoped by the owner; the caller passes the continuation
-- position of the previous page, if any, and fetches one extra row.
-- name: ListCandidateEvidenceFacts :many
SELECT
fact.id,
fact.kind,
fact.source_type,
fact.event_id,
fact.result_id,
fact.attribution,
fact.trust,
fact.grade,
fact.basis,
fact.calibration_status,
fact.occurred_at,
fact.visibility,
COALESCE(
(
SELECT array_agg(skill.skill_code ORDER BY skill.skill_code)
FROM skill_evidence_skills AS skill
WHERE skill.fact_id = fact.id
),
'{}'::text []
)::text [] AS skills
FROM skill_evidence_facts AS fact
WHERE
fact.candidate_id = sqlc.arg(candidate_id)
AND (
sqlc.narg(after_occurred_at)::timestamptz IS NULL
OR (fact.occurred_at, fact.id) < (
sqlc.narg(after_occurred_at)::timestamptz,
sqlc.narg(after_id)::uuid
)
)
ORDER BY fact.occurred_at DESC, fact.id DESC
LIMIT sqlc.arg(row_limit);
-- The evidence that one organization may read about one candidate: one fact
-- for each category of the card, the fact that supports the confirmed grade
-- of that category (the earliest one that passed exactly that grade, so a
-- lower grade or a retake adds nothing). The statement selects from the
-- effective publication view (published and backed by an unrevoked C2) and
-- excludes the candidates that hide the reading organization, so no row means
-- nothing to read, whatever the reason. The card must publish the categories
-- field and only visible measurements qualify. The categories come from the
-- caller as "specialization/grade" pairs taken from the card that was just
-- projected, so the answer never names a skill the card does not show. The columns are
-- an allowlist: no identifier of the fact, the event, the result, or the
-- candidate leaves, the instant is cut to the year, and the basis and the
-- calibration (the same for every candidate) say that the fact is a synthetic
-- demonstration.
-- name: ListOrganizationVisibleEvidence :many
SELECT DISTINCT ON (skill.skill_code)
skill.skill_code AS skill,
fact.grade,
fact.trust,
fact.basis,
fact.calibration_status,
extract(YEAR FROM fact.occurred_at AT TIME ZONE 'UTC')::integer AS observed_year
FROM candidate_effective_publications AS effective
INNER JOIN skill_evidence_facts AS fact
ON effective.user_id = fact.candidate_id
INNER JOIN skill_evidence_skills AS skill
ON fact.id = skill.fact_id
WHERE
effective.user_id = sqlc.arg(candidate_id)
AND 'categories' = any(effective.fields)
AND (skill.skill_code || '/' || fact.grade) = any(sqlc.arg(categories)::text [])
AND fact.kind = 'measurement'
AND fact.visibility = 'visible'
AND NOT EXISTS (
SELECT 1
FROM candidate_hidden_organizations AS hidden
WHERE
hidden.user_id = effective.user_id
AND hidden.organization_id = sqlc.arg(organization_id)
)
ORDER BY skill.skill_code, fact.occurred_at, fact.id;
-- The same selection for the candidate's own card preview, so the candidate
-- sees what an organization would read. It is scoped by the owner and runs
-- after the caller locked the effective C2 and publication; it does not apply
-- an organization or a cohort.
-- name: ListCandidatePreviewEvidence :many
SELECT DISTINCT ON (skill.skill_code)
skill.skill_code AS skill,
fact.grade,
fact.trust,
fact.basis,
fact.calibration_status,
extract(YEAR FROM fact.occurred_at AT TIME ZONE 'UTC')::integer AS observed_year
FROM skill_evidence_facts AS fact
INNER JOIN skill_evidence_skills AS skill
ON fact.id = skill.fact_id
WHERE
fact.candidate_id = sqlc.arg(candidate_id)
AND (skill.skill_code || '/' || fact.grade) = any(sqlc.arg(categories)::text [])
AND fact.kind = 'measurement'
AND fact.visibility = 'visible'
ORDER BY skill.skill_code, fact.occurred_at, fact.id;