Files
lincodex/backend/internal/domain/policy.go
T

566 lines
23 KiB
Go

package domain
import (
"errors"
"fmt"
"slices"
"time"
)
// ErrInvalidPolicy reports a policy value that is missing, out of range, or
// inconsistent with another value of the same policy.
var ErrInvalidPolicy = errors.New("invalid policy")
// Units of policy values. Every value carries its unit in its type and in its
// document field name, so a number never changes meaning between code and
// storage.
type (
// CalendarDays counts whole days of 24 hours. Duration does not follow
// daylight saving shifts; deadlines are computed in UTC.
CalendarDays int32
// BusinessDays counts working days. Converting it to a deadline needs a
// business calendar, which the consuming feature defines, so it has no
// Duration method.
BusinessDays int32
// Hours counts whole hours.
Hours int32
// BasisPoints is a non-negative decimal with four fractional digits,
// stored as an integer count of 0.0001 units: 0.80 is 8000. Thresholds
// compare exactly, without the drift of binary floating point, and the
// document keeps an integer that every JSON reader decodes the same way.
BasisPoints int32
)
// basisPointsPerUnit is the BasisPoints value of 1.0.
const basisPointsPerUnit BasisPoints = 10000
func (days CalendarDays) Duration() time.Duration { return time.Duration(days) * 24 * time.Hour }
func (hours Hours) Duration() time.Duration { return time.Duration(hours) * time.Hour }
// String formats the value as a decimal, for example "0.8000".
func (points BasisPoints) String() string {
return fmt.Sprintf("%d.%04d", points/basisPointsPerUnit, points%basisPointsPerUnit)
}
// Sanity bounds of policy values. They reject typing mistakes such as a
// value in the wrong unit; they are not product decisions, which the policy
// values themselves record.
const (
maxResponseDeadlineOptions = 5
maxResponseDeadline = CalendarDays(30)
maxPendingInvitationsPerNeed = 1000
maxRepeatAfterDecline = CalendarDays(365)
maxInterviewProposalDeadline = BusinessDays(30)
maxNoDealPause = CalendarDays(365)
maxInvitationQuotaWindow = CalendarDays(31)
maxCardViewQuotaWindow = Hours(7 * 24)
maxTierQuotaLimit = 100000
maxSameGradeRetryInterval = CalendarDays(365)
maxAssessmentAttemptsPerWindow = 20
maxAssessmentAttemptWindow = CalendarDays(730)
maxAssessmentLifetime = Hours(30 * 24)
maxAssessmentIdleTimeoutSeconds = 24 * 60 * 60
maxAssessmentSessions = 10
minAssessmentExpressSeconds = 180
maxAssessmentExpressSeconds = 300
maxAssessmentExpressItems = 20
maxPromotionInterval = CalendarDays(730)
maxScoredItems = 200
maxSeedItems = 20
maxVerificationTokenLifetime = Hours(7 * 24)
maxUnverifiedAccountLifetime = CalendarDays(90)
maxSessionIdleTimeout = Hours(30 * 24)
maxSessionAbsoluteLifetime = CalendarDays(90)
maxSearchingConfirmationInterval = CalendarDays(365)
minExclusiveProbabilityBasisPoints = BasisPoints(1)
maxExclusiveProbabilityBasisPoints = basisPointsPerUnit - 1
minPositiveStandardErrorBasisPoints = BasisPoints(1)
)
// ProductPolicy holds the deadlines, quotas, thresholds, and coefficients
// that product rules read. A stored policy is immutable: a change is a new
// PolicyVersion, and records built under a policy keep the version they used.
type ProductPolicy struct {
Invitations InvitationPolicy
OrganizationQuotas OrganizationQuotaPolicy
Assessment AssessmentPolicy
Identity IdentityPolicy
SearchStatus SearchStatusPolicy
// Support is absent only in immutable policy documents that predate the
// support section. New demo policies should set it explicitly.
Support *SupportPolicy
// Matching holds the coefficients of the deterministic basic matching. It
// is nil in policy versions that predate it; such a version cannot rank
// and never inherits another version's coefficients.
Matching *MatchingPolicy
}
// Validate checks every section. A zero value is never valid, so a section
// that was left out fails instead of silently meaning zero.
func (policy ProductPolicy) Validate() error {
for _, validate := range []func() error{
policy.Invitations.Validate,
policy.OrganizationQuotas.Validate,
policy.Assessment.Validate,
policy.Identity.Validate,
policy.SearchStatus.Validate,
} {
if err := validate(); err != nil {
return err
}
}
if policy.Support != nil {
if err := policy.Support.Validate(); err != nil {
return fmt.Errorf("ProductPolicy.Validate - support section: %w: %w", ErrInvalidPolicy, err)
}
}
if policy.Matching != nil {
if err := policy.Matching.Validate(); err != nil {
return err
}
}
return nil
}
// clone copies the slices, so a caller cannot change a stored version through
// a returned policy.
func (policy ProductPolicy) clone() ProductPolicy {
copied := policy
copied.Invitations.ResponseDeadlineOptions = slices.Clone(policy.Invitations.ResponseDeadlineOptions)
if attempt := policy.Assessment.Attempt; attempt != nil {
attemptCopy := *attempt
copied.Assessment.Attempt = &attemptCopy
}
if training := policy.Assessment.Training; training != nil {
trainingCopy := *training
copied.Assessment.Training = &trainingCopy
}
if signals := policy.Assessment.Signals; signals != nil {
signalsCopy := *signals
copied.Assessment.Signals = &signalsCopy
}
if support := policy.Support; support != nil {
supportCopy := *support
copied.Support = &supportCopy
}
if matching := policy.Matching; matching != nil {
matchingCopy := matching.Clone()
copied.Matching = &matchingCopy
}
return copied
}
// InvitationPolicy governs salary offers sent to candidates.
type InvitationPolicy struct {
// ResponseDeadlineOptions are the response deadlines an employer may
// choose, in strictly increasing order.
ResponseDeadlineOptions []CalendarDays
// DefaultResponseDeadline is one of ResponseDeadlineOptions.
DefaultResponseDeadline CalendarDays
// MaxPendingPerNeed limits unanswered invitations for one employer need.
MaxPendingPerNeed int32
// RepeatAfterDecline is the pause before the same company may invite a
// candidate who declined.
RepeatAfterDecline CalendarDays
// InterviewProposalDeadline is the time the employer has to propose an
// interview after acceptance.
InterviewProposalDeadline BusinessDays
// NoDealPause is the pause after a contact that ended without a deal.
NoDealPause CalendarDays
}
func (policy InvitationPolicy) Validate() error {
const location = "InvitationPolicy.Validate"
options := policy.ResponseDeadlineOptions
if len(options) == 0 || len(options) > maxResponseDeadlineOptions {
return invalidPolicy(location, fmt.Sprintf("invitations.response_deadline_options_days must have 1 to %d values", maxResponseDeadlineOptions))
}
for index, option := range options {
if err := checkRange(location, "invitations.response_deadline_options_days", option, 1, maxResponseDeadline); err != nil {
return err
}
if index > 0 && option <= options[index-1] {
return invalidPolicy(location, "invitations.response_deadline_options_days must be strictly increasing")
}
}
if !slices.Contains(options, policy.DefaultResponseDeadline) {
return invalidPolicy(location, "invitations.default_response_deadline_days must be one of the response deadline options")
}
return firstError(
checkRange(location, "invitations.max_pending_per_need", policy.MaxPendingPerNeed, 1, maxPendingInvitationsPerNeed),
checkRange(location, "invitations.repeat_after_decline_days", policy.RepeatAfterDecline, 1, maxRepeatAfterDecline),
checkRange(location, "invitations.interview_proposal_deadline_business_days", policy.InterviewProposalDeadline, 1, maxInterviewProposalDeadline),
checkRange(location, "invitations.no_deal_pause_days", policy.NoDealPause, 1, maxNoDealPause),
)
}
// OrganizationTier is an employer trust level. Levels are ordered E0 < E1 <
// E2; the rules that move an organization between them belong to the quota
// feature, not to the policy. E0 is the level every organization starts at.
type OrganizationTier string
const (
OrganizationTierE0 OrganizationTier = "e0"
OrganizationTierE1 OrganizationTier = "e1"
OrganizationTierE2 OrganizationTier = "e2"
)
// ParseOrganizationTier accepts e0, e1, or e2.
func ParseOrganizationTier(value string) (OrganizationTier, error) {
tier := OrganizationTier(value)
switch tier {
case OrganizationTierE0, OrganizationTierE1, OrganizationTierE2:
return tier, nil
default:
return "", invalidPolicy("domain.ParseOrganizationTier", "tier must be e0, e1, or e2")
}
}
// OrganizationQuotaPolicy limits employer activity per trust level. Limits
// apply per rolling window.
type OrganizationQuotaPolicy struct {
InvitationWindow CalendarDays
CardViewWindow Hours
TierE0 OrganizationTierQuota
TierE1 OrganizationTierQuota
TierE2 OrganizationTierQuota
}
// OrganizationTierQuota is the quota of one level. An inactive level keeps
// its limits for the time it is enabled, but no organization can hold it
// before that. E0 is always active, and the active levels form a prefix: a
// level is active only when every lower level is.
type OrganizationTierQuota struct {
Active bool
InvitationsPerWindow int32
DistinctCardViewsPerWindow int32
}
// Tier returns the quota of a level. An unknown level returns
// ErrInvalidPolicy; callers check Active before assigning a level.
func (policy OrganizationQuotaPolicy) Tier(tier OrganizationTier) (OrganizationTierQuota, error) {
switch tier {
case OrganizationTierE0:
return policy.TierE0, nil
case OrganizationTierE1:
return policy.TierE1, nil
case OrganizationTierE2:
return policy.TierE2, nil
default:
return OrganizationTierQuota{}, invalidPolicy("OrganizationQuotaPolicy.Tier", "tier must be e0, e1, or e2")
}
}
func (policy OrganizationQuotaPolicy) Validate() error {
const location = "OrganizationQuotaPolicy.Validate"
if err := firstError(
checkRange(location, "organization_quotas.invitation_window_days", policy.InvitationWindow, 1, maxInvitationQuotaWindow),
checkRange(location, "organization_quotas.card_view_window_hours", policy.CardViewWindow, 1, maxCardViewQuotaWindow),
); err != nil {
return err
}
if !policy.TierE0.Active {
return invalidPolicy(location, "organization_quotas.tiers.e0 must be active, because every organization starts there")
}
tiers := []struct {
name OrganizationTier
quota OrganizationTierQuota
}{
{name: OrganizationTierE0, quota: policy.TierE0},
{name: OrganizationTierE1, quota: policy.TierE1},
{name: OrganizationTierE2, quota: policy.TierE2},
}
// The zero quota is below every valid limit and counts as active, so the
// lowest level passes the ordering checks.
lower := OrganizationTierQuota{Active: true}
for _, tier := range tiers {
prefix := "organization_quotas.tiers." + string(tier.name)
if err := firstError(
checkRange(location, prefix+".invitations_per_window", tier.quota.InvitationsPerWindow, 1, maxTierQuotaLimit),
checkRange(location, prefix+".distinct_card_views_per_window", tier.quota.DistinctCardViewsPerWindow, 1, maxTierQuotaLimit),
); err != nil {
return err
}
if tier.quota.Active && !lower.Active {
return invalidPolicy(location, prefix+" cannot be active while a lower tier is inactive")
}
// A higher level is granted after more trust, so it never has a
// smaller limit than the level below it.
if tier.quota.InvitationsPerWindow < lower.InvitationsPerWindow ||
tier.quota.DistinctCardViewsPerWindow < lower.DistinctCardViewsPerWindow {
return invalidPolicy(location, prefix+" limits must not be lower than the tier below")
}
lower = tier.quota
}
return nil
}
// AssessmentCalibration records whether assessment thresholds come from a
// calibration study.
type AssessmentCalibration string
const (
// AssessmentCalibrationUncalibratedInitial marks initial values chosen for
// verification of the product flow. They make no psychometric claim.
AssessmentCalibrationUncalibratedInitial AssessmentCalibration = "uncalibrated_initial"
// AssessmentCalibrationCalibrated marks values backed by a pilot and a
// documented calibration.
AssessmentCalibrationCalibrated AssessmentCalibration = "calibrated"
)
// AssessmentPolicy governs grade assessment attempts and decisions. P_G is
// the estimated probability that the candidate meets the claimed grade.
type AssessmentPolicy struct {
Calibration AssessmentCalibration
// SameGradeRetryAfter is the pause before another attempt at the same
// grade.
SameGradeRetryAfter CalendarDays
// MaxAttemptsPerWindow limits a candidate's root attempts across all
// specializations in any AttemptWindow. Corrective and training attempts
// do not reserve another root slot.
MaxAttemptsPerWindow int32
AttemptWindow CalendarDays
// PromotionMinInterval is the minimum time between grade promotions.
PromotionMinInterval CalendarDays
// ConfirmationThreshold is the lowest P_G that confirms the grade.
ConfirmationThreshold BasisPoints
// HighStrengthThreshold is the lowest P_G reported as a strong result.
HighStrengthThreshold BasisPoints
// PracticeRequired makes the unscored practice block mandatory before a
// scored attempt.
PracticeRequired bool
StopRule AssessmentStopRule
// Attempt is nil in legacy policy documents that predate the attempt
// contract. Attempt creation must fail closed when it is nil; readers keep
// those policy versions available for records created under them.
Attempt *AssessmentAttemptPolicy
// Training is an explicit non-qualification policy section. It is nil in
// immutable legacy policies and never inherits real assessment settings.
Training *AssessmentTrainingPolicy
// Signals holds the thresholds of the manual-review band. It is nil in
// policy versions that predate it; such a version computes no band and
// never inherits another version's thresholds.
Signals *AssessmentSignalPolicy
}
// AssessmentAttemptPolicy holds the versioned execution limits for a newly
// started attempt. It is optional only for immutable legacy policy versions;
// callers cannot infer missing values from defaults.
type AssessmentAttemptPolicy struct {
Lifetime Hours
ChainDeadline Hours
MaxSessions int32
IdleTimeoutSeconds int32
RealMode AssessmentRealMode
BasicPassMark BasisPoints
}
// AssessmentTrainingPolicy holds settings for a separate training run. Its
// bank source is pinned independently from real category openings.
type AssessmentTrainingPolicy struct {
DemoExpressDurationSeconds int32
DemoExpressItemCount int32
MaxSessions int32
IdleTimeoutSeconds int32
}
// AssessmentRealMode is a server-selected mode for a real assessment.
type AssessmentRealMode string
const (
AssessmentRealModeDemoBasic AssessmentRealMode = "demo_basic"
AssessmentRealModeAdaptive AssessmentRealMode = "adaptive"
)
func (policy AssessmentAttemptPolicy) validate(calibration AssessmentCalibration) error {
const location = "AssessmentAttemptPolicy.Validate"
if err := firstError(
checkRange(location, "assessment.attempt.lifetime_hours", policy.Lifetime, 1, maxAssessmentLifetime),
checkRange(location, "assessment.attempt.chain_deadline_hours", policy.ChainDeadline, 1, maxAssessmentLifetime),
checkRange(location, "assessment.attempt.max_sessions", policy.MaxSessions, 1, maxAssessmentSessions),
checkRange(location, "assessment.attempt.idle_timeout_seconds", policy.IdleTimeoutSeconds, 60, maxAssessmentIdleTimeoutSeconds),
); err != nil {
return err
}
if policy.ChainDeadline > policy.Lifetime {
return invalidPolicy(location, "assessment.attempt.chain_deadline_hours must not exceed lifetime_hours")
}
if int64(policy.IdleTimeoutSeconds) > int64(policy.Lifetime)*60*60 {
return invalidPolicy(location, "assessment.attempt.idle_timeout_seconds must not exceed lifetime_hours")
}
switch policy.RealMode {
case AssessmentRealModeDemoBasic:
if err := checkRange(location, "assessment.attempt.basic_pass_mark_bp", policy.BasicPassMark, 1, basisPointsPerUnit); err != nil {
return err
}
case AssessmentRealModeAdaptive:
if policy.BasicPassMark != 0 {
return invalidPolicy(location, "assessment.attempt.basic_pass_mark_bp must be zero in adaptive mode")
}
if calibration != AssessmentCalibrationCalibrated {
return invalidPolicy(location, "adaptive assessment mode requires a calibrated assessment policy")
}
default:
return invalidPolicy(location, "assessment.attempt.real_mode must be demo_basic or adaptive")
}
return nil
}
func (policy AssessmentTrainingPolicy) validate() error {
const location = "AssessmentTrainingPolicy.Validate"
if err := firstError(
checkRange(location, "assessment.training.demo_express_duration_seconds", policy.DemoExpressDurationSeconds, minAssessmentExpressSeconds, maxAssessmentExpressSeconds),
checkRange(location, "assessment.training.demo_express_item_count", policy.DemoExpressItemCount, 1, maxAssessmentExpressItems),
checkRange(location, "assessment.training.max_sessions", policy.MaxSessions, 1, maxAssessmentSessions),
checkRange(location, "assessment.training.idle_timeout_seconds", policy.IdleTimeoutSeconds, 60, maxAssessmentIdleTimeoutSeconds),
); err != nil {
return err
}
if policy.IdleTimeoutSeconds > policy.DemoExpressDurationSeconds {
return invalidPolicy(location, "assessment.training.idle_timeout_seconds must not exceed demo_express_duration_seconds")
}
return nil
}
// AssessmentStopRule ends an adaptive attempt. After MinScoredItems the
// attempt stops when P_G reaches UpperProbability or falls to
// LowerProbability, or when the standard error is at most MaxStandardError;
// it always stops after MaxScoredItems. SeedItems are unscored items for
// collecting statistics on new tasks and come on top of the scored ones.
type AssessmentStopRule struct {
MinScoredItems int32
MaxScoredItems int32
SeedItems int32
UpperProbability BasisPoints
LowerProbability BasisPoints
MaxStandardError BasisPoints
}
func (policy AssessmentPolicy) Validate() error {
const location = "AssessmentPolicy.Validate"
switch policy.Calibration {
case AssessmentCalibrationUncalibratedInitial, AssessmentCalibrationCalibrated:
default:
return invalidPolicy(location, "assessment.calibration must be uncalibrated_initial or calibrated")
}
if err := firstError(
checkRange(location, "assessment.same_grade_retry_after_days", policy.SameGradeRetryAfter, 1, maxSameGradeRetryInterval),
checkRange(location, "assessment.max_attempts_per_window", policy.MaxAttemptsPerWindow, 1, maxAssessmentAttemptsPerWindow),
checkRange(location, "assessment.attempt_window_days", policy.AttemptWindow, 1, maxAssessmentAttemptWindow),
checkRange(location, "assessment.promotion_min_interval_days", policy.PromotionMinInterval, 1, maxPromotionInterval),
checkProbability(location, "assessment.confirmation_threshold_bp", policy.ConfirmationThreshold),
checkProbability(location, "assessment.high_strength_threshold_bp", policy.HighStrengthThreshold),
); err != nil {
return err
}
if policy.HighStrengthThreshold < policy.ConfirmationThreshold {
return invalidPolicy(location, "assessment.high_strength_threshold_bp must not be below the confirmation threshold")
}
if err := policy.StopRule.validate(location, policy.ConfirmationThreshold); err != nil {
return err
}
if policy.Attempt != nil {
if err := policy.Attempt.validate(policy.Calibration); err != nil {
return err
}
}
if policy.Training != nil {
if err := policy.Training.validate(); err != nil {
return err
}
}
if policy.Signals != nil {
if err := policy.Signals.Validate(); err != nil {
return err
}
}
return nil
}
func (rule AssessmentStopRule) validate(location string, confirmation BasisPoints) error {
if err := firstError(
checkRange(location, "assessment.stop_rule.min_scored_items", rule.MinScoredItems, 1, maxScoredItems),
checkRange(location, "assessment.stop_rule.max_scored_items", rule.MaxScoredItems, rule.MinScoredItems, maxScoredItems),
checkRange(location, "assessment.stop_rule.seed_items", rule.SeedItems, 0, maxSeedItems),
checkProbability(location, "assessment.stop_rule.upper_probability_bp", rule.UpperProbability),
checkProbability(location, "assessment.stop_rule.lower_probability_bp", rule.LowerProbability),
checkRange(location, "assessment.stop_rule.max_standard_error_bp", rule.MaxStandardError, minPositiveStandardErrorBasisPoints, basisPointsPerUnit),
); err != nil {
return err
}
// An attempt must be able to stop above the confirmation threshold and
// below it; otherwise an early stop could never confirm or never reject.
if rule.LowerProbability >= confirmation || rule.UpperProbability < confirmation {
return invalidPolicy(location, "assessment.stop_rule probabilities must satisfy lower < confirmation threshold <= upper")
}
return nil
}
// IdentityPolicy holds the account and session lifetimes of the identity
// contract.
type IdentityPolicy struct {
VerificationTokenLifetime Hours
// UnverifiedAccountLifetime counts from the latest registration.
UnverifiedAccountLifetime CalendarDays
SessionIdleTimeout Hours
SessionAbsoluteLifetime CalendarDays
}
func (policy IdentityPolicy) Validate() error {
const location = "IdentityPolicy.Validate"
if err := firstError(
checkRange(location, "identity.verification_token_lifetime_hours", policy.VerificationTokenLifetime, 1, maxVerificationTokenLifetime),
checkRange(location, "identity.unverified_account_lifetime_days", policy.UnverifiedAccountLifetime, 1, maxUnverifiedAccountLifetime),
checkRange(location, "identity.session_idle_timeout_hours", policy.SessionIdleTimeout, 1, maxSessionIdleTimeout),
checkRange(location, "identity.session_absolute_lifetime_days", policy.SessionAbsoluteLifetime, 1, maxSessionAbsoluteLifetime),
); err != nil {
return err
}
if policy.SessionIdleTimeout.Duration() > policy.SessionAbsoluteLifetime.Duration() {
return invalidPolicy(location, "identity.session_idle_timeout_hours must not exceed the absolute session lifetime")
}
return nil
}
// SearchStatusPolicy governs the candidate "searching" status.
type SearchStatusPolicy struct {
// SearchingConfirmationInterval is how often a candidate confirms that
// the "searching" status is still current.
SearchingConfirmationInterval CalendarDays
}
func (policy SearchStatusPolicy) Validate() error {
return checkRange("SearchStatusPolicy.Validate", "search_status.searching_confirmation_interval_days",
policy.SearchingConfirmationInterval, 1, maxSearchingConfirmationInterval)
}
func checkRange[T ~int32](location, field string, value, minimum, maximum T) error {
if value < minimum || value > maximum {
return invalidPolicy(location, fmt.Sprintf("%s must be between %d and %d", field, minimum, maximum))
}
return nil
}
// checkProbability accepts a probability strictly between 0 and 1: a
// threshold of 0 or 1 would make a rule always or never apply.
func checkProbability(location, field string, value BasisPoints) error {
return checkRange(location, field, value, minExclusiveProbabilityBasisPoints, maxExclusiveProbabilityBasisPoints)
}
func invalidPolicy(location, reason string) error {
return fmt.Errorf("%s - %s: %w", location, reason, ErrInvalidPolicy)
}
func firstError(errs ...error) error {
for _, err := range errs {
if err != nil {
return err
}
}
return nil
}