feat(platform): add the notification inbox and deterministic match search

This commit is contained in:
shira committed 2026-10-09 13:14:46 +03:00
1 parent 5edff21d2d
commit 0b11021b16
169 files changed
+17083 -443

No files matched your search

@@ -0,0 +1,22 @@
package domain
import (
"log/slog"
"github.com/google/uuid"
)
// VisibleCandidateCard pairs the organization-scoped anonymous card with the
// internal candidate identifier of the same read. The identifier is a join and
// ordering key for server-side work such as matching; it must never be
// serialized, logged, or returned to an organization.
type VisibleCandidateCard struct {
CandidateID uuid.UUID
Card AnonymousCandidateViewDTO
}
func (VisibleCandidateCard) String() string { return "[visible candidate card]" }
func (VisibleCandidateCard) GoString() string { return "[visible candidate card]" }
func (VisibleCandidateCard) LogValue() slog.Value {
return slog.StringValue("[visible candidate card]")
}
@@ -0,0 +1,19 @@
package domain
// EvidenceSkillRelation says how the skill of a piece of evidence relates to
// a skill that a need asks for.
type EvidenceSkillRelation uint8
const (
// EvidenceSkillRelationNone means the evidence says nothing about the
// requested skill.
EvidenceSkillRelationNone EvidenceSkillRelation = iota
// EvidenceSkillRelationExact means the same skill.
EvidenceSkillRelationExact
// EvidenceSkillRelationNarrower means the evidence names a part of the
// requested skill (a technology under a requested specialization).
EvidenceSkillRelationNarrower
// EvidenceSkillRelationBroader means the evidence names a field that
// contains the requested skill (a specialization over a technology).
EvidenceSkillRelationBroader
)
+32 -3
View File
@@ -14,13 +14,41 @@ var ErrInvalidNotificationInboxEntry = errors.New("invalid notification inbox en
// in the internal inbox.
type NotificationInboxEventType string
const NotificationInboxInvitationDelivered NotificationInboxEventType = "invitation.delivered"
const (
// NotificationInboxInvitationDelivered records that an invitation reached
// the candidate's inbox. Its source is the invitation.
NotificationInboxInvitationDelivered NotificationInboxEventType = "invitation.delivered"
// NotificationInboxSyntheticDelivered is a synthetic event type. It
// carries no product meaning: it exists to exercise the whole inbox path
// (outbox, consumer, read-time visibility check, listing, read state)
// before real producers exist and in browser tests. Its source is the
// sending organization, and its content is a fixed notice that names that
// organization.
NotificationInboxSyntheticDelivered NotificationInboxEventType = "notification.synthetic_delivered"
)
// NotificationInboxSourceType identifies the current source-of-truth record
// used to resolve an inbox item's content.
type NotificationInboxSourceType string
const NotificationInboxSourceInvitation NotificationInboxSourceType = "invitation"
const (
NotificationInboxSourceInvitation NotificationInboxSourceType = "invitation"
NotificationInboxSourceOrganization NotificationInboxSourceType = "organization"
)
// NotificationInboxSourceFor returns the only source type that an event type
// may refer to, and false for an event type that is not allowlisted. The
// database repeats the same pairs in a CHECK constraint.
func NotificationInboxSourceFor(eventType NotificationInboxEventType) (NotificationInboxSourceType, bool) {
switch eventType {
case NotificationInboxInvitationDelivered:
return NotificationInboxSourceInvitation, true
case NotificationInboxSyntheticDelivered:
return NotificationInboxSourceOrganization, true
default:
return "", false
}
}
// NotificationInboxEntryInput contains identifiers and event metadata only.
// It deliberately has no content snapshot: presentation is resolved from the
@@ -78,7 +106,8 @@ func restoreNotificationInboxEntryWithLocation(
if input.EventID == uuid.Nil || input.RecipientUserID == uuid.Nil || input.OrganizationID == uuid.Nil || input.SourceID == uuid.Nil {
return NotificationInboxEntry{}, fmt.Errorf("%s - event, recipient, organization, and source IDs are required: %w", location, ErrInvalidNotificationInboxEntry)
}
if input.EventType != NotificationInboxInvitationDelivered || input.SchemaVersion != 1 || input.SourceType != NotificationInboxSourceInvitation {
sourceType, known := NotificationInboxSourceFor(input.EventType)
if !known || input.SchemaVersion != 1 || input.SourceType != sourceType {
return NotificationInboxEntry{}, fmt.Errorf("%s - event type, schema version, and source type are unsupported: %w", location, ErrInvalidNotificationInboxEntry)
}
if input.OccurredAt.IsZero() {
@@ -57,6 +57,7 @@ func TestRestoreNotificationInboxEntryRejectsInvalidMetadata(t *testing.T) {
{name: "unknown event type", mutate: func(input *NotificationInboxEntryInput) { input.EventType = "notification.mail_requested" }},
{name: "unsupported schema version", mutate: func(input *NotificationInboxEntryInput) { input.SchemaVersion = 2 }},
{name: "unknown source type", mutate: func(input *NotificationInboxEntryInput) { input.SourceType = "mail_request" }},
{name: "source type of another event type", mutate: func(input *NotificationInboxEntryInput) { input.SourceType = NotificationInboxSourceOrganization }},
{name: "missing occurrence time", mutate: func(input *NotificationInboxEntryInput) { input.OccurredAt = time.Time{} }},
{name: "zero read time", mutate: func(input *NotificationInboxEntryInput) { input.ReadAt = &zeroTime }},
}
@@ -118,3 +119,21 @@ func TestNotificationInboxEntryMarkReadPreservesFirstTimestamp(t *testing.T) {
t.Fatal("MarkRead changed immutable source identity")
}
}
func TestNotificationInboxEntryAcceptsTheSyntheticEventOnlyWithItsSource(t *testing.T) {
t.Parallel()
input := NotificationInboxEntryInput{
EventID: uuid.New(), RecipientUserID: uuid.New(), OrganizationID: uuid.New(),
EventType: NotificationInboxSyntheticDelivered, SchemaVersion: 1,
SourceType: NotificationInboxSourceOrganization, SourceID: uuid.New(),
OccurredAt: time.Date(2026, time.October, 8, 12, 30, 0, 0, time.UTC),
}
if _, err := NewNotificationInboxEntry(input); err != nil {
t.Fatalf("NewNotificationInboxEntry(synthetic) error = %v", err)
}
input.SourceType = NotificationInboxSourceInvitation
if _, err := NewNotificationInboxEntry(input); !errors.Is(err, ErrInvalidNotificationInboxEntry) {
t.Fatalf("NewNotificationInboxEntry(synthetic with invitation source) error = %v, want ErrInvalidNotificationInboxEntry", err)
}
}
+13
View File
@@ -93,6 +93,10 @@ type ProductPolicy struct {
// 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
@@ -114,6 +118,11 @@ func (policy ProductPolicy) Validate() error {
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
}
@@ -138,6 +147,10 @@ func (policy ProductPolicy) clone() ProductPolicy {
supportCopy := *support
copied.Support = &supportCopy
}
if matching := policy.Matching; matching != nil {
matchingCopy := matching.Clone()
copied.Matching = &matchingCopy
}
return copied
}
+10
View File
@@ -96,3 +96,13 @@ func DemoProductPolicyV3() ProductPolicy {
policy.Assessment.Signals = &signals
return policy
}
// DemoProductPolicyV4 returns the demo policy with the matching coefficients
// on top of DemoProductPolicyV3. It is published explicitly; a stored version
// is never rewritten, and startup seeding publishes V1 only.
func DemoProductPolicyV4() ProductPolicy {
policy := DemoProductPolicyV3()
matching := DemoMatchingPolicy()
policy.Matching = &matching
return policy
}
+127 -4
View File
@@ -7,6 +7,7 @@ import (
"errors"
"fmt"
"io"
"slices"
)
const (
@@ -36,6 +37,7 @@ type productPolicyDocument struct {
Identity *identityPolicyDocument `json:"identity"`
SearchStatus *searchStatusDocument `json:"search_status"`
Support *supportPolicyDocument `json:"support,omitempty"`
Matching *matchingPolicyDocument `json:"matching,omitempty"`
}
// productPolicyV1Document deliberately excludes extension keys. Its strict
@@ -157,6 +159,39 @@ type identityPolicyDocument struct {
SessionAbsoluteLifetimeDays *CalendarDays `json:"session_absolute_lifetime_days"`
}
type matchingPolicyDocument struct {
FitCoverageWeightBP *BasisPoints `json:"fit_coverage_weight_bp"`
FitDomainWeightBP *BasisPoints `json:"fit_domain_weight_bp"`
FitSemanticsWeightBP *BasisPoints `json:"fit_semantics_weight_bp"`
RankFitWeightBP *BasisPoints `json:"rank_fit_weight_bp"`
RankStrengthWeightBP *BasisPoints `json:"rank_strength_weight_bp"`
FreshnessFloorBP *BasisPoints `json:"freshness_floor_bp"`
ResponsivenessFloorBP *BasisPoints `json:"responsiveness_floor_bp"`
CompetitionBoostBP *BasisPoints `json:"competition_boost_bp"`
NeutralUnknownBP *BasisPoints `json:"neutral_unknown_bp"`
NearSkillThresholdBP *BasisPoints `json:"near_skill_threshold_bp"`
RequiredSkillWeight *int32 `json:"required_skill_weight"`
DesiredSkillWeight *int32 `json:"desired_skill_weight"`
TrustStatedBP *BasisPoints `json:"trust_stated_bp"`
TrustOnlineBP *BasisPoints `json:"trust_online_bp"`
TrustIdentityBP *BasisPoints `json:"trust_identity_bp"`
TrustInPersonBP *BasisPoints `json:"trust_in_person_bp"`
AttributionPersonalBP *BasisPoints `json:"attribution_personal_bp"`
AttributionTeamRoleBP *BasisPoints `json:"attribution_team_role_bp"`
AttributionTeamUnattributed *BasisPoints `json:"attribution_team_unattributed_bp"`
RelationExactBP *BasisPoints `json:"relation_exact_bp"`
RelationNarrowerBP *BasisPoints `json:"relation_narrower_bp"`
RelationBroaderBP *BasisPoints `json:"relation_broader_bp"`
PercentileMinCohort *int32 `json:"percentile_min_cohort"`
MaxResultsPerGroup *int32 `json:"max_results_per_group"`
SkillTaxonomy *[]matchingSkillGroupDocument `json:"skill_taxonomy"`
}
type matchingSkillGroupDocument struct {
Specialization *SpecializationCode `json:"specialization"`
Skills *[]CandidateViewSkillCode `json:"skills"`
}
type searchStatusDocument struct {
SearchingConfirmationIntervalDays *CalendarDays `json:"searching_confirmation_interval_days"`
}
@@ -178,7 +213,8 @@ func encodeProductPolicy(policy ProductPolicy) ([]byte, PolicyDocumentHash, erro
}
}
schemaVersion := int32(productPolicySchemaVersionV1)
if policy.Assessment.Attempt != nil || policy.Assessment.Training != nil || policy.Assessment.Signals != nil || policy.Support != nil {
if policy.Assessment.Attempt != nil || policy.Assessment.Training != nil || policy.Assessment.Signals != nil ||
policy.Support != nil || policy.Matching != nil {
schemaVersion = productPolicySchemaVersionV2
}
document := productPolicyDocument{
@@ -230,7 +266,8 @@ func encodeProductPolicy(policy ProductPolicy) ([]byte, PolicyDocumentHash, erro
SearchStatus: &searchStatusDocument{
SearchingConfirmationIntervalDays: pointer(policy.SearchStatus.SearchingConfirmationInterval),
},
Support: support,
Support: support,
Matching: encodeMatchingPolicy(policy.Matching),
}
encoded, err := json.Marshal(document)
if err != nil {
@@ -292,6 +329,49 @@ func encodeAssessmentSignalPolicy(policy *AssessmentSignalPolicy) *assessmentSig
}
}
func encodeMatchingPolicy(policy *MatchingPolicy) *matchingPolicyDocument {
if policy == nil {
return nil
}
return &matchingPolicyDocument{
FitCoverageWeightBP: pointer(policy.FitCoverageWeight),
FitDomainWeightBP: pointer(policy.FitDomainWeight),
FitSemanticsWeightBP: pointer(policy.FitSemanticsWeight),
RankFitWeightBP: pointer(policy.RankFitWeight),
RankStrengthWeightBP: pointer(policy.RankStrengthWeight),
FreshnessFloorBP: pointer(policy.FreshnessFloor),
ResponsivenessFloorBP: pointer(policy.ResponsivenessFloor),
CompetitionBoostBP: pointer(policy.CompetitionBoost),
NeutralUnknownBP: pointer(policy.NeutralUnknown),
NearSkillThresholdBP: pointer(policy.NearSkillThreshold),
RequiredSkillWeight: pointer(policy.RequiredSkillWeight),
DesiredSkillWeight: pointer(policy.DesiredSkillWeight),
TrustStatedBP: pointer(policy.TrustStated),
TrustOnlineBP: pointer(policy.TrustOnline),
TrustIdentityBP: pointer(policy.TrustIdentity),
TrustInPersonBP: pointer(policy.TrustInPerson),
AttributionPersonalBP: pointer(policy.AttributionSelf),
AttributionTeamRoleBP: pointer(policy.AttributionTeamRole),
AttributionTeamUnattributed: pointer(policy.AttributionTeamUnattributed),
RelationExactBP: pointer(policy.RelationExact),
RelationNarrowerBP: pointer(policy.RelationNarrower),
RelationBroaderBP: pointer(policy.RelationBroader),
PercentileMinCohort: pointer(policy.PercentileMinCohort),
MaxResultsPerGroup: pointer(policy.MaxResultsPerGroup),
SkillTaxonomy: pointer(encodeMatchingSkillGroups(policy.SkillTaxonomy)),
}
}
func encodeMatchingSkillGroups(groups []MatchingSkillGroup) []matchingSkillGroupDocument {
documents := make([]matchingSkillGroupDocument, 0, len(groups))
for _, group := range groups {
documents = append(documents, matchingSkillGroupDocument{
Specialization: pointer(group.Specialization), Skills: pointer(slices.Clone(group.Skills)),
})
}
return documents
}
func encodeTierQuota(quota OrganizationTierQuota) *organizationTierQuotaDocument {
return &organizationTierQuotaDocument{
Active: pointer(quota.Active),
@@ -347,7 +427,7 @@ func decodeProductPolicy(document []byte) (ProductPolicy, error) {
}
assessment := parsed.Assessment
hasAssessmentExtension := assessment != nil && (assessment.Attempt != nil || assessment.Training != nil || assessment.Signals != nil)
if !hasAssessmentExtension && parsed.Support == nil {
if !hasAssessmentExtension && parsed.Support == nil && parsed.Matching == nil {
return ProductPolicy{}, invalidPolicy(location, "schema_version 2 requires at least one policy extension")
}
default:
@@ -493,7 +573,8 @@ func decodeProductPolicyFields(parsed productPolicyDocument, schemaVersion int32
SearchStatus: SearchStatusPolicy{
SearchingConfirmationInterval: require(&reader, "search_status.searching_confirmation_interval_days", searchStatus.SearchingConfirmationIntervalDays),
},
Support: decodeOptionalSupportPolicy(&reader, parsed.Support),
Support: decodeOptionalSupportPolicy(&reader, parsed.Support),
Matching: decodeOptionalMatchingPolicy(&reader, parsed.Matching),
}
if reader.missing != "" {
return ProductPolicy{}, invalidPolicy(location, reader.missing+" is required")
@@ -501,6 +582,48 @@ func decodeProductPolicyFields(parsed productPolicyDocument, schemaVersion int32
return policy, nil
}
// decodeOptionalMatchingPolicy keeps documents that predate the matching
// section without it and never fills an omitted section with demo values.
func decodeOptionalMatchingPolicy(reader *documentReader, document *matchingPolicyDocument) *MatchingPolicy {
if document == nil {
return nil
}
taxonomy := make([]MatchingSkillGroup, 0)
for _, group := range require(reader, "matching.skill_taxonomy", document.SkillTaxonomy) {
taxonomy = append(taxonomy, MatchingSkillGroup{
Specialization: require(reader, "matching.skill_taxonomy.specialization", group.Specialization),
Skills: require(reader, "matching.skill_taxonomy.skills", group.Skills),
})
}
return &MatchingPolicy{
FitCoverageWeight: require(reader, "matching.fit_coverage_weight_bp", document.FitCoverageWeightBP),
FitDomainWeight: require(reader, "matching.fit_domain_weight_bp", document.FitDomainWeightBP),
FitSemanticsWeight: require(reader, "matching.fit_semantics_weight_bp", document.FitSemanticsWeightBP),
RankFitWeight: require(reader, "matching.rank_fit_weight_bp", document.RankFitWeightBP),
RankStrengthWeight: require(reader, "matching.rank_strength_weight_bp", document.RankStrengthWeightBP),
FreshnessFloor: require(reader, "matching.freshness_floor_bp", document.FreshnessFloorBP),
ResponsivenessFloor: require(reader, "matching.responsiveness_floor_bp", document.ResponsivenessFloorBP),
CompetitionBoost: require(reader, "matching.competition_boost_bp", document.CompetitionBoostBP),
NeutralUnknown: require(reader, "matching.neutral_unknown_bp", document.NeutralUnknownBP),
NearSkillThreshold: require(reader, "matching.near_skill_threshold_bp", document.NearSkillThresholdBP),
RequiredSkillWeight: require(reader, "matching.required_skill_weight", document.RequiredSkillWeight),
DesiredSkillWeight: require(reader, "matching.desired_skill_weight", document.DesiredSkillWeight),
TrustStated: require(reader, "matching.trust_stated_bp", document.TrustStatedBP),
TrustOnline: require(reader, "matching.trust_online_bp", document.TrustOnlineBP),
TrustIdentity: require(reader, "matching.trust_identity_bp", document.TrustIdentityBP),
TrustInPerson: require(reader, "matching.trust_in_person_bp", document.TrustInPersonBP),
AttributionSelf: require(reader, "matching.attribution_personal_bp", document.AttributionPersonalBP),
AttributionTeamRole: require(reader, "matching.attribution_team_role_bp", document.AttributionTeamRoleBP),
AttributionTeamUnattributed: require(reader, "matching.attribution_team_unattributed_bp", document.AttributionTeamUnattributed),
RelationExact: require(reader, "matching.relation_exact_bp", document.RelationExactBP),
RelationNarrower: require(reader, "matching.relation_narrower_bp", document.RelationNarrowerBP),
RelationBroader: require(reader, "matching.relation_broader_bp", document.RelationBroaderBP),
PercentileMinCohort: require(reader, "matching.percentile_min_cohort", document.PercentileMinCohort),
MaxResultsPerGroup: require(reader, "matching.max_results_per_group", document.MaxResultsPerGroup),
SkillTaxonomy: taxonomy,
}
}
func decodeTierQuota(reader *documentReader, field string, document *organizationTierQuotaDocument) OrganizationTierQuota {
tier := require(reader, field, document)
return OrganizationTierQuota{
+336
View File
@@ -0,0 +1,336 @@
package domain
import "slices"
// MatchingPolicy holds the versioned coefficients of the deterministic basic
// matching (FR09). Every share is a BasisPoints value, so a comparison and a
// stored document carry an exact integer instead of a binary fraction. The
// section is optional: a policy version without it cannot rank, and an absent
// section never acquires defaults.
//
// Fit = FitCoverageWeight*Cov + FitDomainWeight*Dom + FitSemanticsWeight*Sem
// P = T + CompetitionBoost*(1-T)*V
// S = (RankFitWeight*Fit + RankStrengthWeight*P) *
//
// (FreshnessFloor + (1-FreshnessFloor)*Fr) *
// (ResponsivenessFloor + (1-ResponsivenessFloor)*Rsp)
//
// A skill contributes the best product of the trust, attribution, and
// relation coefficients over the permitted evidence; Cov is the weighted mean
// of the contributions of the requested skills.
type MatchingPolicy struct {
FitCoverageWeight BasisPoints
FitDomainWeight BasisPoints
FitSemanticsWeight BasisPoints
RankFitWeight BasisPoints
RankStrengthWeight BasisPoints
// FreshnessFloor and ResponsivenessFloor are the multipliers of a
// component equal to zero; a component equal to one multiplies by 1.
FreshnessFloor BasisPoints
ResponsivenessFloor BasisPoints
// CompetitionBoost is the share of the remaining distance (1-T) that a
// competition contribution of one adds to the strength of the profile.
CompetitionBoost BasisPoints
// NeutralUnknown replaces a component whose value is unknown. The
// unknown state is reported next to it and is never read as zero ability.
NeutralUnknown BasisPoints
// NearSkillThreshold is the contribution below which a requested
// required skill moves a confirmed profile to the near group.
NearSkillThreshold BasisPoints
RequiredSkillWeight int32
DesiredSkillWeight int32
// The trust coefficients are indexed by the evidence trust level 0..3.
TrustStated BasisPoints
TrustOnline BasisPoints
TrustIdentity BasisPoints
TrustInPerson BasisPoints
AttributionSelf BasisPoints
// AttributionTeamRole is a relevant role in a team result and
// AttributionTeamUnattributed a team result without a role.
AttributionTeamRole BasisPoints
AttributionTeamUnattributed BasisPoints
// The relation coefficients apply when the evidence skill equals the
// requested one (or a synonym), is narrower than it, or is broader.
RelationExact BasisPoints
RelationNarrower BasisPoints
RelationBroader BasisPoints
// PercentileMinCohort is the smallest number of comparable real
// candidates that allows a percentile; below it T is neutral.
PercentileMinCohort int32
// MaxResultsPerGroup bounds how many entries of each group one search may
// return. The whole visible bank is ranked and only the output is cut, so
// a search cannot read the whole bank at once. It is a demonstration value
// that stays below the daily card-view allowance of the first tier.
MaxResultsPerGroup int32
// SkillTaxonomy lists, for each specialization, the technologies that fall
// inside it. Evidence for a specialization is broader evidence for each of
// them, and evidence for one of them is narrower evidence for the
// specialization. It is part of the version, so the policy version fully
// determines a result.
SkillTaxonomy []MatchingSkillGroup
}
// MatchingSkillGroup is the technologies that one specialization contains.
type MatchingSkillGroup struct {
Specialization SpecializationCode
Skills []CandidateViewSkillCode
}
// Clone copies the slices, so a caller cannot change a stored version.
func (policy MatchingPolicy) Clone() MatchingPolicy {
policy.SkillTaxonomy = slices.Clone(policy.SkillTaxonomy)
for index := range policy.SkillTaxonomy {
policy.SkillTaxonomy[index].Skills = slices.Clone(policy.SkillTaxonomy[index].Skills)
}
return policy
}
// RelateSkill classifies the skill of a piece of evidence against a requested
// skill by the taxonomy of this policy version. Both are taxonomy codes; an
// unmapped code has no relation.
func (policy MatchingPolicy) RelateSkill(requested, evidence string) EvidenceSkillRelation {
switch {
case requested == "" || evidence == "":
return EvidenceSkillRelationNone
case requested == evidence:
return EvidenceSkillRelationExact
case policy.contains(evidence, requested):
return EvidenceSkillRelationBroader
case policy.contains(requested, evidence):
return EvidenceSkillRelationNarrower
default:
return EvidenceSkillRelationNone
}
}
func (policy MatchingPolicy) contains(specialization, skill string) bool {
for _, group := range policy.SkillTaxonomy {
if string(group.Specialization) != specialization {
continue
}
for _, contained := range group.Skills {
if string(contained) == skill {
return true
}
}
}
return false
}
// Sanity bounds of the matching section. They reject a value in the wrong
// unit; the demo values themselves are recorded in DemoMatchingPolicy.
const (
maxMatchingSkillWeight = 100
maxMatchingCohortMinimum = 100000
maxMatchingResults = 1000
)
// DemoMatchingPolicy returns the initial matching coefficients. They are the
// design values of PRD 4.9 for verifying the flow, not measured results: no
// labelled set supports them, and a calibrated policy must replace them.
func DemoMatchingPolicy() MatchingPolicy {
return MatchingPolicy{
FitCoverageWeight: 7500, FitDomainWeight: 1500, FitSemanticsWeight: 1000,
RankFitWeight: 5000, RankStrengthWeight: 5000,
FreshnessFloor: 9000, ResponsivenessFloor: 9000,
CompetitionBoost: 3000,
NeutralUnknown: 5000, NearSkillThreshold: 2500,
RequiredSkillWeight: 2, DesiredSkillWeight: 1,
TrustStated: 2500, TrustOnline: 6000, TrustIdentity: 8500, TrustInPerson: 10000,
AttributionSelf: 10000, AttributionTeamRole: 8000, AttributionTeamUnattributed: 5000,
RelationExact: 10000, RelationNarrower: 8000, RelationBroader: 4000,
PercentileMinCohort: 30,
// 10 per group is at most 30 reveals for one search, below the 50
// distinct card views per day of the first tier, so one search cannot
// spend a whole allowance.
MaxResultsPerGroup: 10,
SkillTaxonomy: []MatchingSkillGroup{
{
Specialization: SpecializationBackend,
Skills: []CandidateViewSkillCode{
CandidateViewSkillDocker, CandidateViewSkillGo, CandidateViewSkillKafka, CandidateViewSkillPostgreSQL,
},
},
{Specialization: SpecializationDevopsSRE, Skills: []CandidateViewSkillCode{CandidateViewSkillDocker}},
},
}
}
// TrustCoefficient returns the coefficient of an evidence trust level. An
// unknown level has none.
func (policy MatchingPolicy) TrustCoefficient(trust EvidenceTrust) (BasisPoints, bool) {
switch trust {
case EvidenceTrustStated:
return policy.TrustStated, true
case EvidenceTrustOnlineUnconfirmed:
return policy.TrustOnline, true
case EvidenceTrustIdentityTied:
return policy.TrustIdentity, true
case EvidenceTrustInPerson:
return policy.TrustInPerson, true
default:
return 0, false
}
}
// AttributionCoefficient returns the coefficient of an evidence attribution.
func (policy MatchingPolicy) AttributionCoefficient(attribution EvidenceAttribution) (BasisPoints, bool) {
switch attribution {
case EvidenceAttributionPersonal:
return policy.AttributionSelf, true
case EvidenceAttributionTeamRole:
return policy.AttributionTeamRole, true
case EvidenceAttributionTeamUnattributed:
return policy.AttributionTeamUnattributed, true
default:
return 0, false
}
}
// RelationCoefficient returns the coefficient of a skill relation. A skill
// that is unrelated to the requested one earns nothing.
func (policy MatchingPolicy) RelationCoefficient(relation EvidenceSkillRelation) BasisPoints {
switch relation {
case EvidenceSkillRelationExact:
return policy.RelationExact
case EvidenceSkillRelationNarrower:
return policy.RelationNarrower
case EvidenceSkillRelationBroader:
return policy.RelationBroader
case EvidenceSkillRelationNone:
return 0
default:
return 0
}
}
// Validate rejects a zero, out-of-range, or inconsistent section.
func (policy MatchingPolicy) Validate() error {
return firstError(
policy.validateShares(),
policy.validateWeights(),
policy.validateOrdering(),
)
}
func (policy MatchingPolicy) validateShares() error {
const location = "MatchingPolicy.Validate"
shares := []struct {
field string
value BasisPoints
}{
{"matching.competition_boost_bp", policy.CompetitionBoost},
{"matching.neutral_unknown_bp", policy.NeutralUnknown},
{"matching.near_skill_threshold_bp", policy.NearSkillThreshold},
{"matching.trust_stated_bp", policy.TrustStated},
{"matching.trust_online_bp", policy.TrustOnline},
{"matching.trust_identity_bp", policy.TrustIdentity},
{"matching.trust_in_person_bp", policy.TrustInPerson},
{"matching.attribution_personal_bp", policy.AttributionSelf},
{"matching.attribution_team_role_bp", policy.AttributionTeamRole},
{"matching.attribution_team_unattributed_bp", policy.AttributionTeamUnattributed},
{"matching.relation_exact_bp", policy.RelationExact},
{"matching.relation_narrower_bp", policy.RelationNarrower},
{"matching.relation_broader_bp", policy.RelationBroader},
}
for _, share := range shares {
if err := checkRange(location, share.field, share.value, 0, basisPointsPerUnit); err != nil {
return err
}
}
// A floor of zero would let one unknown multiplier erase the score, and a
// floor of one would switch the multiplier off.
return firstError(
checkRange(location, "matching.freshness_floor_bp", policy.FreshnessFloor, 1, basisPointsPerUnit),
checkRange(location, "matching.responsiveness_floor_bp", policy.ResponsivenessFloor, 1, basisPointsPerUnit),
)
}
func (policy MatchingPolicy) validateWeights() error {
const location = "MatchingPolicy.Validate"
if err := firstError(
checkRange(location, "matching.required_skill_weight", policy.RequiredSkillWeight, 1, maxMatchingSkillWeight),
checkRange(location, "matching.desired_skill_weight", policy.DesiredSkillWeight, 1, maxMatchingSkillWeight),
checkRange(location, "matching.percentile_min_cohort", policy.PercentileMinCohort, 1, maxMatchingCohortMinimum),
checkRange(location, "matching.max_results_per_group", policy.MaxResultsPerGroup, 1, maxMatchingResults),
policy.validateTaxonomy(),
); err != nil {
return err
}
for _, sum := range []struct {
field string
values []BasisPoints
}{
{"matching.fit_*_weight_bp", []BasisPoints{policy.FitCoverageWeight, policy.FitDomainWeight, policy.FitSemanticsWeight}},
{"matching.rank_*_weight_bp", []BasisPoints{policy.RankFitWeight, policy.RankStrengthWeight}},
} {
var total BasisPoints
for _, value := range sum.values {
if err := checkRange(location, sum.field, value, 0, basisPointsPerUnit); err != nil {
return err
}
total += value
}
if total != basisPointsPerUnit {
return invalidPolicy(location, sum.field+" must add up to 1.0000")
}
}
return nil
}
// validateOrdering keeps a stronger confirmation from counting for less than
// a weaker one, and a closer relation from counting for less than a looser one.
func (policy MatchingPolicy) validateOrdering() error {
const location = "MatchingPolicy.Validate"
if policy.TrustStated > policy.TrustOnline || policy.TrustOnline > policy.TrustIdentity || policy.TrustIdentity > policy.TrustInPerson {
return invalidPolicy(location, "matching trust coefficients must not decrease with the trust level")
}
if policy.AttributionTeamUnattributed > policy.AttributionTeamRole || policy.AttributionTeamRole > policy.AttributionSelf {
return invalidPolicy(location, "matching attribution coefficients must not increase from personal to team results")
}
if policy.RelationBroader > policy.RelationNarrower || policy.RelationNarrower > policy.RelationExact {
return invalidPolicy(location, "matching relation coefficients must not increase from broader to exact")
}
return nil
}
// validateTaxonomy keeps each specialization and technology known and listed
// once, so a relation never depends on the order or a repeat.
func (policy MatchingPolicy) validateTaxonomy() error {
const location = "MatchingPolicy.Validate"
seen := make(map[SpecializationCode]struct{}, len(policy.SkillTaxonomy))
if len(policy.SkillTaxonomy) > len(specializationCodes) {
return invalidPolicy(location, "matching.skill_taxonomy has more groups than specializations")
}
for _, group := range policy.SkillTaxonomy {
if !group.Specialization.IsKnown() {
return invalidPolicy(location, "matching.skill_taxonomy names an unknown specialization")
}
if _, repeated := seen[group.Specialization]; repeated {
return invalidPolicy(location, "matching.skill_taxonomy repeats a specialization")
}
seen[group.Specialization] = struct{}{}
if len(group.Skills) == 0 || len(group.Skills) > len(candidateViewSkillCodes) {
return invalidPolicy(location, "matching.skill_taxonomy needs between one and every known technology for a specialization")
}
skills := make(map[CandidateViewSkillCode]struct{}, len(group.Skills))
for _, skill := range group.Skills {
if !skill.IsKnown() {
return invalidPolicy(location, "matching.skill_taxonomy names an unknown technology")
}
if _, repeated := skills[skill]; repeated {
return invalidPolicy(location, "matching.skill_taxonomy repeats a technology")
}
skills[skill] = struct{}{}
}
}
return nil
}
@@ -0,0 +1,187 @@
package domain
import (
"bytes"
"errors"
"reflect"
"testing"
)
func TestDemoProductPolicyV4CarriesTheMatchingSection(t *testing.T) {
policy := DemoProductPolicyV4()
if err := policy.Validate(); err != nil {
t.Fatalf("DemoProductPolicyV4().Validate() error = %v", err)
}
if policy.Matching == nil || policy.Assessment.Signals == nil || policy.Support == nil {
t.Fatalf("DemoProductPolicyV4() sections = matching:%v signals:%v support:%v, want all", policy.Matching != nil, policy.Assessment.Signals != nil, policy.Support != nil)
}
if DemoProductPolicyV3().Matching != nil {
t.Fatal("DemoProductPolicyV3() gained a matching section: a stored version must not change")
}
encoded, _, err := encodeProductPolicy(policy)
if err != nil {
t.Fatalf("encodeProductPolicy() error = %v", err)
}
decoded, err := decodeProductPolicy(encoded)
if err != nil {
t.Fatalf("decodeProductPolicy() error = %v", err)
}
if decoded.Matching == nil || !reflect.DeepEqual(*decoded.Matching, *policy.Matching) {
t.Fatalf("decoded matching policy = %+v, want %+v", decoded.Matching, policy.Matching)
}
}
func TestMatchingPolicyIsAnIndependentSchemaTwoExtension(t *testing.T) {
policy := DemoProductPolicyV1()
matching := DemoMatchingPolicy()
policy.Matching = &matching
encoded, _, err := encodeProductPolicy(policy)
if err != nil {
t.Fatalf("encodeProductPolicy() error = %v", err)
}
decoded, err := decodeProductPolicy(encoded)
if err != nil {
t.Fatalf("decodeProductPolicy() error = %v", err)
}
if decoded.Matching == nil || decoded.Assessment.Attempt != nil || decoded.Assessment.Training != nil ||
decoded.Assessment.Signals != nil || decoded.Support != nil {
t.Fatalf("decoded extensions = matching:%v attempt:%v training:%v signals:%v support:%v, want only matching",
decoded.Matching != nil, decoded.Assessment.Attempt != nil, decoded.Assessment.Training != nil,
decoded.Assessment.Signals != nil, decoded.Support != nil)
}
legacy := editPolicySchemaDocument(t, []byte(demoProductPolicyV1Document), func(document map[string]any) {
document["matching"] = nil
})
if _, err := decodeProductPolicy(legacy); !errors.Is(err, ErrInvalidPolicy) {
t.Fatalf("decodeProductPolicy(schema 1 with a matching key) error = %v, want ErrInvalidPolicy", err)
}
}
func TestMatchingPolicyDocumentRequiresEveryFieldAndRejectsUnknownOnes(t *testing.T) {
encoded, _, err := encodeProductPolicy(DemoProductPolicyV4())
if err != nil {
t.Fatalf("encodeProductPolicy() error = %v", err)
}
missing := bytes.Replace(encoded, []byte(`"neutral_unknown_bp":5000,`), nil, 1)
if bytes.Equal(missing, encoded) {
t.Fatal("encoded matching section did not contain neutral_unknown_bp")
}
if _, err := decodeProductPolicy(missing); !errors.Is(err, ErrInvalidPolicy) {
t.Fatalf("decodeProductPolicy(missing neutral_unknown_bp) error = %v, want ErrInvalidPolicy", err)
}
unknown := bytes.Replace(encoded, []byte(`"neutral_unknown_bp":5000`), []byte(`"neutral_unknown_bp":5000,"unknown":1`), 1)
if _, err := decodeProductPolicy(unknown); !errors.Is(err, ErrInvalidPolicy) {
t.Fatalf("decodeProductPolicy(unknown matching field) error = %v, want ErrInvalidPolicy", err)
}
}
func TestMatchingPolicyRejectsInconsistentValues(t *testing.T) {
tests := []struct {
name string
change func(*MatchingPolicy)
}{
{name: "fit weights do not add up", change: func(policy *MatchingPolicy) { policy.FitCoverageWeight = 7000 }},
{name: "rank weights do not add up", change: func(policy *MatchingPolicy) { policy.RankFitWeight = 6000 }},
{name: "share above one", change: func(policy *MatchingPolicy) { policy.NeutralUnknown = 10001 }},
{name: "zero freshness floor", change: func(policy *MatchingPolicy) { policy.FreshnessFloor = 0 }},
{name: "zero responsiveness floor", change: func(policy *MatchingPolicy) { policy.ResponsivenessFloor = 0 }},
{name: "trust falls with the level", change: func(policy *MatchingPolicy) { policy.TrustOnline = 2000 }},
{name: "team result above a personal one", change: func(policy *MatchingPolicy) { policy.AttributionTeamRole = 10001 }},
{name: "broader relation above exact", change: func(policy *MatchingPolicy) {
policy.RelationBroader = 10000
policy.RelationNarrower = 9000
policy.RelationExact = 8000
}},
{name: "zero required weight", change: func(policy *MatchingPolicy) { policy.RequiredSkillWeight = 0 }},
{name: "zero cohort minimum", change: func(policy *MatchingPolicy) { policy.PercentileMinCohort = 0 }},
{name: "no results allowed", change: func(policy *MatchingPolicy) { policy.MaxResultsPerGroup = 0 }},
{name: "unbounded results", change: func(policy *MatchingPolicy) { policy.MaxResultsPerGroup = 1001 }},
{name: "unknown specialization in the taxonomy", change: func(policy *MatchingPolicy) { policy.SkillTaxonomy[0].Specialization = "chef" }},
{name: "unknown technology in the taxonomy", change: func(policy *MatchingPolicy) { policy.SkillTaxonomy[0].Skills[0] = "cobol" }},
{name: "repeated technology in a group", change: func(policy *MatchingPolicy) { policy.SkillTaxonomy[0].Skills = []CandidateViewSkillCode{"go", "go"} }},
{name: "repeated specialization in the taxonomy", change: func(policy *MatchingPolicy) { policy.SkillTaxonomy[1].Specialization = SpecializationBackend }},
{name: "empty group in the taxonomy", change: func(policy *MatchingPolicy) { policy.SkillTaxonomy[1].Skills = nil }},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
policy := DemoProductPolicyV4()
test.change(policy.Matching)
if err := policy.Validate(); !errors.Is(err, ErrInvalidPolicy) {
t.Fatalf("ProductPolicy.Validate() error = %v, want ErrInvalidPolicy", err)
}
})
}
}
func TestMatchingPolicyDemoValuesAreTheDesignValuesOfThePRD(t *testing.T) {
policy := DemoMatchingPolicy()
for level, want := range map[EvidenceTrust]BasisPoints{
EvidenceTrustStated: 2500, EvidenceTrustOnlineUnconfirmed: 6000, EvidenceTrustIdentityTied: 8500, EvidenceTrustInPerson: 10000,
} {
if got, ok := policy.TrustCoefficient(level); !ok || got != want {
t.Errorf("TrustCoefficient(%d) = %d, %v, want %d", level, got, ok, want)
}
}
if _, ok := policy.TrustCoefficient(EvidenceTrust(4)); ok {
t.Error("TrustCoefficient(4) reported a coefficient for an unknown level")
}
for attribution, want := range map[EvidenceAttribution]BasisPoints{
EvidenceAttributionPersonal: 10000, EvidenceAttributionTeamRole: 8000, EvidenceAttributionTeamUnattributed: 5000,
} {
if got, ok := policy.AttributionCoefficient(attribution); !ok || got != want {
t.Errorf("AttributionCoefficient(%s) = %d, %v, want %d", attribution, got, ok, want)
}
}
for relation, want := range map[EvidenceSkillRelation]BasisPoints{
EvidenceSkillRelationExact: 10000, EvidenceSkillRelationNarrower: 8000, EvidenceSkillRelationBroader: 4000, EvidenceSkillRelationNone: 0,
} {
if got := policy.RelationCoefficient(relation); got != want {
t.Errorf("RelationCoefficient(%d) = %d, want %d", relation, got, want)
}
}
}
func TestMatchingPolicyRelatesSkillsByItsOwnTaxonomy(t *testing.T) {
policy := DemoMatchingPolicy()
tests := []struct {
name string
requested, offered string
want EvidenceSkillRelation
}{
{"same technology", "go", "go", EvidenceSkillRelationExact},
{"specialization evidence for a technology", "go", "backend", EvidenceSkillRelationBroader},
{"technology evidence for a specialization", "backend", "go", EvidenceSkillRelationNarrower},
{"another technology", "go", "kafka", EvidenceSkillRelationNone},
{"unrelated specialization", "go", "frontend", EvidenceSkillRelationNone},
{"devops covers docker only", "go", "devops_sre", EvidenceSkillRelationNone},
{"devops covers docker", "docker", "devops_sre", EvidenceSkillRelationBroader},
{"unmapped requested skill", "", "backend", EvidenceSkillRelationNone},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
if got := policy.RelateSkill(test.requested, test.offered); got != test.want {
t.Fatalf("RelateSkill(%q, %q) = %d, want %d", test.requested, test.offered, got, test.want)
}
})
}
// A version without a taxonomy relates nothing but equal codes, and a
// changed version changes the relation: the version decides the result.
policy.SkillTaxonomy = nil
if got := policy.RelateSkill("go", "backend"); got != EvidenceSkillRelationNone {
t.Fatalf("RelateSkill without a taxonomy = %d, want none", got)
}
policy.SkillTaxonomy = []MatchingSkillGroup{{Specialization: SpecializationFrontend, Skills: []CandidateViewSkillCode{"docker"}}}
if got := policy.RelateSkill("docker", "frontend"); got != EvidenceSkillRelationBroader {
t.Fatalf("RelateSkill with a changed taxonomy = %d, want broader", got)
}
}
func TestMatchingPolicyCloneDoesNotShareTheTaxonomy(t *testing.T) {
original := DemoMatchingPolicy()
copied := original.Clone()
copied.SkillTaxonomy[0].Skills[0] = "kafka"
copied.SkillTaxonomy[1].Specialization = SpecializationQA
if original.SkillTaxonomy[0].Skills[0] == "kafka" || original.SkillTaxonomy[1].Specialization == SpecializationQA {
t.Fatal("a clone of the matching policy shares its taxonomy with the original")
}
}