Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions apps/web/src/application/ports/llm-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,7 @@ import type { MatchCandidate } from "../../domain/matching/match-strategy";
import type { ParticipantProfile } from "../../domain/participant/participant.entity";

export interface LlmProvider {
/** Identifies the provider and model, recorded with every reranked result. */
readonly id: string;
rerank(viewer: ParticipantProfile, candidates: MatchCandidate[]): Promise<MatchCandidate[]>;
}
3 changes: 2 additions & 1 deletion apps/web/src/application/ports/match-repository.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type { MatchCandidate } from "../../domain/matching/match-strategy";

export interface MatchRepository {
save(eventId: string, participantId: string, candidates: MatchCandidate[]): Promise<void>;
/** Replaces the participant's matches; array order is the order shown to them. */
save(eventId: string, participantId: string, candidates: MatchCandidate[], computationVersion: string): Promise<void>;
listForParticipant(eventId: string, participantId: string, limit?: number): Promise<MatchCandidate[]>;
}
2 changes: 1 addition & 1 deletion apps/web/src/application/use-cases/request-intro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ export async function requestIntro(
dependencies.participants.findProfile(input.eventId, input.requesterId),
dependencies.participants.findProfile(input.eventId, input.recipientId),
]);
if (!requester || !recipient || !recipient.visible) throw new Error("This participant is unavailable");
if (!requester || !recipient || !recipient.visible || !recipient.profileComplete) throw new Error("This participant is unavailable");
const intro = await dependencies.intros.create(input);
if (recipient.email && dependencies.notifications) {
await dependencies.notifications.introRequested({
Expand Down
13 changes: 10 additions & 3 deletions apps/web/src/domain/matching/pipeline.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,12 @@ export interface MatchingInput {
limit?: number;
}

/**
* Bump when scorers, weights, or stage behavior change, so persisted matches
* from an older computation can be recognised and recomputed.
*/
export const MATCHING_PIPELINE_VERSION = "v1";

/** Same retrieve/filter/score/top-K/rerank pipeline for both entry points. */
export class MatchingPipeline {
private readonly retrieve: RetrieveStage;
Expand Down Expand Up @@ -56,7 +62,8 @@ export class MatchingPipeline {
async run(input: MatchingInput) {
if (input.mode === "search" && !input.query?.trim()) throw new Error("Enter a search query");
const storedProfile = await this.participants.findProfile(input.eventId, input.participantId);
if (!storedProfile) throw new Error("Complete your event profile before continuing");
// Hidden viewers may still browse; only a saved profile is required.
if (!storedProfile?.profileComplete) throw new Error("Complete your event profile before continuing");

const embeddingText = input.mode === "search" ? input.query!.trim() : profileText(storedProfile);
const embedding = input.mode === "profile" && storedProfile.embedding
Expand All @@ -77,10 +84,10 @@ export class MatchingPipeline {
const compatible = this.filter.execute(viewer, retrieved);
const scored = this.score.execute(viewer, compatible);
const top = this.topK.execute(scored, input.limit ?? 12);
const ranked = await this.rerank.execute(viewer, top);
const { candidates: ranked, rankedBy } = await this.rerank.execute(viewer, top);

if (input.mode === "profile") {
await this.persist.execute(input.eventId, input.participantId, ranked);
await this.persist.execute(input.eventId, input.participantId, ranked, `${MATCHING_PIPELINE_VERSION}+${rankedBy}`);
}
return ranked;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import type { ParticipantProfile } from "../../participant/participant.entity";
import type { Specification } from "./specification";

/** A profile counts as complete once the participant has saved it for the event. */
export class CompleteProfileSpecification implements Specification<ParticipantProfile> {
isSatisfiedBy(candidate: ParticipantProfile): boolean {
return candidate.profileComplete === true;
}
}
5 changes: 4 additions & 1 deletion apps/web/src/domain/matching/stages/intent-filter.stage.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import type { ParticipantProfile } from "../../participant/participant.entity";
import { CompleteProfileSpecification } from "../specifications/complete-profile.spec";
import { IntentCompatibleSpecification } from "../specifications/intent-compatible.spec";
import { VisibleSpecification } from "../specifications/visible.spec";

export class IntentFilterStage {
execute(viewer: ParticipantProfile, candidates: ParticipantProfile[]): ParticipantProfile[] {
const intent = new IntentCompatibleSpecification(viewer.intent);
const visible = new VisibleSpecification();
return candidates.filter((candidate) => intent.isSatisfiedBy(candidate) && visible.isSatisfiedBy(candidate));
const complete = new CompleteProfileSpecification();
return candidates.filter((candidate) =>
intent.isSatisfiedBy(candidate) && visible.isSatisfiedBy(candidate) && complete.isSatisfiedBy(candidate));
}
}
16 changes: 12 additions & 4 deletions apps/web/src/domain/matching/stages/llm-rerank.stage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,16 +2,24 @@ import type { LlmProvider } from "../../../application/ports/llm-provider";
import type { ParticipantProfile } from "../../participant/participant.entity";
import type { MatchCandidate } from "../match-strategy";

export interface RerankResult {
candidates: MatchCandidate[];
/** `llm:<provider id>` when the model ordered the list, `score` for the fallback. */
rankedBy: string;
}

export class LlmRerankStage {
constructor(private readonly provider: LlmProvider | null) {}

async execute(viewer: ParticipantProfile, candidates: MatchCandidate[]): Promise<MatchCandidate[]> {
if (!this.provider || candidates.length === 0) return candidates.map(addFallbackReason);
async execute(viewer: ParticipantProfile, candidates: MatchCandidate[]): Promise<RerankResult> {
const scored = { candidates: candidates.map(addFallbackReason), rankedBy: "score" };
if (!this.provider || candidates.length === 0) return scored;
try {
return await this.provider.rerank(viewer, candidates);
const reranked = await this.provider.rerank(viewer, candidates);
return { candidates: reranked.map(addFallbackReason), rankedBy: `llm:${this.provider.id}` };
} catch (error) {
console.warn("[matching] LLM rerank unavailable; using scored order", error);
return candidates.map(addFallbackReason);
return scored;
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions apps/web/src/domain/matching/stages/persist.stage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import type { MatchCandidate } from "../match-strategy";

export class PersistStage {
constructor(private readonly matches: MatchRepository) {}
execute(eventId: string, participantId: string, candidates: MatchCandidate[]): Promise<void> {
return this.matches.save(eventId, participantId, candidates);
execute(eventId: string, participantId: string, candidates: MatchCandidate[], computationVersion: string): Promise<void> {
return this.matches.save(eventId, participantId, candidates, computationVersion);
}
}
32 changes: 20 additions & 12 deletions apps/web/src/infrastructure/postgres/match.repo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import type { MatchRepository } from "../../application/ports/match-repository";
import type { MatchCandidate } from "../../domain/matching/match-strategy";
import type { ParticipantProfile } from "../../domain/participant/participant.entity";
import { Intent } from "../../domain/participant/intent";
import { ELIGIBLE_CANDIDATE } from "./participant.repo";

interface MatchRow {
event_id: string;
Expand All @@ -25,18 +26,25 @@ interface MatchRow {
};

export class PostgresMatchRepository implements MatchRepository {
async save(eventId: string, participantId: string, candidates: MatchCandidate[]): Promise<void> {
async save(eventId: string, participantId: string, candidates: MatchCandidate[], computationVersion: string): Promise<void> {
await transaction(async (client) => {
await client.query(`delete from event_matches where event_id = $1 and participant_id = $2`, [eventId, participantId]);
for (const candidate of candidates) {
await client.query(
`insert into event_matches
(event_id, participant_id, candidate_id, score, score_breakdown, match_reason, mutual_interest)
values ($1, $2, $3, $4, $5::jsonb, $6, $7)`,
[eventId, participantId, candidate.participant.attendeeId, candidate.score,
JSON.stringify(candidate.scoreBreakdown), candidate.reason, candidate.mutualInterest]
);
}
if (candidates.length === 0) return;
// Array position is the final (possibly reranked) order, stored as rank 1..N.
await client.query(
`insert into event_matches
(event_id, participant_id, candidate_id, rank, score, score_breakdown, match_reason, mutual_interest, computation_version)
select $1, $2, c.candidate_id, c.rank, c.score, c.score_breakdown, c.match_reason, c.mutual_interest, $3
from unnest($4::uuid[], $5::int[], $6::numeric[], $7::jsonb[], $8::text[], $9::boolean[])
as c(candidate_id, rank, score, score_breakdown, match_reason, mutual_interest)`,
[eventId, participantId, computationVersion,
candidates.map((candidate) => candidate.participant.attendeeId),
candidates.map((_, index) => index + 1),
candidates.map((candidate) => candidate.score),
candidates.map((candidate) => JSON.stringify(candidate.scoreBreakdown)),
candidates.map((candidate) => candidate.reason),
candidates.map((candidate) => candidate.mutualInterest)]
);
});
}

Expand All @@ -54,8 +62,8 @@ export class PostgresMatchRepository implements MatchRepository {
from event_matches m
join event_participants p on p.event_id = m.event_id and p.attendee_id = m.candidate_id
join registered_attendees a on a.id = p.attendee_id
where m.event_id = $1 and m.participant_id = $2
order by m.score desc, m.created_at desc limit $3`,
where m.event_id = $1 and m.participant_id = $2 and ${ELIGIBLE_CANDIDATE}
order by m.rank, m.candidate_id limit $3`,
[eventId, participantId, Math.max(1, Math.min(100, limit))]
);
return rows.map((row) => ({
Expand Down
10 changes: 8 additions & 2 deletions apps/web/src/infrastructure/postgres/participant.repo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,12 @@ const PROFILE_COLUMNS = `p.event_id, a.id as attendee_id, a.name,
p.venue_zone, p.visible, p.embedding::text as embedding, p.profile_updated_at`;
const PROFILE_FROM = `from event_participants p
join registered_attendees a on a.id = p.attendee_id`;
/**
* Who other participants may see as a candidate: on this event's roster (the
* join), visible, named, and with a saved event profile. Every results path —
* fresh retrieval, cached ids, saved matches — applies this same rule.
*/
export const ELIGIBLE_CANDIDATE = `p.visible = true and a.name is not null and p.profile_updated_at is not null`;

export class PostgresParticipantRepository implements ParticipantRepository {
async findProfile(eventId: string, attendeeId: string): Promise<ParticipantProfile | null> {
Expand Down Expand Up @@ -72,7 +78,7 @@ export class PostgresParticipantRepository implements ParticipantRepository {
const vector = toVector(input.embedding ?? null);
const { rows } = await query<ProfileRow>(
`select ${PROFILE_COLUMNS} ${PROFILE_FROM}
where p.event_id = $1 and ($2::uuid is null or a.id <> $2::uuid) and p.visible = true and a.name is not null
where p.event_id = $1 and ($2::uuid is null or a.id <> $2::uuid) and ${ELIGIBLE_CANDIDATE}
order by case when $3::vector is not null and p.embedding is not null then 0 else 1 end,
p.embedding <=> $3::vector nulls last, a.name asc
limit $4`,
Expand All @@ -85,7 +91,7 @@ export class PostgresParticipantRepository implements ParticipantRepository {
if (!ids.length) return [];
const { rows } = await query<ProfileRow>(
`select ${PROFILE_COLUMNS} ${PROFILE_FROM}
where p.event_id = $1 and a.id = any($2::uuid[]) and p.visible = true
where p.event_id = $1 and a.id = any($2::uuid[]) and ${ELIGIBLE_CANDIDATE}
order by array_position($2::uuid[], a.id)`,
[eventId, ids]
);
Expand Down
8 changes: 7 additions & 1 deletion apps/web/src/infrastructure/providers/gemini-llm.provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,17 @@ import type { LlmProvider } from "../../application/ports/llm-provider";
import type { MatchCandidate } from "../../domain/matching/match-strategy";
import type { ParticipantProfile } from "../../domain/participant/participant.entity";

const DEFAULT_MODEL = "gemini-3.8-flash";

export class GeminiLlmProvider implements LlmProvider {
get id(): string {
return `gemini:${process.env.GEMINI_LLM_MODEL || DEFAULT_MODEL}`;
}

async rerank(viewer: ParticipantProfile, candidates: MatchCandidate[]): Promise<MatchCandidate[]> {
const apiKey = process.env.GEMINI_API_KEY;
if (!apiKey) return candidates;
const model = process.env.GEMINI_LLM_MODEL || "gemini-3.8-flash";
const model = process.env.GEMINI_LLM_MODEL || DEFAULT_MODEL;
const input = candidates.map(({ participant, score, mutualInterest }) => ({
id: participant.attendeeId,
name: participant.name,
Expand Down
34 changes: 34 additions & 0 deletions packages/db/migrations/0004_match_rank.sql
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
-- Persist the final order of saved matches.
--
-- The LLM rerank can order the shortlist differently from the numeric score,
-- but rows were stored without a position and read back by score, so a page
-- reload silently undid the rerank. `rank` is the 1-based position shown to the
-- participant; `computation_version` records which pipeline and reranker
-- produced the list, so stale results can be identified and recomputed.

alter table event_matches add column if not exists rank integer;
alter table event_matches add column if not exists computation_version text not null default 'legacy';

-- Existing rows keep the order they were already displayed in.
update event_matches m
set rank = ordered.position
from (
select event_id, participant_id, candidate_id,
row_number() over (
partition by event_id, participant_id
order by score desc, created_at desc, candidate_id
) as position
from event_matches
) ordered
where m.event_id = ordered.event_id
and m.participant_id = ordered.participant_id
and m.candidate_id = ordered.candidate_id
and m.rank is null;

alter table event_matches alter column rank set not null;
alter table event_matches add constraint event_matches_rank_positive check (rank > 0);
-- New rows must say which computation produced them.
alter table event_matches alter column computation_version drop default;

create unique index if not exists idx_event_matches_rank on event_matches(event_id, participant_id, rank);
drop index if exists idx_event_matches_participant;
112 changes: 112 additions & 0 deletions tests/integration/candidate-eligibility.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
/**
* Hidden, incomplete, removed, and other-event participants must not appear
* through any results path: fresh retrieval, cached search ids, or saved
* matches. Runs against a real Postgres and is skipped when DATABASE_URL is unset.
*/
import { afterAll, beforeAll, describe, expect, it } from "vitest";
import { query, closePool, attendees } from "@match-maker/db";
import { migrate } from "../../packages/db/src/migrate";
import { PostgresParticipantRepository } from "../../apps/web/src/infrastructure/postgres/participant.repo";
import { PostgresMatchRepository } from "../../apps/web/src/infrastructure/postgres/match.repo";
import { RetrieveStage } from "../../apps/web/src/domain/matching/stages/retrieve.stage";
import { Intent } from "../../apps/web/src/domain/participant/intent";
import type { MatchCandidate } from "../../apps/web/src/domain/matching/match-strategy";

const hasDatabase = Boolean(process.env.DATABASE_URL);
const describeDb = hasDatabase ? describe : describe.skip;

const ORG_SLUG = "integration-eligibility";
const KEYS = ["viewer", "eligible", "hidden", "incomplete", "removed", "other"] as const;
type Key = (typeof KEYS)[number];
const emailOf = (key: Key) => `eligibility-${key}@example.com`;

describeDb("candidate eligibility", () => {
const participants = new PostgresParticipantRepository();
const matches = new PostgresMatchRepository();
let eventId: string;
let otherEventId: string;
let ids: Record<Key, string>;

beforeAll(async () => {
await migrate();
await attendees.upsertMany(KEYS.map((key) => ({ name: key, email: emailOf(key) })));
const found = await attendees.findIdsByEmails(KEYS.map(emailOf));
ids = Object.fromEntries(KEYS.map((key) => [key, found.find((row) => row.email === emailOf(key))!.id])) as Record<Key, string>;

const { rows: [org] } = await query<{ id: string }>(
`insert into organizations (name, slug) values ('Eligibility test', $1)
on conflict (slug) do update set name = excluded.name returning id`, [ORG_SLUG]
);
const event = async (slug: string) => (await query<{ id: string }>(
`insert into events (organization_id, name, slug, status) values ($1, $2, $2, 'open')
on conflict (organization_id, slug) do update set status = 'open' returning id`, [org.id, slug]
)).rows[0].id;
eventId = await event(ORG_SLUG);
otherEventId = await event(`${ORG_SLUG}-other`);

const join = (event: string, key: Key, saved: boolean, visible = true) => query(
`insert into event_participants (event_id, attendee_id, visible, profile_updated_at)
values ($1, $2, $3, case when $4 then now() end)
on conflict (event_id, attendee_id) do update
set visible = excluded.visible, profile_updated_at = excluded.profile_updated_at`,
[event, ids[key], visible, saved]
);
await join(eventId, "viewer", true);
await join(eventId, "eligible", true);
await join(eventId, "hidden", true, false);
await join(eventId, "incomplete", false);
await join(eventId, "removed", true);
await join(otherEventId, "other", true);

// Saved before "removed" left the roster; "hidden"/"incomplete" changed after matching.
await matches.save(eventId, ids.viewer,
(["hidden", "eligible", "incomplete", "removed"] as const).map((key) => candidate(key)), "v1+score");
await query(`delete from event_participants where event_id = $1 and attendee_id = $2`, [eventId, ids.removed]);
});

afterAll(async () => {
await query(`delete from organizations where slug = $1`, [ORG_SLUG]);
await query(`delete from registered_attendees where email = any($1::text[])`, [KEYS.map(emailOf)]);
await closePool();
});

function candidate(key: Key): MatchCandidate {
return {
participant: {
eventId, attendeeId: ids[key], name: key, designation: null, domain: null, aboutMe: null,
selfDescription: null, yearsOfExperience: null, mostImpressiveBuild: null,
intent: Intent.NETWORKING, interests: [], venueZone: null, visible: true,
},
score: 50, scoreBreakdown: {}, mutualInterest: false, reason: `Reason for ${key}`,
};
}
const keysOf = (rows: Array<{ attendeeId: string }>) =>
rows.map((row) => KEYS.find((key) => ids[key] === row.attendeeId) ?? row.attendeeId);

it("returns only eligible candidates from fresh retrieval", async () => {
const rows = await participants.listCandidates({ eventId, excludeAttendeeId: ids.viewer });
expect(keysOf(rows)).toEqual(["eligible"]);
});

it("re-checks eligibility when hydrating cached ids", async () => {
const allIds = KEYS.map((key) => ids[key]);
expect(keysOf(await participants.findCandidatesByIds(eventId, allIds)).sort()).toEqual(["eligible", "viewer"]);

// A cache entry written before people became ineligible still yields only current candidates.
const cache = { get: async () => allIds, set: async () => {} };
const retrieved = await new RetrieveStage(participants, cache)
.execute({ eventId, viewerId: ids.viewer, embedding: null, query: "anything" });
expect(keysOf(retrieved)).toEqual(["eligible"]);
});

it("filters saved matches that are no longer eligible", async () => {
const saved = await matches.listForParticipant(eventId, ids.viewer);
expect(keysOf(saved.map((match) => match.participant))).toEqual(["eligible"]);
});

it("keeps a hidden viewer's own matches readable", async () => {
await query(`update event_participants set visible = false where event_id = $1 and attendee_id = $2`, [eventId, ids.viewer]);
const saved = await matches.listForParticipant(eventId, ids.viewer);
expect(keysOf(saved.map((match) => match.participant))).toEqual(["eligible"]);
});
});
Loading