feat: add assessment, privacy and support flows

This commit is contained in:
TakuyaYagam1 committed 2026-10-08 08:08:25 +03:00
1 parent ee3738ee73
commit e4f24fa202
339 files changed
+56454 -1126

No files matched your search

@@ -0,0 +1,719 @@
-- +goose Up
-- Assessment attempts pin their product policy, category opening or separate
-- training source, and generated item variants. Candidate answers are stored
-- separately from the immutable variant and never appear in idempotency rows.
CREATE TABLE assessment_training_bank_bindings (
id uuid NOT NULL,
category text NOT NULL,
product_policy_version_id uuid NOT NULL REFERENCES policy_versions (id),
item_count integer NOT NULL,
manifest_sha256 bytea NOT NULL,
family_manifest jsonb NOT NULL,
reviewed_by text NOT NULL,
created_at timestamptz NOT NULL,
CONSTRAINT assessment_training_bank_bindings_pkey PRIMARY KEY (id),
CONSTRAINT assessment_training_bank_bindings_policy_manifest_key UNIQUE (
category, product_policy_version_id, manifest_sha256
),
CONSTRAINT assessment_training_bank_bindings_category_format CHECK (
category ~ '^[a-z][a-z0-9-]{1,47}$'
),
CONSTRAINT assessment_training_bank_bindings_item_count CHECK (
item_count BETWEEN 1 AND 20
),
CONSTRAINT assessment_training_bank_bindings_manifest_hash CHECK (
octet_length(manifest_sha256) = 32
),
CONSTRAINT assessment_training_bank_bindings_manifest_object CHECK (
jsonb_typeof(family_manifest) = 'array'
),
CONSTRAINT assessment_training_bank_bindings_reviewer CHECK (
char_length(reviewed_by) <= 128
AND reviewed_by ~ '^operator:[a-z0-9][a-z0-9._-]*$'
)
);
CREATE TABLE assessment_training_bank_binding_families (
binding_id uuid NOT NULL REFERENCES assessment_training_bank_bindings (id),
ordinal integer NOT NULL,
family_id uuid NOT NULL REFERENCES assessment_families (id),
family_key text NOT NULL,
family_version integer NOT NULL,
content_sha256 bytea NOT NULL,
CONSTRAINT assessment_training_bank_binding_families_pkey PRIMARY KEY (binding_id, ordinal),
CONSTRAINT assessment_training_bank_binding_families_family_key UNIQUE (binding_id, family_key),
CONSTRAINT assessment_training_bank_binding_families_ordinal CHECK (ordinal > 0),
CONSTRAINT assessment_training_bank_binding_families_version CHECK (family_version > 0),
CONSTRAINT assessment_training_bank_binding_families_hash CHECK (octet_length(content_sha256) = 32)
);
-- A binding is accepted only for an explicit training policy and a category
-- not already opened for real assessments. The category advisory lock is the
-- same lock taken by the bank's publish, retire, and opening operations.
-- +goose StatementBegin
CREATE FUNCTION assessment_training_binding_guard() RETURNS trigger
LANGUAGE plpgsql AS $$
DECLARE
policy_item_count integer;
current_product_policy_id uuid;
BEGIN
PERFORM pg_advisory_xact_lock(
hashtextextended('lincodex.assessment.category:' || NEW.category, 0)
);
SELECT (document #>> '{assessment,training,demo_express_item_count}')::integer
INTO policy_item_count
FROM policy_versions
WHERE id = NEW.product_policy_version_id
AND policy_key = 'product';
IF policy_item_count IS NULL OR policy_item_count <> NEW.item_count THEN
RAISE EXCEPTION USING
ERRCODE = '23514', CONSTRAINT = 'assessment_training_binding_policy',
MESSAGE = 'training binding does not match explicit product policy';
END IF;
SELECT id INTO current_product_policy_id
FROM policy_versions
WHERE policy_key = 'product' AND effective_at <= clock_timestamp()
ORDER BY version DESC
LIMIT 1;
IF current_product_policy_id IS DISTINCT FROM NEW.product_policy_version_id THEN
RAISE EXCEPTION USING
ERRCODE = '23514', CONSTRAINT = 'assessment_training_binding_current_policy',
MESSAGE = 'training binding must pin the current product policy';
END IF;
IF EXISTS (
SELECT 1 FROM assessment_category_openings WHERE category = NEW.category
) THEN
RAISE EXCEPTION USING
ERRCODE = '23514', CONSTRAINT = 'assessment_training_category_is_disjoint',
MESSAGE = 'training category already has a real opening';
END IF;
NEW.created_at := clock_timestamp();
RETURN NEW;
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER assessment_training_binding_guard
BEFORE INSERT ON assessment_training_bank_bindings
FOR EACH ROW EXECUTE FUNCTION assessment_training_binding_guard();
-- A real opening cannot consume a category reserved for training. Taking the
-- same lock in both directions closes the race between binding and opening.
-- +goose StatementBegin
CREATE FUNCTION assessment_real_opening_rejects_training_category() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
PERFORM pg_advisory_xact_lock(
hashtextextended('lincodex.assessment.category:' || NEW.category, 0)
);
IF EXISTS (
SELECT 1 FROM assessment_training_bank_bindings WHERE category = NEW.category
) THEN
RAISE EXCEPTION USING
ERRCODE = '23514', CONSTRAINT = 'assessment_training_category_is_disjoint',
MESSAGE = 'real opening cannot use a training category';
END IF;
RETURN NEW;
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER assessment_real_opening_rejects_training_category
BEFORE INSERT ON assessment_category_openings
FOR EACH ROW EXECUTE FUNCTION assessment_real_opening_rejects_training_category();
-- Each pinned training family must be reviewed, published, and in the
-- category reserved by its binding. No family row can later be replaced.
-- +goose StatementBegin
CREATE FUNCTION assessment_training_binding_family_guard() RETURNS trigger
LANGUAGE plpgsql AS $$
DECLARE
binding assessment_training_bank_bindings%ROWTYPE;
family assessment_families%ROWTYPE;
BEGIN
SELECT * INTO STRICT binding
FROM assessment_training_bank_bindings
WHERE id = NEW.binding_id;
SELECT * INTO STRICT family
FROM assessment_families
WHERE id = NEW.family_id;
IF family.category <> binding.category OR family.family_key <> NEW.family_key OR
family.version <> NEW.family_version OR family.content_sha256 <> NEW.content_sha256 OR
family.lifecycle <> 'published' OR family.review_status <> 'approved' OR
family.reviewer IS NULL OR family.author = family.reviewer THEN
RAISE EXCEPTION USING
ERRCODE = '23514', CONSTRAINT = 'assessment_training_binding_family_reviewed',
MESSAGE = 'training family is not an approved published member of the binding';
END IF;
RETURN NEW;
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER assessment_training_binding_family_guard
BEFORE INSERT ON assessment_training_bank_binding_families
FOR EACH ROW EXECUTE FUNCTION assessment_training_binding_family_guard();
-- The family rows and canonical manifest must agree when the transaction
-- commits; inserts may arrive after the binding header in the same unit.
-- +goose StatementBegin
CREATE FUNCTION assessment_training_binding_complete() RETURNS trigger
LANGUAGE plpgsql AS $$
DECLARE
binding_id_value uuid;
BEGIN
binding_id_value := NEW.id;
PERFORM assessment_training_binding_assert_complete(binding_id_value);
RETURN NULL;
END;
$$;
-- +goose StatementEnd
-- +goose StatementBegin
CREATE FUNCTION assessment_training_binding_assert_complete(binding_id_value uuid) RETURNS void
LANGUAGE plpgsql AS $$
DECLARE
expected_count integer;
actual_count integer;
actual_manifest jsonb;
family_manifest_value jsonb;
BEGIN
SELECT item_count, family_manifest INTO expected_count, family_manifest_value
FROM assessment_training_bank_bindings
WHERE id = binding_id_value;
SELECT count(*)::integer INTO actual_count
FROM assessment_training_bank_binding_families
WHERE binding_id = binding_id_value;
IF actual_count <> expected_count OR jsonb_array_length(family_manifest_value) <> expected_count THEN
RAISE EXCEPTION USING
ERRCODE = '23514', CONSTRAINT = 'assessment_training_binding_complete',
MESSAGE = 'training binding family count is incomplete';
END IF;
SELECT COALESCE(jsonb_agg(
jsonb_build_object(
'family_key', family_key,
'version', family_version,
'content_sha256', encode(content_sha256, 'hex')
) ORDER BY family_key, family_version
), '[]'::jsonb) INTO actual_manifest
FROM assessment_training_bank_binding_families
WHERE binding_id = binding_id_value;
IF actual_manifest <> family_manifest_value THEN
RAISE EXCEPTION USING
ERRCODE = '23514', CONSTRAINT = 'assessment_training_binding_manifest',
MESSAGE = 'training binding manifest does not match its families';
END IF;
END;
$$;
-- +goose StatementEnd
-- The deferred child trigger prevents an extra family from being appended
-- after the header's own deferred completeness check was queued.
-- +goose StatementBegin
CREATE FUNCTION assessment_training_binding_family_complete() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
PERFORM assessment_training_binding_assert_complete(NEW.binding_id);
RETURN NULL;
END;
$$;
-- +goose StatementEnd
CREATE CONSTRAINT TRIGGER assessment_training_binding_complete
AFTER INSERT ON assessment_training_bank_bindings
DEFERRABLE INITIALLY DEFERRED
FOR EACH ROW EXECUTE FUNCTION assessment_training_binding_complete();
CREATE CONSTRAINT TRIGGER assessment_training_binding_family_complete
AFTER INSERT ON assessment_training_bank_binding_families
DEFERRABLE INITIALLY DEFERRED
FOR EACH ROW EXECUTE FUNCTION assessment_training_binding_family_complete();
-- Bindings and their family manifest are immutable once stored.
-- +goose StatementBegin
CREATE FUNCTION assessment_training_binding_refuse_change() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
RAISE EXCEPTION USING
ERRCODE = '23000', CONSTRAINT = 'assessment_training_binding_immutable',
MESSAGE = 'training bank bindings are immutable';
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER assessment_training_binding_refuse_update_delete
BEFORE UPDATE OR DELETE ON assessment_training_bank_bindings
FOR EACH ROW EXECUTE FUNCTION assessment_training_binding_refuse_change();
CREATE TRIGGER assessment_training_binding_family_refuse_update_delete
BEFORE UPDATE OR DELETE ON assessment_training_bank_binding_families
FOR EACH ROW EXECUTE FUNCTION assessment_training_binding_refuse_change();
CREATE TABLE assessment_attempts (
id uuid NOT NULL,
user_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
kind text NOT NULL,
mode text NOT NULL,
state text NOT NULL,
outcome text,
bank_category text NOT NULL,
specialization text,
target_grade text,
task_language text,
root_attempt_id uuid NOT NULL,
product_policy_version_id uuid NOT NULL REFERENCES policy_versions (id),
product_policy_version integer NOT NULL,
grading_policy_version_id uuid REFERENCES policy_versions (id),
opening_id uuid REFERENCES assessment_category_openings (id),
opening_manifest_sha256 bytea,
training_binding_id uuid REFERENCES assessment_training_bank_bindings (id),
training_manifest_sha256 bytea,
bank_version text NOT NULL,
algorithm_version text NOT NULL,
created_at timestamptz NOT NULL,
updated_at timestamptz NOT NULL,
expires_at timestamptz NOT NULL,
chain_deadline timestamptz,
idle_timeout_seconds integer NOT NULL,
max_sessions integer NOT NULL,
sessions_used integer NOT NULL,
session_started_at timestamptz NOT NULL,
last_activity_at timestamptz NOT NULL,
version bigint NOT NULL,
ended_at timestamptz,
CONSTRAINT assessment_attempts_pkey PRIMARY KEY (id),
CONSTRAINT assessment_attempts_id_owner_key UNIQUE (id, user_id),
CONSTRAINT assessment_attempts_owner_root_fk FOREIGN KEY (root_attempt_id, user_id)
REFERENCES assessment_attempts (id, user_id) DEFERRABLE INITIALLY DEFERRED,
CONSTRAINT assessment_attempts_kind CHECK (kind IN ('root', 'corrective', 'demo_express')),
CONSTRAINT assessment_attempts_mode CHECK (mode IN ('demo_basic', 'adaptive', 'demo_express')),
CONSTRAINT assessment_attempts_state CHECK (
state IN ('in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize',
'completed', 'expired', 'insufficient_bank')
),
CONSTRAINT assessment_attempts_outcome CHECK (
outcome IS NULL OR outcome IN ('confirmed', 'not_confirmed', 'not_determined')
),
CONSTRAINT assessment_attempts_track CHECK (
(
kind IN ('root', 'corrective')
AND mode IN ('demo_basic', 'adaptive')
AND specialization IS NOT NULL
AND specialization ~ '^[a-z][a-z0-9_-]{1,47}$'
AND target_grade IS NOT NULL
AND target_grade IN ('intern', 'junior', 'middle', 'senior')
AND (task_language IS NULL OR task_language IN ('go', 'python'))
AND grading_policy_version_id IS NOT NULL
AND opening_id IS NOT NULL
AND opening_manifest_sha256 IS NOT NULL
AND octet_length(opening_manifest_sha256) = 32
AND training_binding_id IS NULL
AND training_manifest_sha256 IS NULL
AND chain_deadline IS NOT NULL
AND (
(kind = 'root' AND root_attempt_id = id)
OR (kind = 'corrective' AND root_attempt_id <> id)
)
) OR (
kind = 'demo_express'
AND mode = 'demo_express'
AND specialization IS NULL AND target_grade IS NULL AND task_language IS NULL
AND root_attempt_id = id
AND grading_policy_version_id IS NULL
AND opening_id IS NULL AND opening_manifest_sha256 IS NULL
AND training_binding_id IS NOT NULL
AND training_manifest_sha256 IS NOT NULL
AND octet_length(training_manifest_sha256) = 32
AND chain_deadline IS NULL
)
),
CONSTRAINT assessment_attempts_policy_version_positive CHECK (product_policy_version > 0),
CONSTRAINT assessment_attempts_version_positive CHECK (version > 0),
CONSTRAINT assessment_attempts_session_limits CHECK (
idle_timeout_seconds BETWEEN 60 AND 86400
AND max_sessions BETWEEN 1 AND 10
AND sessions_used BETWEEN 1 AND max_sessions
),
CONSTRAINT assessment_attempts_timestamps CHECK (
created_at <= updated_at
AND created_at <= session_started_at
AND session_started_at <= last_activity_at
AND last_activity_at <= updated_at
AND expires_at > created_at
AND (chain_deadline IS NULL OR (chain_deadline > created_at AND expires_at <= chain_deadline))
AND (ended_at IS NULL OR (ended_at >= created_at AND ended_at >= last_activity_at AND ended_at <= updated_at))
),
CONSTRAINT assessment_attempts_state_stamp CHECK (
(state IN ('in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize')
AND outcome IS NULL AND ended_at IS NULL)
OR (state IN ('expired', 'insufficient_bank') AND outcome IS NULL AND ended_at IS NOT NULL)
OR (state = 'completed' AND outcome IS NOT NULL AND ended_at IS NOT NULL)
)
);
-- A corrective attempt can only attach to an eligible terminal root owned by
-- the same candidate and for the same specialization. The application still
-- validates the full chain order and descending grades inside its transaction.
-- +goose StatementBegin
CREATE FUNCTION assessment_attempt_root_guard() RETURNS trigger
LANGUAGE plpgsql AS $$
DECLARE
root_attempt assessment_attempts%ROWTYPE;
BEGIN
IF NEW.kind <> 'corrective' THEN
RETURN NEW;
END IF;
SELECT * INTO root_attempt
FROM assessment_attempts
WHERE id = NEW.root_attempt_id
FOR SHARE;
IF NOT FOUND OR root_attempt.kind <> 'root' OR root_attempt.user_id <> NEW.user_id OR
root_attempt.specialization <> NEW.specialization OR
root_attempt.state NOT IN ('expired', 'completed') OR
(root_attempt.state = 'completed' AND root_attempt.outcome NOT IN ('not_confirmed', 'not_determined')) OR
root_attempt.chain_deadline IS NULL OR root_attempt.chain_deadline <= NEW.created_at OR
NEW.chain_deadline <> root_attempt.chain_deadline THEN
RAISE EXCEPTION USING
ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_root_eligibility',
MESSAGE = 'corrective attempt does not continue an eligible root';
END IF;
RETURN NEW;
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER assessment_attempt_root_guard
BEFORE INSERT OR UPDATE ON assessment_attempts
FOR EACH ROW EXECUTE FUNCTION assessment_attempt_root_guard();
-- Verify the row refers to the exact current, reviewed opening or separately
-- reviewed training binding chosen by the transaction-bound bank service.
-- The caller holds the category advisory lock while it resolves and inserts.
-- +goose StatementBegin
CREATE FUNCTION assessment_attempt_bank_pin_guard() RETURNS trigger
LANGUAGE plpgsql AS $$
DECLARE
pinned_category text;
pinned_product_policy_id uuid;
pinned_grading_policy_id uuid;
pinned_manifest_sha256 bytea;
current_product_policy_id uuid;
current_product_policy_version integer;
BEGIN
PERFORM pg_advisory_xact_lock(
hashtextextended('lincodex.assessment.category:' || NEW.bank_category, 0)
);
SELECT id, version INTO current_product_policy_id, current_product_policy_version
FROM policy_versions
WHERE policy_key = 'product' AND effective_at <= NEW.created_at
ORDER BY version DESC
LIMIT 1;
IF NOT FOUND OR current_product_policy_id <> NEW.product_policy_version_id OR
current_product_policy_version <> NEW.product_policy_version THEN
RAISE EXCEPTION USING
ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_product_policy_pin',
MESSAGE = 'attempt must pin the effective product policy';
END IF;
IF NEW.kind = 'demo_express' THEN
SELECT category, product_policy_version_id, manifest_sha256
INTO pinned_category, pinned_product_policy_id, pinned_manifest_sha256
FROM assessment_training_bank_bindings
WHERE id = NEW.training_binding_id;
IF NOT FOUND OR pinned_category <> NEW.bank_category OR
pinned_product_policy_id <> NEW.product_policy_version_id OR
pinned_manifest_sha256 <> NEW.training_manifest_sha256 THEN
RAISE EXCEPTION USING
ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_training_binding_pin',
MESSAGE = 'training attempt does not match its reviewed binding';
END IF;
ELSE
SELECT opening.category, opening.policy_version_id, catalog.published_manifest_sha256
INTO pinned_category, pinned_grading_policy_id, pinned_manifest_sha256
FROM assessment_category_openings AS opening
JOIN assessment_category_catalog_bindings AS catalog ON catalog.opening_id = opening.id
WHERE opening.id = NEW.opening_id
AND NOT EXISTS (
SELECT 1 FROM assessment_category_openings AS newer
WHERE newer.category = opening.category
AND (newer.opened_at, newer.id) > (opening.opened_at, opening.id)
);
IF NOT FOUND THEN
RAISE EXCEPTION USING
ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_opening_pin',
MESSAGE = 'real attempt opening is not current and reviewed';
END IF;
IF pinned_category <> NEW.bank_category OR
pinned_grading_policy_id <> NEW.grading_policy_version_id OR
pinned_manifest_sha256 <> NEW.opening_manifest_sha256 OR
current_product_policy_id IS DISTINCT FROM NEW.product_policy_version_id THEN
RAISE EXCEPTION USING
ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_opening_pin',
MESSAGE = 'real attempt does not match its current reviewed opening';
END IF;
END IF;
RETURN NEW;
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER assessment_attempt_bank_pin_guard
BEFORE INSERT ON assessment_attempts
FOR EACH ROW EXECUTE FUNCTION assessment_attempt_bank_pin_guard();
-- Commands may update lifecycle and session fields, but an attempt's owner,
-- selection, policy/bank pins, and deadlines never change after creation.
-- +goose StatementBegin
CREATE FUNCTION assessment_attempt_immutable_pins_guard() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF (to_jsonb(NEW) - 'state' - 'outcome' - 'updated_at' - 'sessions_used' -
'session_started_at' - 'last_activity_at' - 'version' - 'ended_at') IS DISTINCT FROM
(to_jsonb(OLD) - 'state' - 'outcome' - 'updated_at' - 'sessions_used' -
'session_started_at' - 'last_activity_at' - 'version' - 'ended_at') OR
NEW.version <> OLD.version + 1 OR NEW.updated_at < OLD.updated_at THEN
RAISE EXCEPTION USING
ERRCODE = '23000', CONSTRAINT = 'assessment_attempt_pins_immutable',
MESSAGE = 'assessment attempt pins are immutable and every transition increments version';
END IF;
RETURN NEW;
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER assessment_attempt_immutable_pins_guard
BEFORE UPDATE ON assessment_attempts
FOR EACH ROW EXECUTE FUNCTION assessment_attempt_immutable_pins_guard();
CREATE INDEX assessment_attempts_candidate_created_idx
ON assessment_attempts (user_id, created_at DESC, id DESC);
-- Corrective attempts belong to their root chain and share its specialization.
CREATE INDEX assessment_attempts_root_chain_idx
ON assessment_attempts (root_attempt_id, created_at, id);
-- Active work is unique per candidate and real specialization. All nonterminal
-- lifecycle states stay in the index as later commands add them.
CREATE UNIQUE INDEX assessment_attempts_one_active_real_specialization
ON assessment_attempts (user_id, specialization)
WHERE kind IN ('root', 'corrective')
AND state IN ('in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize');
CREATE UNIQUE INDEX assessment_attempts_one_active_training
ON assessment_attempts (user_id)
WHERE kind = 'demo_express'
AND state IN ('in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize');
CREATE TABLE assessment_attempt_items (
id uuid NOT NULL,
attempt_id uuid NOT NULL REFERENCES assessment_attempts (id) ON DELETE CASCADE,
ordinal integer NOT NULL,
family_id uuid NOT NULL REFERENCES assessment_families (id),
family_key text NOT NULL,
family_version integer NOT NULL,
family_content_sha256 bytea NOT NULL,
variant jsonb NOT NULL,
-- Keep canonical UTF-8 JSON bytes so schema-valid strings containing NUL
-- survive PostgreSQL storage; jsonb rejects \u0000 values.
answer bytea,
answered_at timestamptz,
CONSTRAINT assessment_attempt_items_pkey PRIMARY KEY (id),
CONSTRAINT assessment_attempt_items_ordinal_key UNIQUE (attempt_id, ordinal),
CONSTRAINT assessment_attempt_items_family_key UNIQUE (attempt_id, family_key),
CONSTRAINT assessment_attempt_items_ordinal CHECK (ordinal BETWEEN 1 AND 220),
CONSTRAINT assessment_attempt_items_family_version CHECK (family_version > 0),
CONSTRAINT assessment_attempt_items_family_hash CHECK (octet_length(family_content_sha256) = 32),
CONSTRAINT assessment_attempt_items_variant_object CHECK (
jsonb_typeof(variant) = 'object' AND octet_length(variant::text) <= 1048576
),
CONSTRAINT assessment_attempt_items_answer_bound CHECK (
answer IS NULL OR octet_length(answer) <= 524288
),
CONSTRAINT assessment_attempt_items_answer_stamp CHECK (
(answer IS NULL) = (answered_at IS NULL)
)
);
CREATE INDEX assessment_attempt_items_family_usage_idx
ON assessment_attempt_items (family_id, attempt_id);
-- A variant's identity and content are fixed at creation. Answering is a
-- one-way NULL -> value transition; replay is handled by the attempt outcome.
-- +goose StatementBegin
CREATE FUNCTION assessment_attempt_item_guard() RETURNS trigger
LANGUAGE plpgsql AS $$
DECLARE
attempt assessment_attempts%ROWTYPE;
family assessment_families%ROWTYPE;
BEGIN
IF TG_OP = 'DELETE' THEN
IF pg_trigger_depth() <= 1 THEN
RAISE EXCEPTION USING
ERRCODE = '23000', CONSTRAINT = 'assessment_attempt_item_delete_forbidden',
MESSAGE = 'assessment items can be removed only by account or attempt cascade';
END IF;
RETURN OLD;
END IF;
SELECT * INTO STRICT attempt
FROM assessment_attempts WHERE id = NEW.attempt_id;
SELECT * INTO STRICT family
FROM assessment_families WHERE id = NEW.family_id;
IF family.family_key <> NEW.family_key OR family.version <> NEW.family_version OR
family.content_sha256 <> NEW.family_content_sha256 OR family.category <> attempt.bank_category THEN
RAISE EXCEPTION USING
ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_item_family_pin',
MESSAGE = 'assessment item family pin is inconsistent';
END IF;
IF TG_OP = 'UPDATE' THEN
IF NEW.id <> OLD.id OR NEW.attempt_id <> OLD.attempt_id OR NEW.ordinal <> OLD.ordinal OR
NEW.family_id <> OLD.family_id OR NEW.family_key <> OLD.family_key OR
NEW.family_version <> OLD.family_version OR NEW.family_content_sha256 <> OLD.family_content_sha256 OR
NEW.variant <> OLD.variant OR OLD.answer IS NOT NULL OR NEW.answer IS NULL OR NEW.answered_at IS NULL THEN
RAISE EXCEPTION USING
ERRCODE = '23000', CONSTRAINT = 'assessment_attempt_item_immutable',
MESSAGE = 'assessment item identity and variant are immutable';
END IF;
IF NEW.answered_at < attempt.created_at OR NEW.answered_at >= attempt.expires_at THEN
RAISE EXCEPTION USING
ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_item_answer_time',
MESSAGE = 'assessment answer time is outside the attempt deadline';
END IF;
ELSIF TG_OP = 'INSERT' THEN
IF family.lifecycle <> 'published' OR family.review_status <> 'approved' OR
family.reviewer IS NULL OR family.author = family.reviewer THEN
RAISE EXCEPTION USING
ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_item_family_reviewed',
MESSAGE = 'assessment item family is not approved and published';
END IF;
IF attempt.kind = 'demo_express' AND NOT EXISTS (
SELECT 1
FROM assessment_training_bank_binding_families AS member
WHERE member.binding_id = attempt.training_binding_id
AND member.family_id = NEW.family_id
AND member.family_key = NEW.family_key
AND member.family_version = NEW.family_version
AND member.content_sha256 = NEW.family_content_sha256
) THEN
RAISE EXCEPTION USING
ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_item_training_member',
MESSAGE = 'training attempt item is not in its pinned binding';
END IF;
IF NEW.answer IS NOT NULL OR NEW.answered_at IS NOT NULL THEN
RAISE EXCEPTION USING
ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_item_answer_initial',
MESSAGE = 'assessment items start without candidate answers';
END IF;
END IF;
RETURN NEW;
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER assessment_attempt_item_guard
BEFORE INSERT OR UPDATE OR DELETE ON assessment_attempt_items
FOR EACH ROW EXECUTE FUNCTION assessment_attempt_item_guard();
-- Every idempotent response is a typed, allowlisted public read-model snapshot.
-- It never contains candidate answers, reference answers, seeds, family keys,
-- or private policy and opening identifiers.
CREATE TABLE assessment_attempt_idempotency_outcomes (
scope_hash bytea NOT NULL REFERENCES idempotency_records (scope_hash) ON DELETE CASCADE,
operation text NOT NULL,
status_code smallint NOT NULL,
problem_code text,
response_snapshot jsonb,
response_schema_version smallint NOT NULL DEFAULT 1,
created_at timestamptz NOT NULL,
CONSTRAINT assessment_attempt_idempotency_outcomes_pkey PRIMARY KEY (scope_hash),
CONSTRAINT assessment_attempt_idempotency_outcomes_scope_hash CHECK (octet_length(scope_hash) = 32),
CONSTRAINT assessment_attempt_idempotency_outcomes_operation CHECK (operation IN ('create', 'session')),
CONSTRAINT assessment_attempt_idempotency_outcomes_status CHECK (
(operation = 'create' AND status_code = 201 AND problem_code IS NULL AND response_snapshot IS NOT NULL)
OR (operation = 'create' AND status_code = 409 AND problem_code IS NOT NULL AND response_snapshot IS NULL)
OR (operation = 'session' AND status_code = 200 AND problem_code IS NULL AND response_snapshot IS NOT NULL)
),
CONSTRAINT assessment_attempt_idempotency_outcomes_response CHECK (
response_snapshot IS NULL OR (
jsonb_typeof(response_snapshot) = 'object'
AND octet_length(response_snapshot::text) <= 4194304
)
),
CONSTRAINT assessment_attempt_idempotency_outcomes_schema CHECK (response_schema_version = 1)
);
-- Keep committed command outcomes immutable; the generic 24-hour idempotency
-- purge may still delete them by cascading from idempotency_records.
-- +goose StatementBegin
CREATE FUNCTION assessment_attempt_idempotency_outcome_refuse_update() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
RAISE EXCEPTION USING
ERRCODE = '23000', CONSTRAINT = 'assessment_attempt_idempotency_outcome_immutable',
MESSAGE = 'assessment idempotency outcomes are immutable';
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER assessment_attempt_idempotency_outcome_refuse_update
BEFORE UPDATE ON assessment_attempt_idempotency_outcomes
FOR EACH ROW EXECUTE FUNCTION assessment_attempt_idempotency_outcome_refuse_update();
-- +goose Down
DROP TRIGGER assessment_attempt_idempotency_outcome_refuse_update ON assessment_attempt_idempotency_outcomes;
DROP FUNCTION assessment_attempt_idempotency_outcome_refuse_update();
DROP TABLE assessment_attempt_idempotency_outcomes;
DROP TRIGGER assessment_attempt_item_guard ON assessment_attempt_items;
DROP FUNCTION assessment_attempt_item_guard();
DROP TABLE assessment_attempt_items;
DROP TRIGGER assessment_attempt_root_guard ON assessment_attempts;
DROP FUNCTION assessment_attempt_root_guard();
DROP TRIGGER assessment_attempt_bank_pin_guard ON assessment_attempts;
DROP FUNCTION assessment_attempt_bank_pin_guard();
DROP TRIGGER assessment_attempt_immutable_pins_guard ON assessment_attempts;
DROP FUNCTION assessment_attempt_immutable_pins_guard();
DROP INDEX assessment_attempts_one_active_training;
DROP INDEX assessment_attempts_one_active_real_specialization;
DROP INDEX assessment_attempts_root_chain_idx;
DROP INDEX assessment_attempts_candidate_created_idx;
DROP TABLE assessment_attempts;
DROP TRIGGER assessment_training_binding_family_refuse_update_delete ON assessment_training_bank_binding_families;
DROP TRIGGER assessment_training_binding_refuse_update_delete ON assessment_training_bank_bindings;
DROP FUNCTION assessment_training_binding_refuse_change();
DROP TRIGGER assessment_training_binding_complete ON assessment_training_bank_bindings;
DROP TRIGGER assessment_training_binding_family_complete ON assessment_training_bank_binding_families;
DROP FUNCTION assessment_training_binding_complete();
DROP FUNCTION assessment_training_binding_family_complete();
DROP FUNCTION assessment_training_binding_assert_complete(uuid);
DROP TRIGGER assessment_training_binding_family_guard ON assessment_training_bank_binding_families;
DROP FUNCTION assessment_training_binding_family_guard();
DROP TRIGGER assessment_real_opening_rejects_training_category ON assessment_category_openings;
DROP FUNCTION assessment_real_opening_rejects_training_category();
DROP TRIGGER assessment_training_binding_guard ON assessment_training_bank_bindings;
DROP FUNCTION assessment_training_binding_guard();
DROP TABLE assessment_training_bank_binding_families;
DROP TABLE assessment_training_bank_bindings;
@@ -0,0 +1,385 @@
-- +goose Up
-- Account-owned support snapshots store only typed object references. The
-- referenced records stay in their own bounded authorization scopes.
CREATE SEQUENCE support_case_number_seq
AS bigint
MINVALUE 1
MAXVALUE 9999999999
NO CYCLE;
CREATE TABLE support_cases (
id uuid NOT NULL,
case_number text NOT NULL,
owner_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
case_type text NOT NULL,
status text NOT NULL,
description text NOT NULL,
object_type text,
object_id uuid,
assessment_specialization text,
assessment_grade text,
complaint_reason text,
rubric_version integer,
rubric_opening_id uuid,
rubric_policy_version_id uuid,
target_business_days integer NOT NULL,
target_due_at timestamptz NOT NULL,
target_answered_at timestamptz,
target_policy_version integer NOT NULL,
target_calendar_version integer NOT NULL,
decision_outcome text,
decision_reason text,
decision_at timestamptz,
created_at timestamptz NOT NULL,
updated_at timestamptz NOT NULL,
CONSTRAINT support_cases_pkey PRIMARY KEY (id),
CONSTRAINT support_cases_number_key UNIQUE (case_number),
CONSTRAINT support_cases_number_format CHECK (
case_number ~ '^SC-[0-9]{4}-[0-9]{6,10}$'
AND substring(case_number FROM 4 FOR 4)::integer =
EXTRACT(YEAR FROM created_at AT TIME ZONE 'UTC')::integer
),
CONSTRAINT support_cases_case_type CHECK (
case_type IN ('support', 'complaint', 'grade_appeal', 'anticheat_appeal', 'manual_assessment')
),
CONSTRAINT support_cases_status CHECK (
status IN ('submitted', 'in_review', 'waiting_for_user', 'waiting_expert', 'resolved', 'closed')
),
CONSTRAINT support_cases_description CHECK (
char_length(description) BETWEEN 1 AND 4000
),
CONSTRAINT support_cases_object_pair CHECK (
(object_type IS NULL) = (object_id IS NULL)
),
CONSTRAINT support_cases_object_type CHECK (
object_type IS NULL OR object_type IN ('assessment_attempt', 'organization', 'invitation', 'support_case')
),
CONSTRAINT support_cases_assessment_target_pair CHECK (
(assessment_specialization IS NULL) = (assessment_grade IS NULL)
),
CONSTRAINT support_cases_assessment_specialization CHECK (
assessment_specialization IS NULL OR assessment_specialization IN (
'backend', 'frontend', 'mobile', 'network_engineer', 'devops_sre',
'data_analyst', 'ds_ml', 'information_security', 'qa'
)
),
CONSTRAINT support_cases_assessment_grade CHECK (
assessment_grade IS NULL OR assessment_grade IN ('intern', 'junior', 'middle', 'senior')
),
CONSTRAINT support_cases_complaint_reason CHECK (
complaint_reason IS NULL OR complaint_reason IN (
'organization_conduct', 'offer_content', 'salary_terms_violation', 'data_disclosure', 'other'
)
),
CONSTRAINT support_cases_rubric_version CHECK (rubric_version IS NULL OR rubric_version > 0),
CONSTRAINT support_cases_rubric_opening_fkey FOREIGN KEY (rubric_opening_id)
REFERENCES assessment_category_openings (id),
CONSTRAINT support_cases_rubric_policy_version_fkey FOREIGN KEY (rubric_policy_version_id)
REFERENCES policy_versions (id),
CONSTRAINT support_cases_rubric_pin_shape CHECK (
(rubric_version IS NULL AND rubric_opening_id IS NULL AND rubric_policy_version_id IS NULL)
OR (
case_type = 'manual_assessment'
AND rubric_version IS NOT NULL
AND rubric_opening_id IS NOT NULL
AND rubric_policy_version_id IS NOT NULL
)
),
CONSTRAINT support_cases_target_values CHECK (
target_business_days BETWEEN 1 AND 60
AND target_policy_version > 0
AND target_calendar_version > 0
AND target_due_at >= created_at
AND (target_answered_at IS NULL OR target_answered_at >= created_at)
),
CONSTRAINT support_cases_decision_shape CHECK (
(decision_outcome IS NULL AND decision_reason IS NULL AND decision_at IS NULL)
OR (
decision_outcome IS NOT NULL
AND decision_outcome IN ('upheld', 'partially_upheld', 'not_upheld', 'answered', 'assessed')
AND decision_reason IS NOT NULL
AND char_length(decision_reason) BETWEEN 1 AND 4000
AND decision_at IS NOT NULL
)
),
CONSTRAINT support_cases_timestamps CHECK (
updated_at >= created_at
AND (target_answered_at IS NULL OR target_answered_at <= updated_at)
AND (decision_at IS NULL OR (decision_at >= created_at AND decision_at <= updated_at))
),
CONSTRAINT support_cases_fields_match_type CHECK (
(
case_type = 'support'
AND (complaint_reason IS NULL)
AND rubric_version IS NULL
AND assessment_specialization IS NULL
)
OR (
case_type = 'complaint'
AND object_type IS NOT NULL
AND object_type IN ('organization', 'invitation')
AND complaint_reason IS NOT NULL
AND assessment_specialization IS NULL
AND rubric_version IS NULL
AND (complaint_reason NOT IN ('offer_content', 'salary_terms_violation') OR object_type = 'invitation')
)
OR (
case_type = 'grade_appeal'
AND object_type IS NOT NULL
AND object_type IN ('assessment_attempt', 'support_case')
AND complaint_reason IS NULL
AND assessment_specialization IS NULL
AND rubric_version IS NULL
)
OR (
case_type = 'anticheat_appeal'
AND object_type IS NOT NULL
AND object_type = 'assessment_attempt'
AND complaint_reason IS NULL
AND assessment_specialization IS NULL
AND rubric_version IS NULL
)
OR (
case_type = 'manual_assessment'
AND assessment_specialization IS NOT NULL
AND complaint_reason IS NULL
AND (object_type IS NULL OR object_type = 'assessment_attempt')
)
),
CONSTRAINT support_cases_decision_matches_type CHECK (
decision_outcome IS NULL
OR (case_type = 'support' AND decision_outcome = 'answered')
OR (case_type = 'manual_assessment' AND decision_outcome = 'assessed')
OR (
case_type IN ('complaint', 'grade_appeal', 'anticheat_appeal')
AND decision_outcome IN ('upheld', 'partially_upheld', 'not_upheld')
)
),
CONSTRAINT support_cases_status_decision CHECK (
(status = 'resolved') = (decision_outcome IS NOT NULL)
)
);
-- A stored rubric pin must name the immutable current opening for the exact
-- target and the grading-policy version used by automated assessment.
-- +goose StatementBegin
CREATE FUNCTION support_cases_rubric_pin_guard() RETURNS trigger
LANGUAGE plpgsql AS $$
DECLARE
opening_policy_version_id uuid;
pinned_version integer;
BEGIN
IF NEW.rubric_version IS NULL THEN
RETURN NEW;
END IF;
SELECT opening.policy_version_id, policy.version
INTO opening_policy_version_id, pinned_version
FROM assessment_category_openings AS opening
JOIN assessment_category_catalog_bindings AS binding
ON binding.opening_id = opening.id
JOIN policy_versions AS policy
ON policy.id = opening.policy_version_id
WHERE opening.id = NEW.rubric_opening_id
AND opening.policy_version_id = NEW.rubric_policy_version_id
AND binding.specialization = NEW.assessment_specialization
AND binding.grade = NEW.assessment_grade
AND policy.policy_key = 'product'
AND NOT EXISTS (
SELECT 1
FROM assessment_category_openings AS newer
WHERE newer.category = opening.category
AND (newer.opened_at, newer.id) > (opening.opened_at, opening.id)
)
AND opening.policy_version_id = (
SELECT current_policy.id
FROM policy_versions AS current_policy
WHERE current_policy.policy_key = 'product'
AND current_policy.effective_at <= statement_timestamp()
ORDER BY current_policy.version DESC
LIMIT 1
);
IF NOT FOUND OR opening_policy_version_id IS DISTINCT FROM NEW.rubric_policy_version_id
OR pinned_version IS DISTINCT FROM NEW.rubric_version THEN
RAISE EXCEPTION USING
ERRCODE = 'check_violation', CONSTRAINT = 'support_cases_rubric_pin_consistency',
MESSAGE = 'support case rubric pin does not match its current reviewed opening';
END IF;
RETURN NEW;
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER support_cases_rubric_pin_guard
BEFORE INSERT OR UPDATE OF rubric_version, rubric_opening_id, rubric_policy_version_id,
assessment_specialization, assessment_grade, created_at
ON support_cases
FOR EACH ROW EXECUTE FUNCTION support_cases_rubric_pin_guard();
-- Rubric evidence is fixed at creation even when case status and history later
-- change.
-- +goose StatementBegin
CREATE FUNCTION support_cases_rubric_pin_immutable() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF (NEW.rubric_version, NEW.rubric_opening_id, NEW.rubric_policy_version_id)
IS DISTINCT FROM (OLD.rubric_version, OLD.rubric_opening_id, OLD.rubric_policy_version_id) THEN
RAISE EXCEPTION USING
ERRCODE = 'integrity_constraint_violation', CONSTRAINT = 'support_cases_rubric_pin_immutable',
MESSAGE = 'support case rubric pin is immutable';
END IF;
RETURN NEW;
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER support_cases_rubric_pin_immutable
BEFORE UPDATE ON support_cases
FOR EACH ROW EXECUTE FUNCTION support_cases_rubric_pin_immutable();
CREATE INDEX support_cases_owner_created_idx
ON support_cases (owner_id, created_at DESC, id DESC);
-- An appeal is once per owner, appeal type, and target regardless of outcome.
CREATE UNIQUE INDEX support_cases_one_appeal_per_target
ON support_cases (owner_id, case_type, object_type, object_id)
WHERE case_type IN ('grade_appeal', 'anticheat_appeal');
CREATE UNIQUE INDEX support_cases_one_open_manual_assessment
ON support_cases (owner_id, assessment_specialization)
WHERE case_type = 'manual_assessment' AND status NOT IN ('resolved', 'closed');
CREATE UNIQUE INDEX support_cases_one_open_complaint_per_object
ON support_cases (owner_id, object_type, object_id)
WHERE case_type = 'complaint' AND status NOT IN ('resolved', 'closed');
-- Events are the append-only public history. No staff identity, private note,
-- evidence blob, or copied object data is present in this table.
CREATE TABLE support_case_events (
case_id uuid NOT NULL REFERENCES support_cases (id) ON DELETE CASCADE,
sequence integer NOT NULL,
event_kind text NOT NULL,
actor_kind text NOT NULL,
occurred_at timestamptz NOT NULL,
status text,
message text,
CONSTRAINT support_case_events_pkey PRIMARY KEY (case_id, sequence),
CONSTRAINT support_case_events_sequence CHECK (sequence BETWEEN 1 AND 200),
CONSTRAINT support_case_events_kind CHECK (
event_kind IN ('created', 'status_changed', 'reply', 'decision')
),
CONSTRAINT support_case_events_actor CHECK (actor_kind IN ('user', 'support', 'system')),
CONSTRAINT support_case_events_status CHECK (
status IS NULL OR status IN ('submitted', 'in_review', 'waiting_for_user', 'waiting_expert', 'resolved', 'closed')
),
CONSTRAINT support_case_events_message CHECK (
message IS NULL OR (
char_length(message) BETWEEN 1 AND 4000
)
),
CONSTRAINT support_case_events_shape CHECK (
(event_kind = 'created' AND actor_kind = 'user' AND status = 'submitted' AND message IS NULL)
OR (event_kind = 'status_changed' AND actor_kind IN ('support', 'system') AND status IS NOT NULL)
OR (event_kind = 'reply' AND actor_kind IN ('user', 'support') AND status IS NULL AND message IS NOT NULL)
OR (event_kind = 'decision' AND actor_kind = 'support' AND status = 'resolved' AND message IS NOT NULL)
),
CONSTRAINT support_case_events_close_reason CHECK (
status <> 'closed' OR (event_kind = 'status_changed' AND message IS NOT NULL)
)
);
-- Prevent rewriting event history while allowing account deletion cascades.
-- +goose StatementBegin
CREATE FUNCTION support_case_events_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 = 'support_case_events_immutable',
MESSAGE = 'support case events are immutable';
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER support_case_events_refuse_update_delete
BEFORE UPDATE OR DELETE ON support_case_events
FOR EACH ROW EXECUTE FUNCTION support_case_events_refuse_change();
-- The create result lives exactly as long as its generic scoped idempotency
-- record. Its original snapshot and late flag cannot be rewritten on replay.
CREATE TABLE support_case_create_outcomes (
scope_hash bytea NOT NULL REFERENCES idempotency_records (scope_hash) ON DELETE CASCADE,
outcome_kind text NOT NULL,
case_snapshot jsonb,
target_was_late boolean,
created_at timestamptz NOT NULL,
CONSTRAINT support_case_create_outcomes_pkey PRIMARY KEY (scope_hash),
CONSTRAINT support_case_create_outcomes_scope_hash CHECK (octet_length(scope_hash) = 32),
CONSTRAINT support_case_create_outcomes_kind CHECK (
outcome_kind IN ('created', 'not_found', 'state_conflict')
),
CONSTRAINT support_case_create_outcomes_snapshot CHECK (
(
outcome_kind = 'created'
AND case_snapshot IS NOT NULL
AND jsonb_typeof(case_snapshot) = 'object'
AND octet_length(case_snapshot::text) <= 1048576
AND target_was_late IS NOT NULL
) OR (
outcome_kind IN ('not_found', 'state_conflict')
AND case_snapshot IS NULL
AND target_was_late IS NULL
)
)
);
-- A live idempotent result cannot change between the original response and a
-- replay. Expiry cleanup may still delete it through its parent record.
-- +goose StatementBegin
CREATE FUNCTION support_case_create_outcomes_refuse_update() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
RAISE EXCEPTION USING
ERRCODE = '23000', CONSTRAINT = 'support_case_create_outcomes_immutable',
MESSAGE = 'support case create outcomes are immutable';
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER support_case_create_outcomes_refuse_update
BEFORE UPDATE ON support_case_create_outcomes
FOR EACH ROW EXECUTE FUNCTION support_case_create_outcomes_refuse_update();
-- Request events retain the maximum supported 24-hour window, not merely the
-- current policy's window. Rows are pruned in small batches by each request.
CREATE TABLE support_case_request_events (
id bigint GENERATED ALWAYS AS IDENTITY,
owner_id uuid NOT NULL REFERENCES users (id) ON DELETE CASCADE,
requested_at timestamptz NOT NULL,
CONSTRAINT support_case_request_events_pkey PRIMARY KEY (id)
);
CREATE INDEX support_case_request_events_owner_time_idx
ON support_case_request_events (owner_id, requested_at, id);
-- +goose Down
DROP TABLE support_case_request_events;
DROP TRIGGER support_cases_rubric_pin_immutable ON support_cases;
DROP FUNCTION support_cases_rubric_pin_immutable();
DROP TRIGGER support_cases_rubric_pin_guard ON support_cases;
DROP FUNCTION support_cases_rubric_pin_guard();
DROP TRIGGER support_case_create_outcomes_refuse_update ON support_case_create_outcomes;
DROP FUNCTION support_case_create_outcomes_refuse_update();
DROP TABLE support_case_create_outcomes;
DROP TRIGGER support_case_events_refuse_update_delete ON support_case_events;
DROP FUNCTION support_case_events_refuse_change();
DROP TABLE support_case_events;
DROP INDEX support_cases_one_open_complaint_per_object;
DROP INDEX support_cases_one_open_manual_assessment;
DROP INDEX support_cases_one_appeal_per_target;
DROP INDEX support_cases_owner_created_idx;
DROP TABLE support_cases;
DROP SEQUENCE support_case_number_seq;
@@ -0,0 +1,97 @@
-- +goose Up
-- Store the original public create response alongside the generic
-- idempotency record. A new reservation may replace this snapshot only after
-- the 24-hour logical replay window expires; bounded purge removes it with
-- the idempotency row. The live need is intentionally not a foreign key.
-- jsonb::text adds structural whitespace, so these checks allow a bounded
-- 8 KiB representation margin after the compact application-level limits.
ALTER TABLE organization_need_versions
DROP CONSTRAINT organization_need_versions_snapshot_shape,
ADD CONSTRAINT organization_need_versions_snapshot_shape CHECK (
jsonb_typeof(snapshot) = 'object'
AND snapshot ?& ARRAY['id', 'organization_id', 'version', 'requirements_version']
AND jsonb_typeof(snapshot -> 'id') = 'string'
AND snapshot ->> 'id' = need_id::text
AND jsonb_typeof(snapshot -> 'organization_id') = 'string'
AND snapshot ->> 'organization_id' = organization_id::text
AND jsonb_typeof(snapshot -> 'version') = 'number'
AND snapshot ->> 'version' = version::text
AND jsonb_typeof(snapshot -> 'requirements_version') = 'number'
AND CASE
WHEN snapshot ->> 'requirements_version' ~ '^[0-9]+$'
THEN (snapshot ->> 'requirements_version')::bigint BETWEEN 1 AND version
ELSE FALSE
END
AND octet_length(snapshot::text) <= 270336
);
CREATE TABLE organization_need_creation_results (
scope_hash bytea NOT NULL,
snapshot jsonb NOT NULL,
CONSTRAINT organization_need_creation_results_pkey PRIMARY KEY (scope_hash),
CONSTRAINT organization_need_creation_results_idempotency_fkey FOREIGN KEY (
scope_hash
) REFERENCES idempotency_records (scope_hash) ON DELETE CASCADE,
CONSTRAINT organization_need_creation_results_scope_hash_sha256 CHECK (
octet_length(scope_hash) = 32
),
CONSTRAINT organization_need_creation_results_snapshot_bounded CHECK (
jsonb_typeof(snapshot) = 'object'
AND snapshot ?& ARRAY['need', 'readiness', 'recommendations']
AND octet_length(snapshot::text) <= 532480
)
);
-- +goose Down
-- Rolling back must not invalidate a response replay that is still within its
-- logical window, or remove historical need snapshots that the old bound
-- cannot represent. Expired replay rows may remain until bounded purge runs.
-- The idempotency lock blocks writes across the shared table, so operators
-- run this rollback with writing processes stopped.
LOCK TABLE idempotency_records IN ACCESS EXCLUSIVE MODE;
LOCK TABLE organization_need_versions IN ACCESS EXCLUSIVE MODE;
LOCK TABLE organization_need_creation_results IN ACCESS EXCLUSIVE MODE;
-- +goose StatementBegin
DO $$
BEGIN
IF EXISTS (
SELECT 1
FROM organization_need_creation_results AS result
INNER JOIN idempotency_records AS record USING (scope_hash)
WHERE record.expires_at > clock_timestamp()
) THEN
RAISE EXCEPTION 'cannot roll back migration 00026 while live need creation replays remain';
END IF;
IF EXISTS (
SELECT 1
FROM organization_need_versions
WHERE octet_length(snapshot::text) > 262144
) THEN
RAISE EXCEPTION 'cannot roll back migration 00026 while need snapshots exceed the prior storage bound';
END IF;
END
$$;
-- +goose StatementEnd
DROP TABLE organization_need_creation_results;
ALTER TABLE organization_need_versions
DROP CONSTRAINT organization_need_versions_snapshot_shape,
ADD CONSTRAINT organization_need_versions_snapshot_shape CHECK (
jsonb_typeof(snapshot) = 'object'
AND snapshot ?& ARRAY['id', 'organization_id', 'version', 'requirements_version']
AND jsonb_typeof(snapshot -> 'id') = 'string'
AND snapshot ->> 'id' = need_id::text
AND jsonb_typeof(snapshot -> 'organization_id') = 'string'
AND snapshot ->> 'organization_id' = organization_id::text
AND jsonb_typeof(snapshot -> 'version') = 'number'
AND snapshot ->> 'version' = version::text
AND jsonb_typeof(snapshot -> 'requirements_version') = 'number'
AND CASE
WHEN snapshot ->> 'requirements_version' ~ '^[0-9]+$'
THEN (snapshot ->> 'requirements_version')::bigint BETWEEN 1 AND version
ELSE FALSE
END
AND octet_length(snapshot::text) <= 262144
);
@@ -0,0 +1,64 @@
-- +goose Up
-- TASK-089 adds separately chosen opt-in groups to the anonymous card. The
-- publication and event constraints call this function, so replacing it
-- changes the accepted contract without rewriting any saved field set.
-- +goose StatementBegin
CREATE OR REPLACE FUNCTION candidate_card_fields_are_canonical(fields text []) RETURNS boolean
LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS $$
SELECT
(cardinality(fields) = 0 OR array_ndims(fields) = 1)
AND cardinality(fields) BETWEEN 0 AND 9
AND array_position(fields, NULL) IS NULL
AND fields <@ ARRAY[
'categories', 'experience', 'location', 'relocation',
'salary_compatibility', 'self_assessment', 'soft_skills',
'stack', 'work_formats'
]::text []
AND fields = ARRAY(
SELECT DISTINCT field COLLATE "C"
FROM unnest(fields) AS field
ORDER BY field COLLATE "C"
);
$$;
-- +goose StatementEnd
-- +goose Down
-- Do not strand stored publication or immutable history rows outside the old
-- contract. An operator must close/remove the newer publications through the
-- normal product workflow before this migration can be rolled back.
-- +goose StatementBegin
DO $$
BEGIN
IF EXISTS (
SELECT 1
FROM candidate_publications
WHERE fields && ARRAY['salary_compatibility', 'self_assessment', 'work_formats']::text []
) OR EXISTS (
SELECT 1
FROM candidate_privacy_events
WHERE fields && ARRAY['salary_compatibility', 'self_assessment', 'work_formats']::text []
) THEN
RAISE EXCEPTION 'candidate card opt-in fields are still referenced by publication history';
END IF;
END;
$$;
-- +goose StatementEnd
-- +goose StatementBegin
CREATE OR REPLACE FUNCTION candidate_card_fields_are_canonical(fields text []) RETURNS boolean
LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS $$
SELECT
(cardinality(fields) = 0 OR array_ndims(fields) = 1)
AND cardinality(fields) BETWEEN 0 AND 6
AND array_position(fields, NULL) IS NULL
AND fields <@ ARRAY[
'categories', 'experience', 'location', 'relocation',
'soft_skills', 'stack'
]::text []
AND fields = ARRAY(
SELECT DISTINCT field COLLATE "C"
FROM unnest(fields) AS field
ORDER BY field COLLATE "C"
);
$$;
-- +goose StatementEnd
@@ -0,0 +1,186 @@
-- +goose Up
-- Signal storage is a separate, bounded side channel. It contains only
-- client-reported timing and byte counts, never answer or clipboard content.
-- Writes take the generic idempotency scope, C3 consent row, then attempt row;
-- the event trigger's parent lock is reentrant inside that same transaction.
ALTER TABLE assessment_attempt_items
ADD CONSTRAINT assessment_attempt_items_attempt_id_id_key UNIQUE (attempt_id, id);
CREATE TABLE assessment_signal_batches (
id uuid NOT NULL,
attempt_id uuid NOT NULL REFERENCES assessment_attempts (id) ON DELETE CASCADE,
received_at timestamptz NOT NULL,
event_count integer NOT NULL,
CONSTRAINT assessment_signal_batches_pkey PRIMARY KEY (id),
CONSTRAINT assessment_signal_batches_attempt_id_id_key UNIQUE (attempt_id, id),
CONSTRAINT assessment_signal_batches_event_count CHECK (event_count BETWEEN 1 AND 50)
);
CREATE INDEX assessment_signal_batches_attempt_received_idx
ON assessment_signal_batches (attempt_id, received_at, id);
-- Direct edits and deletes would invalidate accepted receipt counts. The
-- nested delete issued by the attempt foreign-key cascade is the only delete
-- path while a batch exists.
-- +goose StatementBegin
CREATE FUNCTION assessment_signal_batch_immutable() 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 = 'assessment_signal_batches_immutable',
MESSAGE = 'assessment signal batches are immutable';
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER assessment_signal_batch_immutable
BEFORE UPDATE OR DELETE ON assessment_signal_batches
FOR EACH ROW EXECUTE FUNCTION assessment_signal_batch_immutable();
CREATE TABLE assessment_signal_events (
batch_id uuid NOT NULL,
attempt_id uuid NOT NULL,
ordinal integer NOT NULL,
item_instance_id uuid NOT NULL,
kind text NOT NULL,
occurred_at timestamptz NOT NULL,
duration_ms integer,
size_bytes integer,
CONSTRAINT assessment_signal_events_pkey PRIMARY KEY (batch_id, ordinal),
CONSTRAINT assessment_signal_events_batch_attempt_fk FOREIGN KEY (attempt_id, batch_id)
REFERENCES assessment_signal_batches (attempt_id, id) ON DELETE CASCADE,
CONSTRAINT assessment_signal_events_item_attempt_fk FOREIGN KEY (attempt_id, item_instance_id)
REFERENCES assessment_attempt_items (attempt_id, id) ON DELETE CASCADE,
CONSTRAINT assessment_signal_events_ordinal CHECK (ordinal BETWEEN 1 AND 50),
CONSTRAINT assessment_signal_events_kind CHECK (
kind IN ('focus_loss', 'copy', 'paste', 'cut', 'fullscreen_exit')
),
CONSTRAINT assessment_signal_events_measurement CHECK (
(kind = 'focus_loss' AND duration_ms IS NOT NULL AND duration_ms BETWEEN 1 AND 259200000 AND size_bytes IS NULL)
OR (kind IN ('copy', 'paste', 'cut') AND duration_ms IS NULL AND size_bytes IS NOT NULL AND size_bytes BETWEEN 0 AND 2147483647)
OR (kind = 'fullscreen_exit' AND duration_ms IS NULL AND size_bytes IS NULL)
)
);
CREATE INDEX assessment_signal_events_attempt_idx
ON assessment_signal_events (attempt_id, batch_id, ordinal);
-- Serialize capacity and lifecycle checks on the same attempt row used by the
-- usecase. The application stores a whole-batch saturated receipt before this
-- trigger is reached; the trigger is a backstop for other database writers.
-- +goose StatementBegin
CREATE FUNCTION assessment_signal_event_guard() RETURNS trigger
LANGUAGE plpgsql AS $$
DECLARE
attempt_kind text;
attempt_state text;
attempt_expires_at timestamptz;
existing_count bigint;
BEGIN
SELECT kind, state, expires_at
INTO attempt_kind, attempt_state, attempt_expires_at
FROM assessment_attempts
WHERE id = NEW.attempt_id
FOR UPDATE;
IF attempt_kind NOT IN ('root', 'corrective')
OR attempt_state NOT IN ('in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize')
OR attempt_expires_at <= clock_timestamp() THEN
RAISE EXCEPTION USING
ERRCODE = '23514', CONSTRAINT = 'assessment_signal_attempt_active',
MESSAGE = 'assessment attempt cannot accept signal events';
END IF;
SELECT count(*) INTO existing_count
FROM assessment_signal_events
WHERE attempt_id = NEW.attempt_id;
IF existing_count >= 10000 THEN
RAISE EXCEPTION USING
ERRCODE = '23514', CONSTRAINT = 'assessment_signal_attempt_capacity',
MESSAGE = 'assessment attempt signal capacity is full';
END IF;
RETURN NEW;
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER assessment_signal_event_guard
BEFORE INSERT ON assessment_signal_events
FOR EACH ROW EXECUTE FUNCTION assessment_signal_event_guard();
-- Events are immutable. Only nested foreign-key cascades may delete them.
-- +goose StatementBegin
CREATE FUNCTION assessment_signal_event_immutable() 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 = 'assessment_signal_events_immutable',
MESSAGE = 'assessment signal events are immutable';
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER assessment_signal_event_immutable
BEFORE UPDATE OR DELETE ON assessment_signal_events
FOR EACH ROW EXECUTE FUNCTION assessment_signal_event_immutable();
CREATE TABLE assessment_signal_idempotency_outcomes (
scope_hash bytea NOT NULL REFERENCES idempotency_records (scope_hash) ON DELETE CASCADE,
attempt_id uuid NOT NULL REFERENCES assessment_attempts (id) ON DELETE CASCADE,
status text NOT NULL,
accepted_events integer NOT NULL,
received_at timestamptz NOT NULL,
CONSTRAINT assessment_signal_idempotency_outcomes_pkey PRIMARY KEY (scope_hash),
CONSTRAINT assessment_signal_idempotency_outcomes_scope_hash CHECK (octet_length(scope_hash) = 32),
CONSTRAINT assessment_signal_idempotency_outcomes_status CHECK (
(status = 'accepted' AND accepted_events BETWEEN 1 AND 50)
OR (status = 'saturated' AND accepted_events = 0)
)
);
CREATE INDEX assessment_signal_idempotency_outcomes_attempt_received_idx
ON assessment_signal_idempotency_outcomes (attempt_id, received_at, scope_hash);
-- Expired scope replacement and idempotency cleanup may delete an outcome,
-- but a live response snapshot cannot be rewritten.
-- +goose StatementBegin
CREATE FUNCTION assessment_signal_idempotency_outcome_immutable() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
RAISE EXCEPTION USING
ERRCODE = '23000', CONSTRAINT = 'assessment_signal_idempotency_outcomes_immutable',
MESSAGE = 'assessment signal outcomes are immutable';
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER assessment_signal_idempotency_outcome_immutable
BEFORE UPDATE ON assessment_signal_idempotency_outcomes
FOR EACH ROW EXECUTE FUNCTION assessment_signal_idempotency_outcome_immutable();
-- +goose Down
DROP TRIGGER assessment_signal_idempotency_outcome_immutable ON assessment_signal_idempotency_outcomes;
DROP FUNCTION assessment_signal_idempotency_outcome_immutable();
DROP INDEX assessment_signal_idempotency_outcomes_attempt_received_idx;
DROP TABLE assessment_signal_idempotency_outcomes;
DROP TRIGGER assessment_signal_event_immutable ON assessment_signal_events;
DROP FUNCTION assessment_signal_event_immutable();
DROP TRIGGER assessment_signal_event_guard ON assessment_signal_events;
DROP FUNCTION assessment_signal_event_guard();
DROP INDEX assessment_signal_events_attempt_idx;
DROP TABLE assessment_signal_events;
DROP TRIGGER assessment_signal_batch_immutable ON assessment_signal_batches;
DROP FUNCTION assessment_signal_batch_immutable();
DROP INDEX assessment_signal_batches_attempt_received_idx;
DROP TABLE assessment_signal_batches;
ALTER TABLE assessment_attempt_items
DROP CONSTRAINT assessment_attempt_items_attempt_id_id_key;
@@ -0,0 +1,203 @@
-- +goose Up
-- Assessment completion supports the deliberately separate express outcome,
-- and answers/finalization store immutable public responses for key replay.
ALTER TABLE assessment_attempts
DROP CONSTRAINT assessment_attempts_outcome,
ADD CONSTRAINT assessment_attempts_outcome CHECK (
outcome IS NULL OR outcome IN ('confirmed', 'not_confirmed', 'not_determined', 'demonstration')
);
ALTER TABLE assessment_attempt_idempotency_outcomes
DROP CONSTRAINT assessment_attempt_idempotency_outcomes_operation,
DROP CONSTRAINT assessment_attempt_idempotency_outcomes_status,
ADD COLUMN pending_item_ids uuid[] NOT NULL DEFAULT '{}'::uuid[],
ADD CONSTRAINT assessment_attempt_idempotency_outcomes_operation CHECK (
operation IN ('create', 'session', 'answer', 'finalize')
),
ADD CONSTRAINT assessment_attempt_idempotency_outcomes_status CHECK (
(operation = 'create' AND status_code = 201 AND problem_code IS NULL AND response_snapshot IS NOT NULL)
OR (operation = 'create' AND status_code = 409 AND problem_code = 'state_conflict' AND response_snapshot IS NULL)
OR (operation = 'session' AND status_code = 200 AND problem_code IS NULL AND response_snapshot IS NOT NULL)
OR (operation IN ('answer', 'finalize') AND status_code = 200 AND problem_code IS NULL AND response_snapshot IS NOT NULL)
OR (operation IN ('answer', 'finalize') AND status_code = 404 AND problem_code = 'not_found' AND response_snapshot IS NULL)
OR (operation = 'answer' AND status_code = 409 AND problem_code = 'state_conflict' AND response_snapshot IS NULL AND cardinality(pending_item_ids) = 0)
OR (operation = 'finalize' AND status_code = 409 AND problem_code = 'state_conflict' AND response_snapshot IS NULL)
),
ADD CONSTRAINT assessment_attempt_idempotency_outcomes_pending_items CHECK (
cardinality(pending_item_ids) <= 220 AND array_position(pending_item_ids, NULL) IS NULL AND
(cardinality(pending_item_ids) = 0 OR (operation = 'finalize' AND status_code = 409 AND problem_code = 'state_conflict'))
);
-- A completed result is stored once with its exact score, rationale, and
-- pinned inputs. The public projection has no answer keys or submitted answers.
CREATE TABLE assessment_attempt_results (
attempt_id uuid NOT NULL,
user_id uuid NOT NULL,
result_snapshot jsonb NOT NULL,
schema_version smallint NOT NULL DEFAULT 1,
kind text NOT NULL,
mode text NOT NULL,
outcome text NOT NULL,
product_policy_version_id uuid NOT NULL REFERENCES policy_versions (id),
product_policy_version integer NOT NULL,
grading_policy_version_id uuid REFERENCES policy_versions (id),
opening_id uuid REFERENCES assessment_category_openings (id),
opening_manifest_sha256 bytea,
training_binding_id uuid REFERENCES assessment_training_bank_bindings (id),
training_manifest_sha256 bytea,
bank_version text NOT NULL,
algorithm_version text NOT NULL,
rationale_rule text NOT NULL,
pass_mark_basis_points integer,
scored_items smallint,
raw_score smallint,
pass_points smallint,
decided_at timestamptz NOT NULL,
CONSTRAINT assessment_attempt_results_pkey PRIMARY KEY (attempt_id),
CONSTRAINT assessment_attempt_results_owner_fk FOREIGN KEY (attempt_id, user_id)
REFERENCES assessment_attempts (id, user_id) ON DELETE CASCADE,
CONSTRAINT assessment_attempt_results_schema CHECK (schema_version = 1),
CONSTRAINT assessment_attempt_results_snapshot CHECK (
jsonb_typeof(result_snapshot) = 'object' AND octet_length(result_snapshot::text) <= 65536 AND
NOT (result_snapshot ?| ARRAY['answer', 'answers', 'answer_key', 'reference_answer', 'seed', 'variant', 'user_id']) AND
NOT ((result_snapshot->'attempt') ?| ARRAY['answer', 'answers', 'answer_key', 'reference_answer', 'seed', 'variant', 'user_id'])
),
CONSTRAINT assessment_attempt_results_versions CHECK (
product_policy_version > 0 AND bank_version ~ '^[A-Za-z0-9][A-Za-z0-9._-]{0,95}$' AND
algorithm_version ~ '^[A-Za-z0-9][A-Za-z0-9._-]{0,95}$'
),
CONSTRAINT assessment_attempt_results_decision CHECK (
(kind IN ('root', 'corrective') AND mode = 'demo_basic' AND outcome IN ('confirmed', 'not_confirmed')
AND rationale_rule = 'demo_basic_pass_mark'
AND grading_policy_version_id IS NOT NULL AND opening_id IS NOT NULL
AND opening_manifest_sha256 IS NOT NULL AND octet_length(opening_manifest_sha256) = 32
AND training_binding_id IS NULL AND training_manifest_sha256 IS NULL
AND pass_mark_basis_points BETWEEN 1 AND 10000
AND scored_items IS NOT NULL AND scored_items BETWEEN 1 AND 100
AND raw_score IS NOT NULL AND raw_score BETWEEN 0 AND scored_items
AND pass_points IS NOT NULL AND pass_points BETWEEN 1 AND scored_items
AND pass_points = ((scored_items * pass_mark_basis_points + 9999) / 10000)
AND ((outcome = 'confirmed') = (raw_score >= pass_points)))
OR (kind = 'demo_express' AND mode = 'demo_express' AND outcome = 'demonstration'
AND rationale_rule = 'demonstration_only'
AND grading_policy_version_id IS NULL AND opening_id IS NULL AND opening_manifest_sha256 IS NULL
AND training_binding_id IS NOT NULL AND training_manifest_sha256 IS NOT NULL
AND octet_length(training_manifest_sha256) = 32 AND pass_mark_basis_points IS NULL
AND scored_items IS NULL AND raw_score IS NULL AND pass_points IS NULL)
)
);
-- Keep the decision row bound to the completed attempt and exact pinned inputs.
-- +goose StatementBegin
CREATE FUNCTION assessment_attempt_result_guard() RETURNS trigger
LANGUAGE plpgsql AS $$
DECLARE
attempt assessment_attempts%ROWTYPE;
BEGIN
SELECT * INTO attempt
FROM assessment_attempts
WHERE id = NEW.attempt_id AND user_id = NEW.user_id
FOR SHARE;
IF NOT FOUND OR attempt.state <> 'completed' OR attempt.kind <> NEW.kind OR attempt.mode <> NEW.mode OR
attempt.outcome <> NEW.outcome OR attempt.product_policy_version_id <> NEW.product_policy_version_id OR
attempt.product_policy_version <> NEW.product_policy_version OR attempt.grading_policy_version_id IS DISTINCT FROM NEW.grading_policy_version_id OR
attempt.opening_id IS DISTINCT FROM NEW.opening_id OR attempt.opening_manifest_sha256 IS DISTINCT FROM NEW.opening_manifest_sha256 OR
attempt.training_binding_id IS DISTINCT FROM NEW.training_binding_id OR attempt.training_manifest_sha256 IS DISTINCT FROM NEW.training_manifest_sha256 OR
attempt.bank_version <> NEW.bank_version OR attempt.algorithm_version <> NEW.algorithm_version OR
attempt.ended_at IS DISTINCT FROM NEW.decided_at OR
(NEW.result_snapshot->>'outcome') IS DISTINCT FROM NEW.outcome OR
(NEW.result_snapshot->>'decided_at')::timestamptz IS DISTINCT FROM NEW.decided_at OR
(NEW.result_snapshot->'attempt'->>'id')::uuid IS DISTINCT FROM NEW.attempt_id OR
(NEW.result_snapshot->'attempt'->>'kind') IS DISTINCT FROM NEW.kind OR
(NEW.result_snapshot->'attempt'->>'mode') IS DISTINCT FROM NEW.mode OR
(NEW.result_snapshot->'pins'->>'product_policy_version_id')::uuid IS DISTINCT FROM NEW.product_policy_version_id OR
(NEW.result_snapshot->'pins'->>'product_policy_version')::integer IS DISTINCT FROM NEW.product_policy_version OR
(NEW.result_snapshot->'pins'->>'bank_version') IS DISTINCT FROM NEW.bank_version OR
(NEW.result_snapshot->'pins'->>'algorithm_version') IS DISTINCT FROM NEW.algorithm_version OR
(NEW.result_snapshot->'pins'->>'opening_id')::uuid IS DISTINCT FROM NEW.opening_id OR
decode(NEW.result_snapshot->'pins'->>'opening_manifest_sha256', 'hex') IS DISTINCT FROM NEW.opening_manifest_sha256 OR
(NEW.result_snapshot->'pins'->>'training_binding_id')::uuid IS DISTINCT FROM NEW.training_binding_id OR
decode(NEW.result_snapshot->'pins'->>'training_manifest_sha256', 'hex') IS DISTINCT FROM NEW.training_manifest_sha256 OR
(NEW.result_snapshot->'rationale'->>'rule') IS DISTINCT FROM NEW.rationale_rule OR
(NEW.kind IN ('root', 'corrective') AND (
(NEW.result_snapshot->'basic_score'->>'points')::smallint IS DISTINCT FROM NEW.raw_score OR
(NEW.result_snapshot->'basic_score'->>'max_points')::smallint IS DISTINCT FROM NEW.scored_items OR
(NEW.result_snapshot->'basic_score'->>'pass_points')::smallint IS DISTINCT FROM NEW.pass_points OR
(NEW.result_snapshot->'rationale'->>'pass_mark_basis_points')::integer IS DISTINCT FROM NEW.pass_mark_basis_points OR
(NEW.result_snapshot->'rationale'->>'scored_items')::smallint IS DISTINCT FROM NEW.scored_items OR
(NEW.result_snapshot->'rationale'->>'pass_points')::smallint IS DISTINCT FROM NEW.pass_points)) OR
(NEW.kind = 'demo_express' AND NEW.result_snapshot ? 'basic_score') THEN
RAISE EXCEPTION USING
ERRCODE = '23514', CONSTRAINT = 'assessment_attempt_result_snapshot_match',
MESSAGE = 'assessment result does not match its completed attempt';
END IF;
RETURN NEW;
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER assessment_attempt_result_guard
BEFORE INSERT ON assessment_attempt_results
FOR EACH ROW EXECUTE FUNCTION assessment_attempt_result_guard();
-- Results cannot be overwritten or deleted independently of owner deletion.
-- +goose StatementBegin
CREATE FUNCTION assessment_attempt_result_refuse_mutation() 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 = 'assessment_attempt_result_immutable',
MESSAGE = 'assessment result snapshots are immutable';
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER assessment_attempt_result_refuse_mutation
BEFORE UPDATE OR DELETE ON assessment_attempt_results
FOR EACH ROW EXECUTE FUNCTION assessment_attempt_result_refuse_mutation();
-- +goose Down
-- +goose StatementBegin
DO $$
BEGIN
IF EXISTS (
SELECT 1 FROM assessment_attempts WHERE outcome = 'demonstration'
) OR EXISTS (
SELECT 1 FROM assessment_attempt_idempotency_outcomes WHERE operation IN ('answer', 'finalize')
) OR EXISTS (
SELECT 1 FROM assessment_attempt_results
) THEN
RAISE EXCEPTION 'assessment command data uses migration 00029 and must be retained';
END IF;
END;
$$;
-- +goose StatementEnd
DROP TRIGGER assessment_attempt_result_refuse_mutation ON assessment_attempt_results;
DROP FUNCTION assessment_attempt_result_refuse_mutation();
DROP TRIGGER assessment_attempt_result_guard ON assessment_attempt_results;
DROP FUNCTION assessment_attempt_result_guard();
DROP TABLE assessment_attempt_results;
ALTER TABLE assessment_attempt_idempotency_outcomes
DROP CONSTRAINT assessment_attempt_idempotency_outcomes_status,
DROP CONSTRAINT assessment_attempt_idempotency_outcomes_operation,
DROP CONSTRAINT assessment_attempt_idempotency_outcomes_pending_items,
DROP COLUMN pending_item_ids,
ADD CONSTRAINT assessment_attempt_idempotency_outcomes_operation CHECK (operation IN ('create', 'session')),
ADD CONSTRAINT assessment_attempt_idempotency_outcomes_status CHECK (
(operation = 'create' AND status_code = 201 AND problem_code IS NULL AND response_snapshot IS NOT NULL)
OR (operation = 'create' AND status_code = 409 AND problem_code IS NOT NULL AND response_snapshot IS NULL)
OR (operation = 'session' AND status_code = 200 AND problem_code IS NULL AND response_snapshot IS NOT NULL)
);
ALTER TABLE assessment_attempts
DROP CONSTRAINT assessment_attempts_outcome,
ADD CONSTRAINT assessment_attempts_outcome CHECK (
outcome IS NULL OR outcome IN ('confirmed', 'not_confirmed', 'not_determined')
);
@@ -0,0 +1,168 @@
-- +goose Up
-- Immutable audit records for employer reads of anonymous cards and, when a
-- future grant-backed operation exists, selected contact fields. The table
-- contains identifiers and field codes only, never the viewed content.
-- +goose StatementBegin
CREATE FUNCTION candidate_card_access_fields_are_valid(kind text, field_codes text []) RETURNS boolean
LANGUAGE sql IMMUTABLE STRICT PARALLEL SAFE AS $$
SELECT
cardinality(field_codes) BETWEEN 0 AND 6
AND array_position(field_codes, NULL) IS NULL
AND field_codes = ARRAY(
SELECT DISTINCT code COLLATE "C"
FROM unnest(field_codes) AS code
ORDER BY code COLLATE "C"
)
AND (
(
kind = 'card_viewed'
AND field_codes <@ ARRAY[
'categories', 'experience', 'salary_compatibility',
'self_assessment', 'stack', 'work_formats'
]::text []
)
OR (
kind = 'contact_read'
AND cardinality(field_codes) BETWEEN 1 AND 4
AND field_codes <@ ARRAY['email', 'full_name', 'phone', 'telegram']::text []
)
);
$$;
-- +goose StatementEnd
CREATE TABLE candidate_card_access_events (
id uuid NOT NULL,
candidate_id uuid NOT NULL,
organization_id uuid NOT NULL,
actor_id uuid,
kind text NOT NULL,
field_codes text [] NOT NULL,
occurred_at timestamptz NOT NULL,
CONSTRAINT candidate_card_access_events_pkey PRIMARY KEY (id),
CONSTRAINT candidate_card_access_events_candidate_fkey FOREIGN KEY (candidate_id)
REFERENCES users (id) ON DELETE CASCADE,
CONSTRAINT candidate_card_access_events_organization_fkey FOREIGN KEY (organization_id)
REFERENCES organizations (id) ON DELETE RESTRICT,
CONSTRAINT candidate_card_access_events_actor_fkey FOREIGN KEY (actor_id)
REFERENCES users (id) ON DELETE SET NULL,
CONSTRAINT candidate_card_access_events_kind_known CHECK (
kind IN ('card_viewed', 'contact_read')
),
CONSTRAINT candidate_card_access_events_fields_valid CHECK (
candidate_card_access_fields_are_valid(kind, field_codes)
)
);
CREATE INDEX candidate_card_access_events_candidate_occurred_idx
ON candidate_card_access_events (candidate_id, occurred_at DESC, id DESC);
CREATE INDEX candidate_card_access_events_organization_occurred_idx
ON candidate_card_access_events (organization_id, occurred_at DESC, id DESC);
-- Records cannot be altered after insertion. Deletion is allowed only for
-- unverified-account cleanup; confirmed-account history remains evidence.
-- +goose StatementBegin
CREATE FUNCTION candidate_card_access_events_refuse_update() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
-- Actor deletion may anonymize the foreign key while preserving every
-- other part of the historical event.
IF pg_trigger_depth() > 1
AND OLD.actor_id IS NOT NULL
AND NEW.actor_id IS NULL
AND NEW.id IS NOT DISTINCT FROM OLD.id
AND NEW.candidate_id IS NOT DISTINCT FROM OLD.candidate_id
AND NEW.organization_id IS NOT DISTINCT FROM OLD.organization_id
AND NEW.kind IS NOT DISTINCT FROM OLD.kind
AND NEW.field_codes IS NOT DISTINCT FROM OLD.field_codes
AND NEW.occurred_at IS NOT DISTINCT FROM OLD.occurred_at THEN
RETURN NEW;
END IF;
RAISE EXCEPTION USING
ERRCODE = 'integrity_constraint_violation',
CONSTRAINT = 'candidate_card_access_events_immutable',
TABLE = 'candidate_card_access_events',
MESSAGE = 'candidate card access events are append-only';
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER candidate_card_access_events_refuse_update
BEFORE UPDATE ON candidate_card_access_events
FOR EACH ROW EXECUTE FUNCTION candidate_card_access_events_refuse_update();
-- +goose StatementBegin
CREATE FUNCTION candidate_card_access_events_refuse_delete() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF EXISTS (
SELECT 1 FROM users
WHERE users.id = OLD.candidate_id AND users.email_verified_at IS NOT NULL
) THEN
RAISE EXCEPTION USING
ERRCODE = 'integrity_constraint_violation',
CONSTRAINT = 'candidate_card_access_events_retained',
TABLE = 'candidate_card_access_events',
MESSAGE = 'candidate card access events of a confirmed account are retained';
END IF;
RETURN OLD;
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER candidate_card_access_events_refuse_delete
BEFORE DELETE ON candidate_card_access_events
FOR EACH ROW EXECUTE FUNCTION candidate_card_access_events_refuse_delete();
-- Protect a confirmed account from a direct DELETE that would otherwise
-- cascade away its access history. The unverified registration cleanup may
-- still remove those accounts and their records.
-- +goose StatementBegin
CREATE FUNCTION candidate_card_access_events_protect_account() RETURNS trigger
LANGUAGE plpgsql AS $$
BEGIN
IF OLD.email_verified_at IS NOT NULL AND EXISTS (
SELECT 1 FROM candidate_card_access_events
WHERE candidate_card_access_events.candidate_id = OLD.id
) THEN
RAISE EXCEPTION USING
ERRCODE = 'integrity_constraint_violation',
CONSTRAINT = 'candidate_card_access_events_retained',
TABLE = 'users',
MESSAGE = 'confirmed account has retained card access history';
END IF;
RETURN OLD;
END;
$$;
-- +goose StatementEnd
CREATE TRIGGER candidate_card_access_events_protect_account
BEFORE DELETE ON users
FOR EACH ROW EXECUTE FUNCTION candidate_card_access_events_protect_account();
-- +goose Down
-- Do not remove durable access evidence as a side effect of rolling back the
-- schema. Operators must export or explicitly resolve retained history first.
-- +goose StatementBegin
DO $$
BEGIN
IF EXISTS (SELECT 1 FROM candidate_card_access_events) THEN
RAISE EXCEPTION USING
ERRCODE = 'integrity_constraint_violation',
CONSTRAINT = 'candidate_card_access_events_retained',
TABLE = 'candidate_card_access_events',
MESSAGE = 'candidate card access history must be retained before rollback';
END IF;
END;
$$;
-- +goose StatementEnd
DROP TRIGGER candidate_card_access_events_protect_account ON users;
DROP FUNCTION candidate_card_access_events_protect_account();
DROP TRIGGER candidate_card_access_events_refuse_delete ON candidate_card_access_events;
DROP FUNCTION candidate_card_access_events_refuse_delete();
DROP TRIGGER candidate_card_access_events_refuse_update ON candidate_card_access_events;
DROP FUNCTION candidate_card_access_events_refuse_update();
DROP TABLE candidate_card_access_events;
DROP FUNCTION candidate_card_access_fields_are_valid(text, text []);