feat: add assessment, privacy and support flows
This commit is contained in:
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 []);
|
||||
@@ -11,24 +11,28 @@ import (
|
||||
|
||||
// directPublicationReaders are the only queries that may name the table
|
||||
// candidate_publications. The first three are the candidate's own settings
|
||||
// queries; every read on behalf of an organization must go through the view
|
||||
// candidate_effective_publications (published and backed by an unrevoked C2)
|
||||
// and exclude the hidden organizations, as ReadPublicationVisibleToOrganization
|
||||
// does. A new query that reads the table directly fails this test, so it
|
||||
// cannot leak a closed or revoked publication by accident.
|
||||
// queries; the remaining reads are narrowly scoped lock/recheck operations
|
||||
// that require current C2. Organization reads also exclude hidden
|
||||
// organizations, and candidate preview reads remain owner-scoped. A new
|
||||
// query that reads the table directly fails this test until it is reviewed.
|
||||
//
|
||||
// Only queries/*.sql are covered: the project keeps SQL in sqlc queries and
|
||||
// migrations, and the standards forbid raw SQL in Go code.
|
||||
var directPublicationReaders = []string{
|
||||
"ReadCandidatePrivacySettings",
|
||||
"ReadCandidatePublication",
|
||||
"InsertCandidatePublication",
|
||||
"UpdateCandidatePublication",
|
||||
}
|
||||
|
||||
var ownerScopedPublicationQueries = []string{
|
||||
"LockPublicationForCandidatePreview",
|
||||
"LockVisiblePublicationForView",
|
||||
"LockCandidatePublicationForConsentRevocation",
|
||||
}
|
||||
|
||||
var ownerPreviewQueries = []string{"ReadCandidateViewSourceForPreview"}
|
||||
|
||||
var (
|
||||
// sqlc accepts both comment forms and tolerates trailing whitespace.
|
||||
queryHeaderPattern = regexp.MustCompile(`(?m)^(?:--|/\*)[ \t]*name:[ \t]+(\w+)[ \t]+:\w+[ \t]*(?:\*/)?[ \t]*$`)
|
||||
@@ -66,11 +70,11 @@ func TestOnlyTheSettingsQueriesReadThePublicationTableDirectly(t *testing.T) {
|
||||
// Comments may name the table; statements may not.
|
||||
statement := lineComment.ReplaceAllString(blockComment.ReplaceAllString(text[header[1]:end], ""), "")
|
||||
name := text[header[2]:header[3]]
|
||||
statements[name] = strings.Join(strings.Fields(statement), " ")
|
||||
if publicationTableName.MatchString(statement) {
|
||||
found = append(found, name)
|
||||
statements[name] = strings.Join(strings.Fields(statement), " ")
|
||||
}
|
||||
if effectiveViewName.MatchString(statement) && !hiddenTableName.MatchString(statement) {
|
||||
if effectiveViewName.MatchString(statement) && !hiddenTableName.MatchString(statement) && !slices.Contains(ownerPreviewQueries, name) {
|
||||
t.Errorf("%s reads candidate_effective_publications without excluding candidate_hidden_organizations", name)
|
||||
}
|
||||
}
|
||||
@@ -81,9 +85,6 @@ func TestOnlyTheSettingsQueriesReadThePublicationTableDirectly(t *testing.T) {
|
||||
if !slices.Equal(found, want) {
|
||||
t.Fatalf("queries that name candidate_publications = %v, want only settings queries and owner-scoped consent revocation: %v", found, want)
|
||||
}
|
||||
if strings.Contains(strings.Join(found, ","), "Visible") {
|
||||
t.Fatal("the organization-facing read names the table directly")
|
||||
}
|
||||
closeQuery := strings.ToLower(statements["LockCandidatePublicationForConsentRevocation"])
|
||||
for _, required := range []string{
|
||||
"select greatest(candidate_publications.published_at, consent_records.revoked_at)",
|
||||
@@ -100,7 +101,53 @@ func TestOnlyTheSettingsQueriesReadThePublicationTableDirectly(t *testing.T) {
|
||||
t.Errorf("consent revocation query lacks %q: %s", required, closeQuery)
|
||||
}
|
||||
}
|
||||
settingsQuery := strings.ToLower(statements["ReadCandidatePrivacySettings"])
|
||||
for _, required := range []string{
|
||||
"users.id = sqlc.arg(user_id)",
|
||||
"left join candidate_publications",
|
||||
"left join consent_records",
|
||||
"left join candidate_search_statuses",
|
||||
"from candidate_hidden_organizations",
|
||||
} {
|
||||
if !strings.Contains(settingsQuery, required) {
|
||||
t.Errorf("candidate settings query lacks %q: %s", required, settingsQuery)
|
||||
}
|
||||
}
|
||||
for _, forbidden := range []string{"candidate_profiles", "profile_claims", "candidate_questionnaires", "contact_email", "contact_phone"} {
|
||||
if strings.Contains(settingsQuery, forbidden) {
|
||||
t.Errorf("candidate settings query reaches private profile data %q: %s", forbidden, settingsQuery)
|
||||
}
|
||||
}
|
||||
if strings.Contains(closeQuery, "update candidate_publications") || strings.Contains(closeQuery, "set state = 'closed'") {
|
||||
t.Fatalf("consent revocation query rewrites the stored publication instead of preserving its ledger link: %s", closeQuery)
|
||||
}
|
||||
previewQuery := strings.ToLower(statements["ReadCandidateViewSourceForPreview"])
|
||||
for _, required := range []string{
|
||||
"from candidate_effective_publications as effective",
|
||||
"where effective.user_id = sqlc.arg(candidate_id)",
|
||||
"claim.kind in ('stack', 'role', 'experience')",
|
||||
"coalesce(questionnaire.work_formats, '{}'::text[])",
|
||||
} {
|
||||
if !strings.Contains(previewQuery, required) {
|
||||
t.Errorf("owner preview query lacks %q: %s", required, previewQuery)
|
||||
}
|
||||
}
|
||||
visibleLock := strings.ToLower(statements["LockVisiblePublicationForView"])
|
||||
for _, required := range []string{
|
||||
"candidate_publications.user_id = sqlc.arg(candidate_id)",
|
||||
"candidate_publications.state = 'published'",
|
||||
"candidate_publications.consent_record_id = sqlc.arg(consent_record_id)",
|
||||
"consent_records.purpose = 'c2'",
|
||||
"consent_records.revoked_at is null",
|
||||
"candidate_hidden_organizations",
|
||||
"for share of candidate_publications, consent_records",
|
||||
} {
|
||||
if !strings.Contains(visibleLock, required) {
|
||||
t.Errorf("organization card lock lacks %q: %s", required, visibleLock)
|
||||
}
|
||||
}
|
||||
visibleSource := strings.ToLower(statements["ListVisibleCandidateViewSources"])
|
||||
if !effectiveViewName.MatchString(visibleSource) || !hiddenTableName.MatchString(visibleSource) {
|
||||
t.Errorf("organization cohort source must use the effective publication view and hidden-organization filter: %s", visibleSource)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,449 @@
|
||||
-- Finds candidate-requested selections across currently opened categories.
|
||||
-- The adapter validates policy and manifest freshness, locks the category,
|
||||
-- then runs this query again before it returns any pinned families.
|
||||
-- name: ResolveCurrentAssessmentSelection :many
|
||||
WITH current_openings AS (
|
||||
SELECT DISTINCT ON (category)
|
||||
id,
|
||||
category,
|
||||
policy_version_id,
|
||||
required_families
|
||||
FROM assessment_category_openings
|
||||
ORDER BY category, opened_at DESC, id DESC
|
||||
), current_policy AS (
|
||||
SELECT id, version
|
||||
FROM policy_versions
|
||||
WHERE policy_key = 'product' AND effective_at <= statement_timestamp()
|
||||
ORDER BY version DESC
|
||||
LIMIT 1
|
||||
)
|
||||
SELECT
|
||||
opening.id AS opening_id,
|
||||
opening.category,
|
||||
opening.policy_version_id,
|
||||
opening.required_families,
|
||||
COALESCE((
|
||||
SELECT count(DISTINCT family.family_key)::integer
|
||||
FROM assessment_families AS family
|
||||
WHERE family.category = opening.category AND family.lifecycle = 'published'
|
||||
), 0)::integer AS published_count,
|
||||
policy.id AS effective_policy_id,
|
||||
policy.version AS effective_policy_version,
|
||||
binding.specialization,
|
||||
binding.grade,
|
||||
binding.task_languages,
|
||||
binding.published_manifest_sha256,
|
||||
COALESCE((
|
||||
SELECT jsonb_agg(
|
||||
jsonb_build_object(
|
||||
'family_key', family.family_key,
|
||||
'version', family.version,
|
||||
'content_sha256', encode(family.content_sha256, 'hex')
|
||||
) ORDER BY family.family_key, family.version
|
||||
)
|
||||
FROM assessment_families AS family
|
||||
WHERE family.category = opening.category AND family.lifecycle = 'published'
|
||||
), '[]'::jsonb)::text AS published_manifest
|
||||
FROM current_openings AS opening
|
||||
JOIN assessment_category_catalog_bindings AS binding
|
||||
ON binding.opening_id = opening.id
|
||||
LEFT JOIN current_policy AS policy ON true
|
||||
WHERE binding.specialization = sqlc.arg(specialization)
|
||||
AND binding.grade = sqlc.arg(grade)
|
||||
AND (
|
||||
(sqlc.narg(task_language)::text IS NULL AND cardinality(binding.task_languages) = 0)
|
||||
OR sqlc.narg(task_language)::text = ANY(binding.task_languages)
|
||||
)
|
||||
ORDER BY opening.category;
|
||||
|
||||
-- Serializes root quota checks for one candidate before taking its optional
|
||||
-- specialization or training lock. All callers acquire these locks in order.
|
||||
-- name: LockAssessmentAttemptScope :exec
|
||||
WITH candidate_lock AS MATERIALIZED (
|
||||
SELECT pg_advisory_xact_lock(hashtextextended(
|
||||
'lincodex.assessment.attempt:user:' || sqlc.arg(user_id)::text,
|
||||
0
|
||||
))
|
||||
)
|
||||
SELECT pg_advisory_xact_lock(hashtextextended(
|
||||
'lincodex.assessment.attempt:track:' || sqlc.arg(user_id)::text || ':' ||
|
||||
COALESCE(sqlc.narg(specialization)::text, 'training'),
|
||||
0
|
||||
))
|
||||
FROM candidate_lock;
|
||||
|
||||
-- Locks the active real attempt after LockAssessmentAttemptScope.
|
||||
-- name: GetActiveAssessmentAttemptForSpecialization :one
|
||||
SELECT
|
||||
id, user_id, kind, mode, state, outcome, bank_category, specialization,
|
||||
target_grade, task_language, root_attempt_id, product_policy_version_id,
|
||||
product_policy_version, grading_policy_version_id, opening_id,
|
||||
opening_manifest_sha256, training_binding_id, training_manifest_sha256,
|
||||
bank_version, algorithm_version, created_at, updated_at, expires_at,
|
||||
chain_deadline, idle_timeout_seconds, max_sessions, sessions_used,
|
||||
session_started_at, last_activity_at, version, ended_at
|
||||
FROM assessment_attempts
|
||||
WHERE user_id = sqlc.arg(user_id)
|
||||
AND specialization = sqlc.arg(specialization)
|
||||
AND kind IN ('root', 'corrective')
|
||||
AND state IN ('in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize')
|
||||
ORDER BY created_at DESC, id DESC
|
||||
LIMIT 1
|
||||
FOR UPDATE;
|
||||
|
||||
-- Locks the one active express attempt after LockAssessmentAttemptScope.
|
||||
-- name: GetActiveTrainingAssessmentAttempt :one
|
||||
SELECT
|
||||
id, user_id, kind, mode, state, outcome, bank_category, specialization,
|
||||
target_grade, task_language, root_attempt_id, product_policy_version_id,
|
||||
product_policy_version, grading_policy_version_id, opening_id,
|
||||
opening_manifest_sha256, training_binding_id, training_manifest_sha256,
|
||||
bank_version, algorithm_version, created_at, updated_at, expires_at,
|
||||
chain_deadline, idle_timeout_seconds, max_sessions, sessions_used,
|
||||
session_started_at, last_activity_at, version, ended_at
|
||||
FROM assessment_attempts
|
||||
WHERE user_id = sqlc.arg(user_id)
|
||||
AND kind = 'demo_express'
|
||||
AND state IN ('in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize')
|
||||
ORDER BY created_at DESC, id DESC
|
||||
LIMIT 1
|
||||
FOR UPDATE;
|
||||
|
||||
-- Reads the latest root in a specialization, optionally restricted to grade.
|
||||
-- name: GetLatestRootAssessmentAttempt :one
|
||||
SELECT
|
||||
attempt.id, attempt.user_id, attempt.kind, attempt.mode, attempt.state, attempt.outcome,
|
||||
attempt.bank_category, attempt.specialization, attempt.target_grade, attempt.task_language,
|
||||
attempt.root_attempt_id, attempt.product_policy_version_id, attempt.product_policy_version,
|
||||
attempt.grading_policy_version_id, attempt.opening_id, attempt.opening_manifest_sha256,
|
||||
attempt.training_binding_id, attempt.training_manifest_sha256, attempt.bank_version,
|
||||
attempt.algorithm_version, attempt.created_at, attempt.updated_at, attempt.expires_at,
|
||||
attempt.chain_deadline, attempt.idle_timeout_seconds, attempt.max_sessions, attempt.sessions_used,
|
||||
attempt.session_started_at, attempt.last_activity_at, attempt.version, attempt.ended_at
|
||||
FROM assessment_attempts AS attempt
|
||||
LEFT JOIN assessment_attempt_results AS result
|
||||
ON result.attempt_id = attempt.id AND result.user_id = attempt.user_id
|
||||
WHERE attempt.user_id = sqlc.arg(user_id)
|
||||
AND attempt.specialization = sqlc.arg(specialization)
|
||||
AND attempt.kind = 'root'
|
||||
AND (sqlc.narg(target_grade)::text IS NULL OR attempt.target_grade = sqlc.narg(target_grade)::text)
|
||||
AND attempt.state <> 'insufficient_bank'
|
||||
AND COALESCE(result.result_snapshot->>'not_determined_reason', '')
|
||||
NOT IN ('insufficient_bank', 'sandbox_unavailable')
|
||||
ORDER BY attempt.created_at DESC, attempt.id DESC
|
||||
LIMIT 1
|
||||
FOR SHARE OF attempt;
|
||||
|
||||
-- Counts root attempts only; the caller applies the effective policy's
|
||||
-- configured window and the product's approved accounting scope.
|
||||
-- name: CountRootAssessmentAttemptsSince :one
|
||||
SELECT count(*)::bigint
|
||||
FROM assessment_attempts AS attempt
|
||||
LEFT JOIN assessment_attempt_results AS result
|
||||
ON result.attempt_id = attempt.id AND result.user_id = attempt.user_id
|
||||
WHERE attempt.user_id = sqlc.arg(user_id)
|
||||
AND attempt.kind = 'root'
|
||||
AND attempt.created_at >= sqlc.arg(since)::timestamptz
|
||||
AND (sqlc.narg(specialization)::text IS NULL OR attempt.specialization = sqlc.narg(specialization)::text)
|
||||
AND attempt.state <> 'insufficient_bank'
|
||||
AND COALESCE(result.result_snapshot->>'not_determined_reason', '')
|
||||
NOT IN ('insufficient_bank', 'sandbox_unavailable');
|
||||
|
||||
-- Lists explicit immutable training bindings for the effective product
|
||||
-- policy. Callers reject more than one matching active binding as ambiguous.
|
||||
-- name: ListCurrentAssessmentTrainingBindings :many
|
||||
SELECT
|
||||
binding.id,
|
||||
binding.category,
|
||||
binding.product_policy_version_id,
|
||||
binding.item_count,
|
||||
binding.manifest_sha256,
|
||||
binding.family_manifest,
|
||||
policy.version AS product_policy_version
|
||||
FROM assessment_training_bank_bindings AS binding
|
||||
JOIN policy_versions AS policy ON policy.id = binding.product_policy_version_id
|
||||
WHERE policy.policy_key = 'product'
|
||||
AND policy.effective_at <= statement_timestamp()
|
||||
AND NOT EXISTS (
|
||||
SELECT 1 FROM policy_versions AS newer
|
||||
WHERE newer.policy_key = 'product'
|
||||
AND newer.effective_at <= statement_timestamp()
|
||||
AND newer.version > policy.version
|
||||
)
|
||||
ORDER BY binding.category, binding.created_at DESC, binding.id;
|
||||
|
||||
-- Reads the exact family membership pinned by a training binding.
|
||||
-- name: ListAssessmentTrainingBindingFamilies :many
|
||||
SELECT
|
||||
family_id,
|
||||
ordinal,
|
||||
family_key,
|
||||
family_version,
|
||||
content_sha256
|
||||
FROM assessment_training_bank_binding_families
|
||||
WHERE binding_id = sqlc.arg(binding_id)
|
||||
ORDER BY ordinal;
|
||||
|
||||
-- Inserts the attempt header. The database guard rechecks the current policy,
|
||||
-- opening or disjoint training binding, and immutable pins.
|
||||
-- name: InsertAssessmentAttempt :exec
|
||||
INSERT INTO assessment_attempts (
|
||||
id,
|
||||
user_id,
|
||||
kind,
|
||||
mode,
|
||||
state,
|
||||
outcome,
|
||||
bank_category,
|
||||
specialization,
|
||||
target_grade,
|
||||
task_language,
|
||||
root_attempt_id,
|
||||
product_policy_version_id,
|
||||
product_policy_version,
|
||||
grading_policy_version_id,
|
||||
opening_id,
|
||||
opening_manifest_sha256,
|
||||
training_binding_id,
|
||||
training_manifest_sha256,
|
||||
bank_version,
|
||||
algorithm_version,
|
||||
created_at,
|
||||
updated_at,
|
||||
expires_at,
|
||||
chain_deadline,
|
||||
idle_timeout_seconds,
|
||||
max_sessions,
|
||||
sessions_used,
|
||||
session_started_at,
|
||||
last_activity_at,
|
||||
version,
|
||||
ended_at
|
||||
) VALUES (
|
||||
sqlc.arg(id),
|
||||
sqlc.arg(user_id),
|
||||
sqlc.arg(kind),
|
||||
sqlc.arg(mode),
|
||||
sqlc.arg(state),
|
||||
sqlc.narg(outcome),
|
||||
sqlc.arg(bank_category),
|
||||
sqlc.narg(specialization),
|
||||
sqlc.narg(target_grade),
|
||||
sqlc.narg(task_language),
|
||||
sqlc.arg(root_attempt_id),
|
||||
sqlc.arg(product_policy_version_id),
|
||||
sqlc.arg(product_policy_version),
|
||||
sqlc.narg(grading_policy_version_id),
|
||||
sqlc.narg(opening_id),
|
||||
sqlc.narg(opening_manifest_sha256),
|
||||
sqlc.narg(training_binding_id),
|
||||
sqlc.narg(training_manifest_sha256),
|
||||
sqlc.arg(bank_version),
|
||||
sqlc.arg(algorithm_version),
|
||||
sqlc.arg(created_at),
|
||||
sqlc.arg(updated_at),
|
||||
sqlc.arg(expires_at),
|
||||
sqlc.narg(chain_deadline),
|
||||
sqlc.arg(idle_timeout_seconds),
|
||||
sqlc.arg(max_sessions),
|
||||
sqlc.arg(sessions_used),
|
||||
sqlc.arg(session_started_at),
|
||||
sqlc.arg(last_activity_at),
|
||||
sqlc.arg(version),
|
||||
sqlc.narg(ended_at)
|
||||
);
|
||||
|
||||
-- Stores the immutable generated variant and empty answer slot.
|
||||
-- name: InsertAssessmentAttemptItem :exec
|
||||
INSERT INTO assessment_attempt_items (
|
||||
id,
|
||||
attempt_id,
|
||||
ordinal,
|
||||
family_id,
|
||||
family_key,
|
||||
family_version,
|
||||
family_content_sha256,
|
||||
variant,
|
||||
answer,
|
||||
answered_at
|
||||
) VALUES (
|
||||
sqlc.arg(id),
|
||||
sqlc.arg(attempt_id),
|
||||
sqlc.arg(ordinal),
|
||||
sqlc.arg(family_id),
|
||||
sqlc.arg(family_key),
|
||||
sqlc.arg(family_version),
|
||||
sqlc.arg(family_content_sha256),
|
||||
sqlc.arg(variant),
|
||||
sqlc.narg(answer),
|
||||
sqlc.narg(answered_at)
|
||||
);
|
||||
|
||||
-- Returns a full private attempt only to its candidate.
|
||||
-- name: GetAssessmentAttemptForCandidate :one
|
||||
SELECT
|
||||
id, user_id, kind, mode, state, outcome, bank_category, specialization,
|
||||
target_grade, task_language, root_attempt_id, product_policy_version_id,
|
||||
product_policy_version, grading_policy_version_id, opening_id,
|
||||
opening_manifest_sha256, training_binding_id, training_manifest_sha256,
|
||||
bank_version, algorithm_version, created_at, updated_at, expires_at,
|
||||
chain_deadline, idle_timeout_seconds, max_sessions, sessions_used,
|
||||
session_started_at, last_activity_at, version, ended_at
|
||||
FROM assessment_attempts
|
||||
WHERE id = sqlc.arg(id) AND user_id = sqlc.arg(user_id)
|
||||
FOR SHARE;
|
||||
|
||||
-- Reads the immutable attempt kind without locking the row. Session commands
|
||||
-- use this only to decide whether C3 applies before acquiring the row lock.
|
||||
-- name: GetAssessmentAttemptKindForCandidate :one
|
||||
SELECT kind
|
||||
FROM assessment_attempts
|
||||
WHERE id = sqlc.arg(id) AND user_id = sqlc.arg(user_id);
|
||||
|
||||
-- Locks one owner-scoped attempt while a session command performs its CAS.
|
||||
-- name: LockAssessmentAttemptForCandidate :one
|
||||
SELECT
|
||||
id, user_id, kind, mode, state, outcome, bank_category, specialization,
|
||||
target_grade, task_language, root_attempt_id, product_policy_version_id,
|
||||
product_policy_version, grading_policy_version_id, opening_id,
|
||||
opening_manifest_sha256, training_binding_id, training_manifest_sha256,
|
||||
bank_version, algorithm_version, created_at, updated_at, expires_at,
|
||||
chain_deadline, idle_timeout_seconds, max_sessions, sessions_used,
|
||||
session_started_at, last_activity_at, version, ended_at
|
||||
FROM assessment_attempts
|
||||
WHERE id = sqlc.arg(id) AND user_id = sqlc.arg(user_id)
|
||||
FOR UPDATE;
|
||||
|
||||
-- Reads chain headers in creation order. The use case verifies root eligibility
|
||||
-- and descending target grades in the domain before it creates a correction.
|
||||
-- name: ListAssessmentAttemptChain :many
|
||||
SELECT
|
||||
id, user_id, kind, mode, state, outcome, bank_category, specialization,
|
||||
target_grade, task_language, root_attempt_id, product_policy_version_id,
|
||||
product_policy_version, grading_policy_version_id, opening_id,
|
||||
opening_manifest_sha256, training_binding_id, training_manifest_sha256,
|
||||
bank_version, algorithm_version, created_at, updated_at, expires_at,
|
||||
chain_deadline, idle_timeout_seconds, max_sessions, sessions_used,
|
||||
session_started_at, last_activity_at, version, ended_at
|
||||
FROM assessment_attempts
|
||||
WHERE user_id = sqlc.arg(user_id)
|
||||
AND specialization = sqlc.arg(specialization)
|
||||
AND (id = sqlc.arg(root_attempt_id) OR root_attempt_id = sqlc.arg(root_attempt_id))
|
||||
ORDER BY created_at, id
|
||||
FOR SHARE;
|
||||
|
||||
-- Reads private frozen variants and candidate answer bytes in stable order.
|
||||
-- name: ListAssessmentAttemptItems :many
|
||||
SELECT
|
||||
id, attempt_id, ordinal, family_id, family_key, family_version,
|
||||
family_content_sha256, variant::text AS variant, answer, answered_at
|
||||
FROM assessment_attempt_items
|
||||
WHERE attempt_id = sqlc.arg(attempt_id)
|
||||
ORDER BY ordinal;
|
||||
|
||||
-- Applies a versioned session transition after the attempt row is locked.
|
||||
-- name: UpdateAssessmentAttemptSession :one
|
||||
UPDATE assessment_attempts
|
||||
SET
|
||||
state = sqlc.arg(state),
|
||||
outcome = sqlc.narg(outcome),
|
||||
updated_at = sqlc.arg(updated_at),
|
||||
sessions_used = sqlc.arg(sessions_used),
|
||||
session_started_at = sqlc.arg(session_started_at),
|
||||
last_activity_at = sqlc.arg(last_activity_at),
|
||||
version = sqlc.arg(version),
|
||||
ended_at = sqlc.narg(ended_at)
|
||||
WHERE id = sqlc.arg(id)
|
||||
AND user_id = sqlc.arg(user_id)
|
||||
AND version = sqlc.arg(expected_version)
|
||||
RETURNING
|
||||
id, user_id, kind, mode, state, outcome, bank_category, specialization,
|
||||
target_grade, task_language, root_attempt_id, product_policy_version_id,
|
||||
product_policy_version, grading_policy_version_id, opening_id,
|
||||
opening_manifest_sha256, training_binding_id, training_manifest_sha256,
|
||||
bank_version, algorithm_version, created_at, updated_at, expires_at,
|
||||
chain_deadline, idle_timeout_seconds, max_sessions, sessions_used,
|
||||
session_started_at, last_activity_at, version, ended_at;
|
||||
|
||||
-- Stores one final answer before advancing the enclosing attempt version.
|
||||
-- The caller holds the owner-scoped attempt row lock for the surrounding unit.
|
||||
-- name: UpdateAssessmentAttemptItemAnswer :one
|
||||
UPDATE assessment_attempt_items
|
||||
SET answer = sqlc.arg(answer), answered_at = sqlc.arg(answered_at)
|
||||
WHERE attempt_id = sqlc.arg(attempt_id)
|
||||
AND id = sqlc.arg(item_id)
|
||||
AND answer IS NULL
|
||||
RETURNING id;
|
||||
|
||||
-- Applies an answer, expiry, or finalization transition after the attempt row
|
||||
-- is locked. Session limits and all immutable pins remain unchanged.
|
||||
-- name: UpdateAssessmentAttemptTransition :one
|
||||
UPDATE assessment_attempts
|
||||
SET
|
||||
state = sqlc.arg(state),
|
||||
outcome = sqlc.narg(outcome),
|
||||
updated_at = sqlc.arg(updated_at),
|
||||
last_activity_at = sqlc.arg(last_activity_at),
|
||||
version = sqlc.arg(version),
|
||||
ended_at = sqlc.narg(ended_at)
|
||||
WHERE id = sqlc.arg(id)
|
||||
AND user_id = sqlc.arg(user_id)
|
||||
AND version = sqlc.arg(expected_version)
|
||||
RETURNING
|
||||
id, user_id, kind, mode, state, outcome, bank_category, specialization,
|
||||
target_grade, task_language, root_attempt_id, product_policy_version_id,
|
||||
product_policy_version, grading_policy_version_id, opening_id,
|
||||
opening_manifest_sha256, training_binding_id, training_manifest_sha256,
|
||||
bank_version, algorithm_version, created_at, updated_at, expires_at,
|
||||
chain_deadline, idle_timeout_seconds, max_sessions, sessions_used,
|
||||
session_started_at, last_activity_at, version, ended_at;
|
||||
|
||||
-- A newly reserved generic idempotency window can replace an expired typed
|
||||
-- outcome before the new immutable response is inserted.
|
||||
-- name: DeleteAssessmentAttemptIdempotencyOutcome :exec
|
||||
DELETE FROM assessment_attempt_idempotency_outcomes
|
||||
WHERE scope_hash = sqlc.arg(scope_hash);
|
||||
|
||||
-- name: InsertAssessmentAttemptIdempotencyOutcome :exec
|
||||
INSERT INTO assessment_attempt_idempotency_outcomes (
|
||||
scope_hash, operation, status_code, problem_code, response_snapshot,
|
||||
response_schema_version, pending_item_ids, created_at
|
||||
) VALUES (
|
||||
sqlc.arg(scope_hash), sqlc.arg(operation), sqlc.arg(status_code),
|
||||
sqlc.narg(problem_code), sqlc.narg(response_snapshot), 1,
|
||||
sqlc.arg(pending_item_ids)::uuid[], transaction_timestamp()
|
||||
);
|
||||
|
||||
-- name: GetAssessmentAttemptIdempotencyOutcome :one
|
||||
SELECT operation, status_code, problem_code,
|
||||
CAST(COALESCE(response_snapshot::text, ''::text) AS text) AS response_snapshot,
|
||||
pending_item_ids
|
||||
FROM assessment_attempt_idempotency_outcomes
|
||||
WHERE scope_hash = sqlc.arg(scope_hash);
|
||||
|
||||
-- Stores one immutable candidate-visible result with the decision rationale
|
||||
-- and source versions used by its finalized attempt.
|
||||
-- name: InsertAssessmentAttemptResult :exec
|
||||
INSERT INTO assessment_attempt_results (
|
||||
attempt_id, user_id, result_snapshot, schema_version, kind, mode, outcome,
|
||||
product_policy_version_id, product_policy_version,
|
||||
grading_policy_version_id, opening_id, opening_manifest_sha256,
|
||||
training_binding_id, training_manifest_sha256, bank_version, algorithm_version,
|
||||
rationale_rule, pass_mark_basis_points, scored_items, raw_score, pass_points, decided_at
|
||||
)
|
||||
VALUES (
|
||||
sqlc.arg(attempt_id), sqlc.arg(user_id), sqlc.arg(result_snapshot)::jsonb, 1,
|
||||
sqlc.arg(kind), sqlc.arg(mode), sqlc.arg(outcome),
|
||||
sqlc.arg(product_policy_version_id), sqlc.arg(product_policy_version),
|
||||
sqlc.narg(grading_policy_version_id), sqlc.narg(opening_id), sqlc.narg(opening_manifest_sha256),
|
||||
sqlc.narg(training_binding_id), sqlc.narg(training_manifest_sha256),
|
||||
sqlc.arg(bank_version), sqlc.arg(algorithm_version), sqlc.arg(rationale_rule),
|
||||
sqlc.narg(pass_mark_basis_points), sqlc.narg(scored_items), sqlc.narg(raw_score),
|
||||
sqlc.narg(pass_points), sqlc.arg(decided_at)
|
||||
);
|
||||
|
||||
-- Reads a result only for the owning candidate.
|
||||
-- name: GetAssessmentAttemptResult :one
|
||||
SELECT result_snapshot::text AS result_snapshot
|
||||
FROM assessment_attempt_results
|
||||
WHERE user_id = sqlc.arg(user_id) AND attempt_id = sqlc.arg(attempt_id);
|
||||
@@ -0,0 +1,173 @@
|
||||
-- Returns current reviewed grade/language bindings and the live published
|
||||
-- family manifest at one caller-supplied database time. The adapter verifies
|
||||
-- the pinned manifest hash before exposing only family keys.
|
||||
-- name: ListCurrentAssessmentAvailabilitySelections :many
|
||||
WITH current_policy AS (
|
||||
SELECT id, version
|
||||
FROM policy_versions
|
||||
WHERE policy_key = 'product' AND effective_at <= sqlc.arg(as_of)::timestamptz
|
||||
ORDER BY version DESC
|
||||
LIMIT 1
|
||||
), current_openings AS (
|
||||
SELECT DISTINCT ON (category)
|
||||
id,
|
||||
category,
|
||||
policy_version_id,
|
||||
required_families,
|
||||
opened_at
|
||||
FROM assessment_category_openings
|
||||
ORDER BY category, opened_at DESC, id DESC
|
||||
)
|
||||
SELECT
|
||||
opening.id AS opening_id,
|
||||
opening.category,
|
||||
opening.policy_version_id,
|
||||
opening.required_families,
|
||||
COALESCE((
|
||||
SELECT count(DISTINCT family.family_key)::integer
|
||||
FROM assessment_families AS family
|
||||
WHERE family.category = opening.category AND family.lifecycle = 'published'
|
||||
), 0)::integer AS published_count,
|
||||
policy.id AS effective_policy_id,
|
||||
policy.version AS effective_policy_version,
|
||||
binding.specialization,
|
||||
binding.grade,
|
||||
binding.task_languages,
|
||||
binding.published_manifest_sha256,
|
||||
COALESCE((
|
||||
SELECT jsonb_agg(
|
||||
jsonb_build_object(
|
||||
'family_key', family.family_key,
|
||||
'version', family.version,
|
||||
'content_sha256', encode(family.content_sha256, 'hex')
|
||||
) ORDER BY family.family_key, family.version
|
||||
)
|
||||
FROM assessment_families AS family
|
||||
WHERE family.category = opening.category AND family.lifecycle = 'published'
|
||||
), '[]'::jsonb)::text AS published_manifest
|
||||
FROM current_openings AS opening
|
||||
JOIN assessment_category_catalog_bindings AS binding
|
||||
ON binding.opening_id = opening.id
|
||||
LEFT JOIN current_policy AS policy ON true
|
||||
ORDER BY binding.specialization, binding.grade, binding.task_languages, opening.category;
|
||||
|
||||
-- Reads an active real attempt without taking the write lock used by create.
|
||||
-- The availability GET never expires or otherwise mutates this row.
|
||||
-- name: GetAssessmentAvailabilityActiveAttempt :one
|
||||
SELECT id, expires_at
|
||||
FROM assessment_attempts
|
||||
WHERE user_id = sqlc.arg(user_id)
|
||||
AND specialization = sqlc.arg(specialization)
|
||||
AND kind IN ('root', 'corrective')
|
||||
AND state IN ('in_progress', 'practice_pending', 'additional_practice_pending', 'ready_to_finalize')
|
||||
ORDER BY created_at DESC, id DESC
|
||||
LIMIT 1;
|
||||
|
||||
-- Reads roots within the policy horizon and the last header in each correction
|
||||
-- chain. It deliberately omits frozen items, answers, and row locks.
|
||||
-- name: ListAssessmentAvailabilityRootSummaries :many
|
||||
SELECT
|
||||
root.target_grade AS root_target_grade,
|
||||
root.created_at AS root_created_at,
|
||||
root.updated_at AS root_updated_at,
|
||||
root.expires_at AS root_expires_at,
|
||||
root.state AS root_state,
|
||||
root.outcome AS root_outcome,
|
||||
root.chain_deadline AS root_chain_deadline,
|
||||
latest.target_grade AS latest_target_grade,
|
||||
latest.updated_at AS latest_updated_at,
|
||||
latest.expires_at AS latest_expires_at,
|
||||
latest.state AS latest_state,
|
||||
latest.outcome AS latest_outcome,
|
||||
latest.chain_deadline AS latest_chain_deadline,
|
||||
COALESCE(latest_result.result_snapshot->>'not_determined_reason', '')::text AS latest_platform_error
|
||||
FROM assessment_attempts AS root
|
||||
JOIN LATERAL (
|
||||
SELECT attempt.*
|
||||
FROM assessment_attempts AS attempt
|
||||
WHERE attempt.user_id = root.user_id
|
||||
AND attempt.root_attempt_id = root.id
|
||||
AND attempt.kind IN ('root', 'corrective')
|
||||
ORDER BY attempt.created_at DESC, attempt.id DESC
|
||||
LIMIT 1
|
||||
) AS latest ON true
|
||||
LEFT JOIN assessment_attempt_results AS root_result
|
||||
ON root_result.attempt_id = root.id AND root_result.user_id = root.user_id
|
||||
LEFT JOIN assessment_attempt_results AS latest_result
|
||||
ON latest_result.attempt_id = latest.id AND latest_result.user_id = latest.user_id
|
||||
WHERE root.user_id = sqlc.arg(user_id)
|
||||
AND root.specialization = sqlc.arg(specialization)
|
||||
AND root.kind = 'root'
|
||||
AND root.created_at >= sqlc.arg(since)::timestamptz
|
||||
AND root.state <> 'insufficient_bank'
|
||||
AND COALESCE(root_result.result_snapshot->>'not_determined_reason', '')
|
||||
NOT IN ('insufficient_bank', 'sandbox_unavailable')
|
||||
ORDER BY root.created_at DESC, root.id DESC;
|
||||
|
||||
-- Counts eligible root attempts in a policy window and computes the instant
|
||||
-- at which one additional root slot opens. The microsecond adjustment matches
|
||||
-- the creation predicate created_at >= since at PostgreSQL timestamp precision.
|
||||
-- name: GetAssessmentRootQuotaAvailability :one
|
||||
WITH eligible AS (
|
||||
SELECT attempt.id, attempt.created_at
|
||||
FROM assessment_attempts AS attempt
|
||||
LEFT JOIN assessment_attempt_results AS result
|
||||
ON result.attempt_id = attempt.id AND result.user_id = attempt.user_id
|
||||
WHERE attempt.user_id = sqlc.arg(user_id)
|
||||
AND attempt.kind = 'root'
|
||||
AND attempt.state <> 'insufficient_bank'
|
||||
AND attempt.created_at >= sqlc.arg(since)::timestamptz
|
||||
AND attempt.created_at <= sqlc.arg(as_of)::timestamptz
|
||||
AND COALESCE(result.result_snapshot->>'not_determined_reason', '')
|
||||
NOT IN ('insufficient_bank', 'sandbox_unavailable')
|
||||
), total AS (
|
||||
SELECT count(*)::bigint AS attempt_count FROM eligible
|
||||
)
|
||||
SELECT
|
||||
total.attempt_count,
|
||||
CASE WHEN total.attempt_count >= sqlc.arg(max_attempts)::bigint THEN (
|
||||
SELECT eligible.created_at
|
||||
+ make_interval(secs => sqlc.arg(window_seconds)::double precision)
|
||||
+ interval '1 microsecond'
|
||||
FROM eligible
|
||||
ORDER BY eligible.created_at, eligible.id
|
||||
LIMIT 1
|
||||
OFFSET (total.attempt_count - sqlc.arg(max_attempts)::bigint)
|
||||
) ELSE NULL::timestamptz END AS available_at
|
||||
FROM total;
|
||||
|
||||
-- Counts family instances disclosed after the non-repeat boundary. The first
|
||||
-- item is disclosed when the attempt is created; each later item is disclosed
|
||||
-- when the preceding answer is accepted. This per-item timestamp prevents a
|
||||
-- long-running attempt from making later items appear older than they are.
|
||||
-- Counting the first unanswered item after expiry is conservative when the
|
||||
-- final response was lost, while frozen future items remain excluded.
|
||||
-- name: ListAssessmentDisclosedFamilyKeys :many
|
||||
WITH progress AS (
|
||||
SELECT
|
||||
attempt.id AS attempt_id,
|
||||
attempt.created_at,
|
||||
COALESCE(max(item.ordinal) FILTER (WHERE item.answered_at IS NOT NULL), 0) + 1 AS last_disclosed_ordinal
|
||||
FROM assessment_attempts AS attempt
|
||||
JOIN assessment_attempt_items AS item ON item.attempt_id = attempt.id
|
||||
WHERE attempt.user_id = sqlc.arg(user_id)
|
||||
AND attempt.kind IN ('root', 'corrective')
|
||||
AND attempt.expires_at > sqlc.arg(since)::timestamptz
|
||||
GROUP BY attempt.id
|
||||
), disclosed AS (
|
||||
SELECT
|
||||
item.family_key,
|
||||
CASE
|
||||
WHEN item.ordinal = 1 THEN progress.created_at
|
||||
ELSE previous.answered_at
|
||||
END AS disclosed_at
|
||||
FROM progress
|
||||
JOIN assessment_attempt_items AS item ON item.attempt_id = progress.attempt_id
|
||||
LEFT JOIN assessment_attempt_items AS previous
|
||||
ON previous.attempt_id = item.attempt_id AND previous.ordinal = item.ordinal - 1
|
||||
WHERE item.ordinal <= progress.last_disclosed_ordinal
|
||||
)
|
||||
SELECT DISTINCT disclosed.family_key
|
||||
FROM disclosed
|
||||
WHERE disclosed.disclosed_at > sqlc.arg(since)::timestamptz
|
||||
ORDER BY disclosed.family_key;
|
||||
@@ -0,0 +1,78 @@
|
||||
-- New outcomes share the generic idempotency row and are counted for the
|
||||
-- attempt's rolling receipt window. Replays bypass this query in the usecase.
|
||||
-- name: CountRecentAssessmentSignalOutcomes :one
|
||||
SELECT
|
||||
count(*)::bigint AS outcome_count,
|
||||
COALESCE(min(received_at), sqlc.arg(since)::timestamptz) AS oldest_at
|
||||
FROM assessment_signal_idempotency_outcomes
|
||||
WHERE
|
||||
attempt_id = sqlc.arg(attempt_id)
|
||||
AND received_at > sqlc.arg(since);
|
||||
|
||||
-- The attempt row is already locked by the caller. Store a parent before its
|
||||
-- bounded child events, in the same transaction as the immutable receipt.
|
||||
-- name: InsertAssessmentSignalBatch :exec
|
||||
INSERT INTO assessment_signal_batches (id, attempt_id, received_at, event_count)
|
||||
VALUES (
|
||||
sqlc.arg(id),
|
||||
sqlc.arg(attempt_id),
|
||||
sqlc.arg(received_at),
|
||||
sqlc.arg(event_count)
|
||||
);
|
||||
|
||||
-- Each inserted event is checked by the database guard against attempt state
|
||||
-- and the aggregate capacity as a second line of defense.
|
||||
-- name: InsertAssessmentSignalEvent :exec
|
||||
INSERT INTO assessment_signal_events (
|
||||
batch_id,
|
||||
attempt_id,
|
||||
ordinal,
|
||||
item_instance_id,
|
||||
kind,
|
||||
occurred_at,
|
||||
duration_ms,
|
||||
size_bytes
|
||||
) VALUES (
|
||||
sqlc.arg(batch_id),
|
||||
sqlc.arg(attempt_id),
|
||||
sqlc.arg(ordinal),
|
||||
sqlc.arg(item_instance_id),
|
||||
sqlc.arg(kind),
|
||||
sqlc.arg(occurred_at),
|
||||
sqlc.narg(duration_ms)::integer,
|
||||
sqlc.narg(size_bytes)::integer
|
||||
);
|
||||
|
||||
-- Count events only for the already owner-locked attempt.
|
||||
-- name: CountAssessmentSignalEvents :one
|
||||
SELECT count(*)::bigint AS event_count
|
||||
FROM assessment_signal_events
|
||||
WHERE attempt_id = sqlc.arg(attempt_id);
|
||||
|
||||
-- The generic reservation has already established that a previous outcome is
|
||||
-- expired before this child is removed and replaced in the same transaction.
|
||||
-- name: DeleteExpiredAssessmentSignalOutcome :exec
|
||||
DELETE FROM assessment_signal_idempotency_outcomes
|
||||
WHERE scope_hash = sqlc.arg(scope_hash);
|
||||
|
||||
-- Save exactly one immutable response receipt for each live idempotency scope.
|
||||
-- name: InsertAssessmentSignalOutcome :exec
|
||||
INSERT INTO assessment_signal_idempotency_outcomes (
|
||||
scope_hash,
|
||||
attempt_id,
|
||||
status,
|
||||
accepted_events,
|
||||
received_at
|
||||
) VALUES (
|
||||
sqlc.arg(scope_hash),
|
||||
sqlc.arg(attempt_id),
|
||||
sqlc.arg(status),
|
||||
sqlc.arg(accepted_events),
|
||||
sqlc.arg(received_at)
|
||||
);
|
||||
|
||||
-- Read only the receipt associated with the reserved idempotency scope.
|
||||
-- name: GetAssessmentSignalOutcome :one
|
||||
SELECT status, accepted_events, received_at
|
||||
FROM assessment_signal_idempotency_outcomes
|
||||
WHERE scope_hash = sqlc.arg(scope_hash);
|
||||
@@ -229,6 +229,35 @@ WHERE
|
||||
ORDER BY granted_at DESC, id DESC
|
||||
LIMIT 1;
|
||||
|
||||
-- Keeps the current C3 grant stable through a real assessment transaction.
|
||||
-- Revocation updates this row and therefore waits until the caller commits.
|
||||
-- name: LockCurrentConsentForUse :one
|
||||
SELECT
|
||||
id,
|
||||
subject_id,
|
||||
purpose,
|
||||
text_version,
|
||||
text_hash,
|
||||
source,
|
||||
registration_version,
|
||||
organization_id,
|
||||
organization_name,
|
||||
field_set,
|
||||
invitation_id,
|
||||
invitation_terms_version,
|
||||
granted_at,
|
||||
revoked_at,
|
||||
revocation_source,
|
||||
'active'::text AS state
|
||||
FROM consent_records
|
||||
WHERE
|
||||
subject_id = sqlc.arg(subject_id)
|
||||
AND purpose = 'c3'
|
||||
AND revoked_at IS NULL
|
||||
ORDER BY granted_at DESC, id DESC
|
||||
LIMIT 1
|
||||
FOR SHARE;
|
||||
|
||||
-- Locks the active registration C1 while its pending registration is applied.
|
||||
-- name: LockRegistrationConsentRecord :one
|
||||
SELECT
|
||||
|
||||
@@ -58,6 +58,34 @@ WHERE
|
||||
AND need_id = sqlc.arg(need_id)
|
||||
AND version = sqlc.arg(version);
|
||||
|
||||
-- Read one bounded newest-first page of current needs. Both the organization
|
||||
-- scope and the tuple cursor are applied before the limit.
|
||||
-- name: ListOrganizationNeeds :many
|
||||
SELECT
|
||||
need.organization_id,
|
||||
need.id AS need_id,
|
||||
need.current_version,
|
||||
need.requirements_version,
|
||||
need.created_at,
|
||||
need.updated_at,
|
||||
version.snapshot::text AS snapshot
|
||||
FROM organization_needs AS need
|
||||
INNER JOIN organization_need_versions AS version
|
||||
ON version.organization_id = need.organization_id
|
||||
AND version.need_id = need.id
|
||||
AND version.version = need.current_version
|
||||
WHERE
|
||||
need.organization_id = sqlc.arg(organization_id)
|
||||
AND (
|
||||
sqlc.narg(after_created_at)::timestamptz IS NULL
|
||||
OR (need.created_at, need.id) < (
|
||||
sqlc.narg(after_created_at)::timestamptz,
|
||||
sqlc.narg(after_need_id)::uuid
|
||||
)
|
||||
)
|
||||
ORDER BY need.created_at DESC, need.id DESC
|
||||
LIMIT sqlc.arg(row_limit);
|
||||
|
||||
-- The conditional parent update is the compare-and-swap. Appending the
|
||||
-- snapshot is part of the same SQL statement, so a failed insert leaves the
|
||||
-- parent pointer unchanged even before the surrounding transaction rolls
|
||||
@@ -100,3 +128,19 @@ WITH advanced AS (
|
||||
)
|
||||
SELECT appended.snapshot
|
||||
FROM appended;
|
||||
|
||||
-- The generic idempotency scope serializes retries. Replacing the child row
|
||||
-- is safe only in the transaction that reserves an expired scope for a new
|
||||
-- create; live retries read and return the stored response without writing.
|
||||
-- name: SaveOrganizationNeedCreationResult :exec
|
||||
INSERT INTO organization_need_creation_results (scope_hash, snapshot)
|
||||
VALUES (sqlc.arg(scope_hash), sqlc.arg(snapshot)::jsonb)
|
||||
ON CONFLICT (scope_hash) DO UPDATE
|
||||
SET snapshot = excluded.snapshot;
|
||||
|
||||
-- Read only the immutable original response. The current need may have moved
|
||||
-- to a later version since this result was created.
|
||||
-- name: GetOrganizationNeedCreationResult :one
|
||||
SELECT snapshot::text AS snapshot
|
||||
FROM organization_need_creation_results
|
||||
WHERE scope_hash = sqlc.arg(scope_hash);
|
||||
@@ -97,6 +97,32 @@ WHERE
|
||||
AND membership.user_id = sqlc.arg(user_id)
|
||||
AND membership.state = 'active';
|
||||
|
||||
-- Locks the organization first and then the active membership, using the
|
||||
-- same order as organization profile writes. A company operation keeps both
|
||||
-- share locks until its transaction commits, so a concurrent revocation
|
||||
-- cannot authorize a write after it has committed.
|
||||
-- name: LockActiveMembership :one
|
||||
WITH locked_organization AS MATERIALIZED (
|
||||
SELECT organizations.id
|
||||
FROM organizations
|
||||
WHERE organizations.id = sqlc.arg(organization_id)
|
||||
FOR SHARE
|
||||
)
|
||||
SELECT
|
||||
membership.id AS membership_id,
|
||||
membership.organization_id,
|
||||
membership.user_id,
|
||||
membership.role,
|
||||
membership.state,
|
||||
membership.created_at,
|
||||
membership.updated_at
|
||||
FROM memberships AS membership
|
||||
INNER JOIN locked_organization ON locked_organization.id = membership.organization_id
|
||||
WHERE
|
||||
membership.user_id = sqlc.arg(user_id)
|
||||
AND membership.state = 'active'
|
||||
FOR SHARE OF membership;
|
||||
|
||||
-- Changes the profile of an organization over the version the caller read
|
||||
-- and advances the version in the same statement. It names no verification
|
||||
-- column, so a profile update cannot move the trust level. The change
|
||||
|
||||
@@ -6,6 +6,39 @@
|
||||
-- looking, and hides nobody; no statement creates a row except an explicit
|
||||
-- act of the candidate.
|
||||
|
||||
-- Reads the candidate-owned settings and hidden count from one statement
|
||||
-- snapshot. Missing setting rows are restored as the closed/not-looking
|
||||
-- defaults in the adapter. The account row scopes the result but does not
|
||||
-- expose private profile values.
|
||||
-- name: ReadCandidatePrivacySettings :one
|
||||
SELECT
|
||||
users.id AS user_id,
|
||||
candidate_publications.state AS publication_state,
|
||||
candidate_publications.fields AS publication_fields,
|
||||
candidate_publications.consent_record_id AS publication_consent_record_id,
|
||||
candidate_publications.published_at AS publication_published_at,
|
||||
candidate_publications.closed_at AS publication_closed_at,
|
||||
candidate_publications.version AS publication_version,
|
||||
consent_records.revoked_at AS publication_consent_revoked_at,
|
||||
candidate_search_statuses.status AS search_status,
|
||||
candidate_search_statuses.confirmed_at AS search_confirmed_at,
|
||||
candidate_search_statuses.lapses_at AS search_lapses_at,
|
||||
candidate_search_statuses.policy_version_id AS search_policy_version_id,
|
||||
candidate_search_statuses.version AS search_version,
|
||||
(
|
||||
SELECT count(*)
|
||||
FROM candidate_hidden_organizations
|
||||
WHERE candidate_hidden_organizations.user_id = users.id
|
||||
) AS hidden_count
|
||||
FROM users
|
||||
LEFT JOIN candidate_publications
|
||||
ON candidate_publications.user_id = users.id
|
||||
LEFT JOIN consent_records
|
||||
ON consent_records.id = candidate_publications.consent_record_id
|
||||
LEFT JOIN candidate_search_statuses
|
||||
ON candidate_search_statuses.user_id = users.id
|
||||
WHERE users.id = sqlc.arg(user_id);
|
||||
|
||||
-- Reads the publication with the revocation state of the C2 record behind it
|
||||
-- in one statement, so the stored setting and the ledger come from one
|
||||
-- snapshot. The effective state is computed from them: published only while
|
||||
@@ -319,3 +352,74 @@ WHERE
|
||||
hidden.user_id = effective.user_id
|
||||
AND hidden.organization_id = sqlc.arg(organization_id)
|
||||
);
|
||||
|
||||
-- Records a successfully authorized view after visibility and quota checks.
|
||||
-- The audit contains only identities, the access kind, published field codes,
|
||||
-- and time; it never receives the projection content, ranking, or filters.
|
||||
-- name: InsertCandidateCardAccessEvent :exec
|
||||
INSERT INTO candidate_card_access_events (
|
||||
id,
|
||||
candidate_id,
|
||||
organization_id,
|
||||
actor_id,
|
||||
kind,
|
||||
field_codes,
|
||||
occurred_at
|
||||
) VALUES (
|
||||
sqlc.arg(id),
|
||||
sqlc.arg(candidate_id),
|
||||
sqlc.arg(organization_id),
|
||||
sqlc.narg(actor_id),
|
||||
sqlc.arg(kind),
|
||||
sqlc.arg(field_codes),
|
||||
sqlc.arg(occurred_at)
|
||||
);
|
||||
|
||||
-- Lists only the current candidate's own access history. It deliberately
|
||||
-- omits the employee, requested card fields, and search context. The privacy
|
||||
-- read adapter resolves an organization name only through this recorded
|
||||
-- access relation, which is already visible to the candidate.
|
||||
-- name: ListCandidateCardAccessEvents :many
|
||||
SELECT
|
||||
candidate_card_access_events.id,
|
||||
candidate_card_access_events.candidate_id,
|
||||
candidate_card_access_events.organization_id,
|
||||
candidate_card_access_events.actor_id,
|
||||
candidate_card_access_events.kind,
|
||||
candidate_card_access_events.field_codes,
|
||||
candidate_card_access_events.occurred_at,
|
||||
organizations.name AS organization_name
|
||||
FROM candidate_card_access_events
|
||||
INNER JOIN organizations
|
||||
ON organizations.id = candidate_card_access_events.organization_id
|
||||
WHERE
|
||||
candidate_card_access_events.candidate_id = sqlc.arg(candidate_id)
|
||||
AND (
|
||||
sqlc.narg(after_occurred_at)::timestamptz IS NULL
|
||||
OR (candidate_card_access_events.occurred_at, candidate_card_access_events.id) < (
|
||||
sqlc.narg(after_occurred_at)::timestamptz,
|
||||
sqlc.narg(after_id)::uuid
|
||||
)
|
||||
)
|
||||
ORDER BY candidate_card_access_events.occurred_at DESC, candidate_card_access_events.id DESC
|
||||
LIMIT sqlc.arg(row_limit);
|
||||
|
||||
-- The candidate may name an organization in privacy settings only if that
|
||||
-- organization already appears in their own access history or is already
|
||||
-- hidden. Unknown and unseen organizations produce the same no-row result.
|
||||
-- name: CandidateCanSeeOrganization :one
|
||||
SELECT organizations.id, organizations.name
|
||||
FROM organizations
|
||||
WHERE organizations.id = sqlc.arg(organization_id)
|
||||
AND (
|
||||
EXISTS (
|
||||
SELECT 1 FROM candidate_card_access_events
|
||||
WHERE candidate_card_access_events.candidate_id = sqlc.arg(user_id)
|
||||
AND candidate_card_access_events.organization_id = organizations.id
|
||||
)
|
||||
OR EXISTS (
|
||||
SELECT 1 FROM candidate_hidden_organizations
|
||||
WHERE candidate_hidden_organizations.user_id = sqlc.arg(user_id)
|
||||
AND candidate_hidden_organizations.organization_id = organizations.id
|
||||
)
|
||||
);
|
||||
@@ -0,0 +1,181 @@
|
||||
-- Organization-facing anonymous candidate projection inputs. The calling
|
||||
-- usecase has already authorized the active organization membership. This
|
||||
-- single statement snapshot filters both revoked/unpublished C2 states and
|
||||
-- candidates hidden from this organization before any profile value is read.
|
||||
-- The projection reads only stack, declared role, and experience dates. It
|
||||
-- deliberately excludes names, contacts, salary, location, soft skills,
|
||||
-- employer names, summaries, and imported excerpts.
|
||||
-- name: ListVisibleCandidateViewSources :many
|
||||
SELECT
|
||||
effective.user_id,
|
||||
effective.fields,
|
||||
claim.kind,
|
||||
claim.ordinal,
|
||||
CASE
|
||||
WHEN claim.kind = 'experience' THEN jsonb_build_object(
|
||||
'employer_name', NULL::text,
|
||||
'specialization', claim.value ->> 'specialization',
|
||||
'started_on', claim.value ->> 'started_on',
|
||||
'ended_on', claim.value -> 'ended_on',
|
||||
'summary', NULL::text
|
||||
)
|
||||
ELSE claim.value
|
||||
END AS safe_value,
|
||||
claim.status,
|
||||
claim.origin,
|
||||
claim.trust_level,
|
||||
claim.extraction_version,
|
||||
claim.confirmed_at,
|
||||
COALESCE(questionnaire.work_formats, '{}'::text[]) AS work_formats,
|
||||
COALESCE(
|
||||
(
|
||||
SELECT jsonb_agg(
|
||||
jsonb_build_object(
|
||||
'first_index', overlap.first_index,
|
||||
'second_index', overlap.second_index,
|
||||
'first_period', jsonb_build_object(
|
||||
'started_on', overlap.first_started_on,
|
||||
'ended_on', overlap.first_ended_on
|
||||
),
|
||||
'second_period', jsonb_build_object(
|
||||
'started_on', overlap.second_started_on,
|
||||
'ended_on', overlap.second_ended_on
|
||||
)
|
||||
) ORDER BY overlap.first_index, overlap.second_index
|
||||
)::text
|
||||
FROM candidate_profile_overlap_confirmations AS overlap
|
||||
WHERE overlap.user_id = effective.user_id
|
||||
),
|
||||
'[]'::text
|
||||
) AS parallel_period_acknowledgements
|
||||
FROM candidate_effective_publications AS effective
|
||||
LEFT JOIN candidate_profile_claims AS claim
|
||||
ON claim.user_id = effective.user_id
|
||||
AND claim.kind IN ('stack', 'role', 'experience')
|
||||
LEFT JOIN candidate_questionnaires AS questionnaire
|
||||
ON questionnaire.user_id = effective.user_id
|
||||
WHERE 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 effective.user_id, claim.kind, claim.ordinal;
|
||||
|
||||
-- Lock the account before an organization checks candidate visibility. The
|
||||
-- hidden-organization insert trigger takes FOR NO KEY UPDATE on this row, so
|
||||
-- a hide either commits before the later visibility recheck or waits for the
|
||||
-- read transaction to finish.
|
||||
-- name: LockCandidateAccountForView :one
|
||||
SELECT users.id
|
||||
FROM users
|
||||
WHERE users.id = sqlc.arg(candidate_id)
|
||||
FOR SHARE;
|
||||
|
||||
-- Lock the current C2 before locking the publication. C2 revocation updates
|
||||
-- this row before it locks the publication, so preserving this order avoids
|
||||
-- a lock inversion and makes the current consent stable through the read.
|
||||
-- name: LockCurrentC2ForView :one
|
||||
SELECT consent_records.id
|
||||
FROM consent_records
|
||||
WHERE
|
||||
consent_records.subject_id = sqlc.arg(candidate_id)
|
||||
AND consent_records.purpose = 'c2'
|
||||
AND consent_records.revoked_at IS NULL
|
||||
ORDER BY consent_records.granted_at DESC, consent_records.id DESC
|
||||
LIMIT 1
|
||||
FOR SHARE;
|
||||
|
||||
-- Lock and recheck one candidate's exact current publication only after the
|
||||
-- active C2 row is share-locked. No row includes unpublished, revoked, stale
|
||||
-- publication, and organization-hidden states.
|
||||
-- name: LockVisiblePublicationForView :one
|
||||
SELECT candidate_publications.user_id
|
||||
FROM candidate_publications
|
||||
INNER JOIN consent_records
|
||||
ON consent_records.id = candidate_publications.consent_record_id
|
||||
WHERE
|
||||
candidate_publications.user_id = sqlc.arg(candidate_id)
|
||||
AND candidate_publications.state = 'published'
|
||||
AND candidate_publications.consent_record_id = sqlc.arg(consent_record_id)
|
||||
AND consent_records.subject_id = candidate_publications.user_id
|
||||
AND consent_records.purpose = 'c2'
|
||||
AND consent_records.revoked_at IS NULL
|
||||
AND NOT EXISTS (
|
||||
SELECT 1
|
||||
FROM candidate_hidden_organizations AS hidden
|
||||
WHERE
|
||||
hidden.user_id = candidate_publications.user_id
|
||||
AND hidden.organization_id = sqlc.arg(organization_id)
|
||||
)
|
||||
FOR SHARE OF candidate_publications, consent_records;
|
||||
|
||||
-- Lock a candidate's current publication for the private preview. This has
|
||||
-- no organization context and never enters the employer read quota or audit.
|
||||
-- name: LockPublicationForCandidatePreview :one
|
||||
SELECT candidate_publications.user_id
|
||||
FROM candidate_publications
|
||||
INNER JOIN consent_records
|
||||
ON consent_records.id = candidate_publications.consent_record_id
|
||||
WHERE
|
||||
candidate_publications.user_id = sqlc.arg(candidate_id)
|
||||
AND candidate_publications.state = 'published'
|
||||
AND consent_records.subject_id = candidate_publications.user_id
|
||||
AND consent_records.purpose = 'c2'
|
||||
AND consent_records.revoked_at IS NULL
|
||||
FOR SHARE OF candidate_publications, consent_records;
|
||||
|
||||
-- Read the candidate's current private projection inputs after the caller
|
||||
-- locks its active C2 and publication. It selects only fields allowed in the
|
||||
-- anonymous-card projection and is never used for employer visibility.
|
||||
-- name: ReadCandidateViewSourceForPreview :many
|
||||
SELECT
|
||||
effective.user_id,
|
||||
effective.fields,
|
||||
claim.kind,
|
||||
claim.ordinal,
|
||||
CASE
|
||||
WHEN claim.kind = 'experience' THEN jsonb_build_object(
|
||||
'employer_name', NULL::text,
|
||||
'specialization', claim.value ->> 'specialization',
|
||||
'started_on', claim.value ->> 'started_on',
|
||||
'ended_on', claim.value -> 'ended_on',
|
||||
'summary', NULL::text
|
||||
)
|
||||
ELSE claim.value
|
||||
END AS safe_value,
|
||||
claim.status,
|
||||
claim.origin,
|
||||
claim.trust_level,
|
||||
claim.extraction_version,
|
||||
claim.confirmed_at,
|
||||
COALESCE(questionnaire.work_formats, '{}'::text[]) AS work_formats,
|
||||
COALESCE(
|
||||
(
|
||||
SELECT jsonb_agg(
|
||||
jsonb_build_object(
|
||||
'first_index', overlap.first_index,
|
||||
'second_index', overlap.second_index,
|
||||
'first_period', jsonb_build_object(
|
||||
'started_on', overlap.first_started_on,
|
||||
'ended_on', overlap.first_ended_on
|
||||
),
|
||||
'second_period', jsonb_build_object(
|
||||
'started_on', overlap.second_started_on,
|
||||
'ended_on', overlap.second_ended_on
|
||||
)
|
||||
) ORDER BY overlap.first_index, overlap.second_index
|
||||
)::text
|
||||
FROM candidate_profile_overlap_confirmations AS overlap
|
||||
WHERE overlap.user_id = effective.user_id
|
||||
),
|
||||
'[]'::text
|
||||
) AS parallel_period_acknowledgements
|
||||
FROM candidate_effective_publications AS effective
|
||||
LEFT JOIN candidate_profile_claims AS claim
|
||||
ON claim.user_id = effective.user_id
|
||||
AND claim.kind IN ('stack', 'role', 'experience')
|
||||
LEFT JOIN candidate_questionnaires AS questionnaire
|
||||
ON questionnaire.user_id = effective.user_id
|
||||
WHERE effective.user_id = sqlc.arg(candidate_id)
|
||||
ORDER BY effective.user_id, claim.kind, claim.ordinal;
|
||||
@@ -0,0 +1,154 @@
|
||||
-- Case numbers are monotonic and never reused. Sequence gaps on a rolled-back
|
||||
-- request are expected and do not expose request contents.
|
||||
-- name: NextSupportCaseNumber :one
|
||||
WITH next_value AS MATERIALIZED (
|
||||
SELECT nextval('support_case_number_seq') AS value
|
||||
)
|
||||
SELECT
|
||||
'SC-' || sqlc.arg(utc_year)::text || '-' ||
|
||||
CASE
|
||||
WHEN next_value.value < 1000000 THEN lpad(next_value.value::text, 6, '0')
|
||||
ELSE next_value.value::text
|
||||
END::text AS case_number
|
||||
FROM next_value;
|
||||
|
||||
-- The initial public history is inserted in the caller's case transaction.
|
||||
-- Any unique business conflict leaves the transaction usable so the caller can
|
||||
-- store the immutable 409 outcome under the request's idempotency key.
|
||||
-- name: InsertSupportCase :execrows
|
||||
INSERT INTO support_cases (
|
||||
id, case_number, owner_id, case_type, status, description,
|
||||
object_type, object_id, assessment_specialization, assessment_grade,
|
||||
complaint_reason, rubric_version, rubric_opening_id, rubric_policy_version_id,
|
||||
target_business_days, target_due_at,
|
||||
target_answered_at, target_policy_version, target_calendar_version,
|
||||
decision_outcome, decision_reason, decision_at, created_at, updated_at
|
||||
) VALUES (
|
||||
sqlc.arg(id), sqlc.arg(case_number), sqlc.arg(owner_id), sqlc.arg(case_type),
|
||||
sqlc.arg(status), sqlc.arg(description), sqlc.narg(object_type), sqlc.narg(object_id),
|
||||
sqlc.narg(assessment_specialization), sqlc.narg(assessment_grade),
|
||||
sqlc.narg(complaint_reason), sqlc.narg(rubric_version), sqlc.narg(rubric_opening_id),
|
||||
sqlc.narg(rubric_policy_version_id), sqlc.arg(target_business_days),
|
||||
sqlc.arg(target_due_at), sqlc.narg(target_answered_at), sqlc.arg(target_policy_version),
|
||||
sqlc.arg(target_calendar_version), sqlc.narg(decision_outcome), sqlc.narg(decision_reason),
|
||||
sqlc.narg(decision_at), sqlc.arg(created_at), sqlc.arg(updated_at)
|
||||
)
|
||||
ON CONFLICT DO NOTHING;
|
||||
|
||||
-- name: InsertSupportCaseEvent :exec
|
||||
INSERT INTO support_case_events (
|
||||
case_id, sequence, event_kind, actor_kind, occurred_at, status, message
|
||||
) VALUES (
|
||||
sqlc.arg(case_id), sqlc.arg(sequence), sqlc.arg(event_kind), sqlc.arg(actor_kind),
|
||||
sqlc.arg(occurred_at), sqlc.narg(status), sqlc.narg(message)
|
||||
);
|
||||
|
||||
-- Reads a full owner-scoped record. Object values are identifiers only.
|
||||
-- name: ReadOwnedSupportCase :one
|
||||
SELECT
|
||||
id, case_number, owner_id, case_type, status, description,
|
||||
object_type, object_id, assessment_specialization, assessment_grade,
|
||||
complaint_reason, rubric_version, rubric_opening_id, rubric_policy_version_id,
|
||||
target_business_days, target_due_at,
|
||||
target_answered_at, target_policy_version, target_calendar_version,
|
||||
decision_outcome, decision_reason, decision_at, created_at, updated_at
|
||||
FROM support_cases
|
||||
WHERE id = sqlc.arg(case_id) AND owner_id = sqlc.arg(owner_id);
|
||||
|
||||
-- Reads the immutable public history only after the case owner has matched.
|
||||
-- name: ReadSupportCaseEvents :many
|
||||
SELECT sequence, event_kind, actor_kind, occurred_at, status, message
|
||||
FROM support_case_events
|
||||
WHERE case_id = sqlc.arg(case_id)
|
||||
ORDER BY sequence;
|
||||
|
||||
-- Owner-scoped newest-first list. It omits descriptions, complaint reason,
|
||||
-- and event history. The tuple cursor matches the composite sort key.
|
||||
-- name: ListOwnedSupportCases :many
|
||||
WITH cursor_input AS MATERIALIZED (
|
||||
SELECT
|
||||
sqlc.narg(after_created_at)::timestamptz AS after_created_at,
|
||||
sqlc.narg(after_id)::uuid AS after_id
|
||||
)
|
||||
SELECT
|
||||
id, case_number, case_type, status, object_type, object_id,
|
||||
assessment_specialization, assessment_grade, target_business_days,
|
||||
target_due_at, target_answered_at, target_policy_version,
|
||||
target_calendar_version, decision_outcome, created_at, updated_at
|
||||
FROM support_cases
|
||||
CROSS JOIN cursor_input
|
||||
WHERE owner_id = sqlc.arg(owner_id)
|
||||
AND (
|
||||
cursor_input.after_created_at IS NULL
|
||||
OR (created_at, id) < (
|
||||
cursor_input.after_created_at,
|
||||
cursor_input.after_id
|
||||
)
|
||||
)
|
||||
ORDER BY created_at DESC, id DESC
|
||||
LIMIT sqlc.arg(row_limit);
|
||||
|
||||
-- No raw Idempotency-Key or request body reaches these statements. Failure
|
||||
-- responses pass {} as case_snapshot and the CASE stores SQL NULL instead.
|
||||
-- name: DeleteSupportCaseCreateOutcome :exec
|
||||
DELETE FROM support_case_create_outcomes
|
||||
WHERE scope_hash = sqlc.arg(scope_hash);
|
||||
|
||||
-- name: InsertSupportCaseCreateOutcome :exec
|
||||
INSERT INTO support_case_create_outcomes (
|
||||
scope_hash, outcome_kind, case_snapshot, target_was_late, created_at
|
||||
) VALUES (
|
||||
sqlc.arg(scope_hash), sqlc.arg(outcome_kind),
|
||||
CASE WHEN sqlc.arg(outcome_kind)::text = 'created' THEN sqlc.arg(case_snapshot)::jsonb END,
|
||||
CASE WHEN sqlc.arg(outcome_kind)::text = 'created' THEN sqlc.arg(target_was_late)::boolean END,
|
||||
sqlc.arg(created_at)
|
||||
);
|
||||
|
||||
-- name: ReadSupportCaseCreateOutcome :one
|
||||
SELECT outcome_kind, coalesce(case_snapshot::text, '') AS case_snapshot, target_was_late
|
||||
FROM support_case_create_outcomes
|
||||
WHERE scope_hash = sqlc.arg(scope_hash);
|
||||
|
||||
-- Serialize per-owner budget checks even before the first event exists.
|
||||
-- name: LockSupportCaseRequestBudget :exec
|
||||
SELECT pg_advisory_xact_lock(
|
||||
hashtextextended('lincodex.support.case.requests:' || sqlc.arg(owner_id)::uuid::text, 0)
|
||||
);
|
||||
|
||||
-- Read the latest serialized event so a temporarily regressing application
|
||||
-- clock cannot make the next request fall before an event already counted.
|
||||
-- name: LatestSupportCaseRequestEvent :one
|
||||
SELECT requested_at
|
||||
FROM support_case_request_events
|
||||
WHERE owner_id = sqlc.arg(owner_id)
|
||||
ORDER BY requested_at DESC, id DESC
|
||||
LIMIT 1;
|
||||
|
||||
-- Keep up to the maximum supported window, regardless of the current policy.
|
||||
-- The bounded delete prevents one create from doing unbounded cleanup work.
|
||||
-- name: PruneSupportCaseRequestEvents :execrows
|
||||
WITH expired AS MATERIALIZED (
|
||||
SELECT source.id
|
||||
FROM support_case_request_events AS source
|
||||
WHERE source.owner_id = sqlc.arg(owner_id)
|
||||
AND source.requested_at <= sqlc.arg(at)::timestamptz - interval '24 hours'
|
||||
ORDER BY source.requested_at, source.id
|
||||
LIMIT 100
|
||||
FOR UPDATE SKIP LOCKED
|
||||
)
|
||||
DELETE FROM support_case_request_events AS event
|
||||
USING expired
|
||||
WHERE event.id = expired.id;
|
||||
|
||||
-- The strict lower boundary means an event exactly one window old no longer
|
||||
-- counts. The use case derives Retry-After from first_in_window.
|
||||
-- name: CountSupportCaseRequestEvents :one
|
||||
SELECT count(*)::bigint AS event_count, min(requested_at) AS first_in_window
|
||||
FROM support_case_request_events
|
||||
WHERE owner_id = sqlc.arg(owner_id)
|
||||
AND requested_at > sqlc.arg(window_start)::timestamptz
|
||||
AND requested_at <= sqlc.arg(at)::timestamptz;
|
||||
|
||||
-- name: InsertSupportCaseRequestEvent :exec
|
||||
INSERT INTO support_case_request_events (owner_id, requested_at)
|
||||
VALUES (sqlc.arg(owner_id), sqlc.arg(requested_at));
|
||||
@@ -0,0 +1,53 @@
|
||||
-- Lists every current reviewed category binding for one exact public target.
|
||||
-- Manual support cases have no task-language selector, so the use case must
|
||||
-- accept a rubric only when one distinct current opening matches.
|
||||
-- name: ResolveCurrentSupportCaseRubrics :many
|
||||
WITH current_openings AS (
|
||||
SELECT DISTINCT ON (category)
|
||||
id,
|
||||
category,
|
||||
policy_version_id,
|
||||
required_families
|
||||
FROM assessment_category_openings
|
||||
ORDER BY category, opened_at DESC, id DESC
|
||||
), current_policy AS (
|
||||
SELECT id, version
|
||||
FROM policy_versions
|
||||
WHERE policy_key = 'product' AND effective_at <= statement_timestamp()
|
||||
ORDER BY version DESC
|
||||
LIMIT 1
|
||||
)
|
||||
SELECT
|
||||
opening.id AS opening_id,
|
||||
opening.category,
|
||||
opening.policy_version_id,
|
||||
opening.required_families,
|
||||
COALESCE((
|
||||
SELECT count(DISTINCT family.family_key)::integer
|
||||
FROM assessment_families AS family
|
||||
WHERE family.category = opening.category AND family.lifecycle = 'published'
|
||||
), 0)::integer AS published_count,
|
||||
policy.id AS effective_policy_id,
|
||||
policy.version AS effective_policy_version,
|
||||
binding.specialization,
|
||||
binding.grade,
|
||||
binding.task_languages,
|
||||
binding.published_manifest_sha256,
|
||||
COALESCE((
|
||||
SELECT jsonb_agg(
|
||||
jsonb_build_object(
|
||||
'family_key', family.family_key,
|
||||
'version', family.version,
|
||||
'content_sha256', encode(family.content_sha256, 'hex')
|
||||
) ORDER BY family.family_key, family.version
|
||||
)
|
||||
FROM assessment_families AS family
|
||||
WHERE family.category = opening.category AND family.lifecycle = 'published'
|
||||
), '[]'::jsonb)::text AS published_manifest
|
||||
FROM current_openings AS opening
|
||||
JOIN assessment_category_catalog_bindings AS binding
|
||||
ON binding.opening_id = opening.id
|
||||
LEFT JOIN current_policy AS policy ON true
|
||||
WHERE binding.specialization = sqlc.arg(specialization)
|
||||
AND binding.grade = sqlc.arg(grade)
|
||||
ORDER BY opening.category;
|
||||
Reference in new issue
Block a user