diff --git a/backend/app/data/people.py b/backend/app/data/people.py index 3584c51..70ac00a 100644 --- a/backend/app/data/people.py +++ b/backend/app/data/people.py @@ -33,6 +33,9 @@ ("São Paulo", "Brazil"), ("Tokyo", "Japan"), ] +# Every 13th generated attendee also studied here, so alumni matching has a second, smaller network to find. +# Assigned without the random generator, so every other generated value stays the same. +SECOND_SCHOOL, SECOND_SCHOOL_EVERY = "BUET", 13 COMPANIES = ["Wasatch Cloud", "Redwood Labs", "Northbeam", "Harborline", "Copperleaf", "Bluefin Data", "Lumen Grid"] TITLES = ["Platform Engineer", "SRE", "Software Engineer", "ML Engineer", "DevOps Lead", "Engineering Manager"] COMMUNITIES = ["CNCF Ambassadors", "Women in Cloud Native", "Kubernetes contributors", "Local meetup organisers"] @@ -109,7 +112,7 @@ def sample_attendees(n: int = 80) -> list[dict]: "company": rng.choice(COMPANIES), "bio": f"Works on {interests[0].lower()} and {interests[3]}.", "interests": interests, - "schools": [rng.choice(SCHOOLS)], + "schools": [rng.choice(SCHOOLS)] + ([SECOND_SCHOOL] if i % SECOND_SCHOOL_EVERY == 0 else []), "past_companies": rng.sample(COMPANIES, 1), "communities": rng.sample(COMMUNITIES, rng.randint(0, 2)), "city": city, diff --git a/backend/app/embeddings.py b/backend/app/embeddings.py index 552d734..5e10c98 100644 --- a/backend/app/embeddings.py +++ b/backend/app/embeddings.py @@ -22,6 +22,7 @@ COST = meter.create_counter("confox.embeddings.cost", unit="USD", description="Estimated embedding cost") BATCH = 100 +EMBED_CHARS = 2000 # US dollars per million input tokens (OpenAI list prices). PRICE_PER_MTOK = {"text-embedding-3-small": 0.02, "text-embedding-3-large": 0.13} @@ -35,6 +36,18 @@ def _client() -> OpenAI: return OpenAI(api_key=settings.openai_api_key.strip()) +def join_text(*parts) -> str: + """Non-empty parts on their own lines (lists joined with commas), trimmed to EMBED_CHARS.""" + flat = [", ".join(p) if isinstance(p, list) else p for p in parts] + return "\n".join(str(p).strip() for p in flat if p)[:EMBED_CHARS] + + +def person_text(p: dict) -> str: + """What a person is about, for their embedding. Shared by the loader and profile saves, so a saved profile is + embedded exactly like a loaded one.""" + return join_text(p["name"], p.get("title"), p.get("company"), p.get("interests_text"), p.get("bio")) + + def cost_usd(model: str, tokens: int) -> float: return tokens * PRICE_PER_MTOK.get(model, 0.0) / 1_000_000 diff --git a/backend/app/indices.py b/backend/app/indices.py index 669e040..3f04028 100644 --- a/backend/app/indices.py +++ b/backend/app/indices.py @@ -12,6 +12,15 @@ TEXT_KW = {"type": "text", "fields": {"raw": {"type": "keyword", "ignore_above": 512}}} # Semantic search vector. Elasticsearch 9 keeps it out of `_source` unless a request asks for it. EMBEDDING = {"type": "dense_vector", "dims": settings.embed_dims, "similarity": "cosine", "index": True} +# Fields only the profile editor writes. Kept separate so a save can add them to an index loaded before they existed. +PROFILE_FIELDS = { + "projects": {"type": "keyword"}, + "tracks": {"type": "keyword"}, + "looking_for": {"type": "text"}, + "links": {"type": "keyword", "index": False}, + "visibility": {"type": "keyword"}, + "updated_at": LOCAL_TIME, +} MAPPINGS: dict[str, dict] = { settings.idx_sessions: { @@ -58,6 +67,7 @@ # Speakers' published links, shown in session details; stored, never searched. "links": {"type": "object", "enabled": False}, "embedding": EMBEDDING, + **PROFILE_FIELDS, } }, settings.idx_activity: { diff --git a/backend/app/load.py b/backend/app/load.py index 45a8c98..41fc0f1 100644 --- a/backend/app/load.py +++ b/backend/app/load.py @@ -19,7 +19,7 @@ from .data.people import sample_attendees, speakers from .data.samples import attendee_agendas, sample_activity from .data.sessions import build_sessions -from .embeddings import embed, enabled +from .embeddings import embed, enabled, join_text, person_text from .es import es from .indices import rebuild from .telemetry import setup_telemetry, shutdown_telemetry @@ -27,21 +27,10 @@ log = logging.getLogger("confox.load") tracer = trace.get_tracer("confox.load") -EMBED_CHARS = 2000 - - -def _join(*parts) -> str: - flat = [", ".join(p) if isinstance(p, list) else p for p in parts] - return "\n".join(str(p).strip() for p in flat if p)[:EMBED_CHARS] - def session_text(s: dict) -> str: """What a session is about, for its embedding: title, track, projects, then the description.""" - return _join(s["title"], s.get("track"), s.get("projects"), s.get("description")) - - -def person_text(p: dict) -> str: - return _join(p["name"], p.get("title"), p.get("company"), p.get("interests_text"), p.get("bio")) + return join_text(s["title"], s.get("track"), s.get("projects"), s.get("description")) def with_embeddings(docs: list[dict], text) -> list[dict]: diff --git a/backend/app/routers/brief.py b/backend/app/routers/brief.py index 360dd54..dda3086 100644 --- a/backend/app/routers/brief.py +++ b/backend/app/routers/brief.py @@ -23,7 +23,6 @@ import logging from datetime import datetime -from elasticsearch import ApiError from fastapi import APIRouter, Query from opentelemetry import trace @@ -31,7 +30,7 @@ from ..config import settings from ..es import es from ..now import next_food -from .people import SOURCE_EXCLUDES, _load_user, build_match_query, why +from .people import _load_user, rank_people, why from .schedule import _day_sessions, _knn, annotate log = logging.getLogger(__name__) @@ -293,23 +292,10 @@ def _agenda(user_id: str) -> list[dict]: def _ranked_people(user_id: str, user: dict, vector: list | None) -> list[dict]: - """The Match ranking (same query as /api/people/match), lexical if vector scoring fails.""" - - def run(vec: list | None) -> dict: - query = build_match_query(user_id, user, vector=vec) - return es.search( - index=settings.idx_people, query=query, size=PEOPLE_CANDIDATES, source_excludes=SOURCE_EXCLUDES - ) - - try: - res = run(vector) - except ApiError as exc: - if not vector: - raise - log.warning("brief: vector scoring failed, ranking people lexically: %s", exc) - trace.get_current_span().record_exception(exc) - res = run(None) - return [h["_source"] | {"id": h["_id"]} for h in res["hits"]["hits"]] + """The Match ranking for the current profile (same pipeline as /api/people/match), best first.""" + ranked, _, mode = rank_people(user_id, user, vector, size=PEOPLE_CANDIDATES) + trace.get_current_span().set_attribute("confox.brief.people_mode", mode) + return ranked @router.get("") diff --git a/backend/app/routers/people.py b/backend/app/routers/people.py index 773faf5..c652f63 100644 --- a/backend/app/routers/people.py +++ b/backend/app/routers/people.py @@ -1,9 +1,14 @@ """People: profiles and Match. -Match ranks other people for the signed-in user by what they share: schools, current or past company, -communities, city and interests. Each shared value adds a fixed boost, so the ranking is explainable, and the -"why" reasons are computed in Python from the same overlap. When the user's profile has an embedding, cosine -similarity is added on top as a smaller weighted term (see `build_match_query`). +Match ranks other people for the signed-in user, read fresh from Elasticsearch on every request, so a profile +edit changes the next ranking. The pipeline: + +1. Candidates and relevance: reciprocal rank fusion of a lexical list (BM25 of the user's topics on + `interests_text` and `bio`, plus a fixed boost per shared value) and a semantic list (kNN on the profile + `embedding`). Native `rrf` retriever when the licence allows it, else the same fusion in Python. +2. Boosts: the fused score is scaled to at most RRF_WEIGHT and the shared-value boosts are added on top, so a + shared school always outranks a close embedding. +3. Reasons: `why` is computed in Python from the same overlap the boosts count, so every reason is true. """ import logging @@ -15,6 +20,7 @@ from .. import activity from ..config import settings from ..es import es +from .search import SearchFailed, is_license_error, rrf_fuse log = logging.getLogger(__name__) router = APIRouter(prefix="/api/people", tags=["people"]) @@ -23,12 +29,16 @@ ) # Fixed boosts per shared value. Schools weigh most: alumni ties are the demo's headline reason. -BOOST = {"schools": 6.0, "company": 3.0, "communities": 2.0, "city": 2.0, "interests": 1.5} -RELATED_BOOST = 0.5 # soft text match of the user's interests, so speakers (track names) still rank by topic -VECTOR_WEIGHT = 4.0 # max contribution of cosine similarity; below one shared school by design +BOOST = {"schools": 6.0, "company": 3.0, "communities": 2.0, "city": 2.0, "country": 1.0, "interests": 1.5} +RELATED_BOOST = 0.5 # soft text match of the user's topics, so speakers (track names) still rank by topic +RRF_WEIGHT = 4.0 # the fused rank adds at most this; below one shared school by design +RRF_K = 60 +RANK_WINDOW = 100 +NUM_CANDIDATES = 200 MAX_REASONS = 3 TEXT_FIELDS = ["name^3", "title^2", "company^2", "interests_text^2", "bio"] SOURCE_EXCLUDES = ["embedding"] +PRIVATE = {"term": {"visibility": "private"}} # Query parameter -> indexed field(s). `company` matches the current or a past company. FILTER_FIELDS: dict[str, list[str]] = { @@ -42,6 +52,9 @@ } GROUPS = ["schools", "companies", "communities", "city", "country"] +# Whether this cluster accepts the native rrf retriever; None until the first hybrid match finds out. +_native_rrf: bool | None = None + def _values(doc: dict, field: str) -> list[str]: v = doc.get(field) @@ -55,6 +68,19 @@ def companies(doc: dict) -> list[str]: return list(dict.fromkeys(_values(doc, "company") + _values(doc, "past_companies"))) +def topics(user: dict) -> list[str]: + """What the user is into: interests, then keywords or projects, then chosen tracks, without duplicates + (ignoring case). Other people's `interests` hold all three kinds (attendees list projects there, speakers + their session tracks), so each topic is matched against that one field.""" + seen: set[str] = set() + out = [] + for v in _values(user, "interests") + _values(user, "projects") + _values(user, "tracks"): + if v.lower() not in seen: + seen.add(v.lower()) + out.append(v) + return out + + def group_values(user: dict) -> dict[str, list[str]]: """The user's own values per group; groups and boosts are restricted to these.""" return { @@ -71,50 +97,65 @@ def _shared(mine: list[str], theirs: list[str]) -> list[str]: return [v for v in mine if v in their_set] +def affinity(user: dict, person: dict) -> float: + """The fixed boosts for what two people share; the same table the lexical query uses.""" + score = BOOST["schools"] * len(_shared(_values(user, "schools"), _values(person, "schools"))) + score += BOOST["company"] if _shared(companies(user), companies(person)) else 0.0 + score += BOOST["communities"] * len(_shared(_values(user, "communities"), _values(person, "communities"))) + score += BOOST["city"] if _shared(_values(user, "city"), _values(person, "city")) else 0.0 + score += BOOST["country"] if _shared(_values(user, "country"), _values(person, "country")) else 0.0 + score += BOOST["interests"] * len(_shared(topics(user), _values(person, "interests"))) + return score + + def why(user: dict, person: dict) -> list[dict]: """Up to three reasons, most telling first. - Order: schools, the first shared interest, company, community, city, further interests, related topics, then - interests named in the bio. + Order: schools, the first shared topic, company, community, city (or country when the city differs), further + topics, related topics, then topics named in the bio. """ - interests = _shared(_values(user, "interests"), _values(person, "interests")) + mine = topics(user) + shared = _shared(mine, _values(person, "interests")) + verb = "Speaks on" if person.get("kind") == "speaker" else "Both into" reasons = [ {"label": f"{v} alumni", "field": "schools", "value": v} for v in _shared(_values(user, "schools"), _values(person, "schools")) ] - reasons += [{"label": f"Both into {v}", "field": "interests", "value": v} for v in interests[:1]] + reasons += [{"label": f"{verb} {v}", "field": "interests", "value": v} for v in shared[:1]] for v in _shared(companies(user), companies(person)): - verb = "Works at" if v == person.get("company") else "Worked at" - reasons.append({"label": f"{verb} {v}", "field": "company", "value": v}) + label = "Works at" if v == person.get("company") else "Worked at" + reasons.append({"label": f"{label} {v}", "field": "company", "value": v}) reasons += [ {"label": f"Both in {v}", "field": "communities", "value": v} for v in _shared(_values(user, "communities"), _values(person, "communities")) ] - reasons += [ - {"label": f"Also in {v}", "field": "city", "value": v} - for v in _shared(_values(user, "city"), _values(person, "city")) - ] - reasons += [{"label": f"Both into {v}", "field": "interests", "value": v} for v in interests[1:]] + city = _shared(_values(user, "city"), _values(person, "city")) + reasons += [{"label": f"Also in {v}", "field": "city", "value": v} for v in city] + if not city: + reasons += [ + {"label": f"Also from {v}", "field": "country", "value": v} + for v in _shared(_values(user, "country"), _values(person, "country")) + ] + reasons += [{"label": f"{verb} {v}", "field": "interests", "value": v} for v in shared[1:]] verb = "Speaks on" if person.get("kind") == "speaker" else "Into" reasons += [{"label": f"{verb} {v}", "field": "interests", "value": v} for v in related_topics(user, person)] bio = (person.get("bio") or "").lower() - named = [u for u in _values(user, "interests") if u not in interests and u.lower() in bio] + named = [u for u in mine if u not in shared and u.lower() in bio] reasons += [{"label": f"Mentions {v}", "field": "q", "value": v} for v in named] # field q: a keyword search return reasons[:MAX_REASONS] def related_topics(user: dict, person: dict) -> list[str]: - """The person's topics that contain, or are contained in, one of the user's interests, ignoring case. + """The person's topics that contain, or are contained in, one of the user's topics, ignoring case. Speakers' interests are session tracks ("AI Inference + Agentic"), which rarely equal an attendee interest ("AI inference") exactly. The person's own value is returned, so it works as an exact filter. """ - mine = [u.lower() for u in _values(user, "interests")] - exact = set(_values(user, "interests")) + mine = [u.lower() for u in topics(user)] return [ p for p in _values(person, "interests") - if p not in exact and any(u in p.lower() or p.lower() in u for u in mine) + if p.lower() not in mine and any(u in p.lower() or p.lower() in u for u in mine) ] @@ -137,15 +178,15 @@ def build_filters(filters: dict[str, str | None]) -> list[dict]: return out -def build_match_query( - user_id: str, user: dict, q: str = "", kind: str | None = None, vector: list | None = None -) -> dict: - """The scoring query: fixed boosts per shared value, plus an optional keyword match and vector similarity. +def keyword_query(q: str) -> dict: + return {"multi_match": {"query": q, "fields": TEXT_FIELDS, "fuzziness": "AUTO"}} + + +def build_match_query(user_id: str, user: dict, q: str = "", kind: str | None = None) -> dict: + """The lexical side: a fixed boost per shared value plus BM25 of the user's topics, optionally a keyword match. Every candidate matches (minimum_should_match 0), so people with nothing in common still appear, just lower. - With a vector the bool query is wrapped in script_score adding VECTOR_WEIGHT * max(0, cosine). A weighted sum - rather than RRF keeps the explainable boosts in charge: a shared school always outranks a close embedding, - and aggregations and post_filter keep working on one plain query. + The user and anyone who set their profile to private are left out. """ should = [] for v in _values(user, "schools"): @@ -156,37 +197,119 @@ def build_match_query( should.append(_boost("communities", [v], BOOST["communities"])) if city := _values(user, "city"): should.append(_boost("city", city, BOOST["city"])) - interests = _values(user, "interests") - for v in interests: + if country := _values(user, "country"): + should.append(_boost("country", country, BOOST["country"])) + mine = topics(user) + for v in mine: should.append(_boost("interests", [v], BOOST["interests"])) - if interests: + if mine: should.append( - {"multi_match": {"query": " ".join(interests), "fields": ["interests_text", "bio"], "boost": RELATED_BOOST}} + {"multi_match": {"query": " ".join(mine), "fields": ["interests_text", "bio"], "boost": RELATED_BOOST}} ) query: dict = { "bool": { - "must_not": [{"ids": {"values": [user_id]}}], + "must_not": [{"ids": {"values": [user_id]}}, PRIVATE], "should": should, "minimum_should_match": 0, } } if q: - query["bool"]["must"] = [{"multi_match": {"query": q, "fields": TEXT_FIELDS, "fuzziness": "AUTO"}}] + query["bool"]["must"] = [keyword_query(q)] if kind: query["bool"]["filter"] = build_filters({"kind": kind}) + return query + + +def knn_clause( + user_id: str, vector: list[float], q: str = "", kind: str | None = None, post: list | None = None +) -> dict: + """The semantic side: the people nearest the profile vector, under the same filters as the lexical side. + + Filters apply while the graph is searched, so `k` neighbours survive them; a keyword `q` becomes a filter too. + """ + flt: list[dict] = [{"bool": {"must_not": [{"ids": {"values": [user_id]}}, PRIVATE]}}] + if kind: + flt += build_filters({"kind": kind}) + if q: + flt.append(keyword_query(q)) + flt += post or [] + return { + "field": "embedding", + "query_vector": vector, + "k": RANK_WINDOW, + "num_candidates": NUM_CANDIDATES, + "filter": flt, + } + + +def match_body( + user_id: str, + user: dict, + vector: list[float] | None = None, + q: str = "", + kind: str | None = None, + post: list | None = None, + aggs: dict | None = None, +) -> dict: + """One search: the native rrf retriever over both sides when there is a vector, else the lexical query. + + Returns the whole rank window; `rerank` adds the boosts and cuts it to the page size. `post` filters go in + post_filter, so the group counts in `aggs` stay stable while chips are toggled. + """ + lexical = build_match_query(user_id, user, q, kind) + body: dict = {"size": RANK_WINDOW, "_source": {"excludes": SOURCE_EXCLUDES}} if vector: - query = { - "script_score": { - "query": query, - "script": { - "source": "doc['embedding'].size() == 0 ? _score" - " : _score + params.w * Math.max(0, cosineSimilarity(params.v, 'embedding'))", - "params": {"v": vector, "w": VECTOR_WEIGHT}, - }, + body["retriever"] = { + "rrf": { + "retrievers": [ + {"standard": {"query": lexical}}, + {"knn": knn_clause(user_id, vector, q, kind, post)}, + ], + "rank_window_size": RANK_WINDOW, + "rank_constant": RRF_K, } } - return query + else: + body["query"] = lexical + if aggs: + body["aggs"] = aggs + if post: + body["post_filter"] = {"bool": {"filter": post}} + return body + + +def knn_body(user_id: str, vector: list[float], q: str = "", kind: str | None = None, post: list | None = None) -> dict: + """The semantic side on its own, for client-side fusion.""" + return { + "size": RANK_WINDOW, + "knn": knn_clause(user_id, vector, q, kind, post), + "_source": {"excludes": SOURCE_EXCLUDES}, + } + + +def rerank(user: dict, fused: list[dict], lists: int, size: int) -> list[dict]: + """Final order: the shared-value boosts plus the fused rank scaled to at most RRF_WEIGHT. + + `fused` hits carry their RRF score in `_score`; the best possible is one first place per list, so dividing by + lists / (RRF_K + 1) maps it to 0..1. Ties keep the fused order. Each hit gets `score`, `affinity` and `why`. + """ + best = lists / (RRF_K + 1) + out = [] + for hit in fused: + person = _person(hit) + rrf = float(hit.get("_score") or 0.0) / best if best else 0.0 + boost = affinity(user, person) + out.append( + person + | { + "score": round(boost + RRF_WEIGHT * min(rrf, 1.0), 3), + "affinity": boost, + "why": why(user, person), + } + ) + out.sort(key=lambda p: -p["score"]) # stable + return out[:size] def build_group_aggs(user: dict) -> dict: @@ -216,7 +339,8 @@ def parse_groups(user: dict, aggs: dict) -> dict[str, list[dict]]: def _load_user(user_id: str) -> tuple[dict, list | None]: - """The user's profile and, if one exists, their embedding (Elasticsearch 9 leaves vectors out of _source).""" + """The user's profile as stored right now, and its embedding if there is one. Never cached: a profile edit + must change the very next ranking. Elasticsearch 9 leaves vectors out of _source unless asked.""" try: doc = es.get(index=settings.idx_people, id=user_id, source_exclude_vectors=False) except NotFoundError as exc: @@ -231,6 +355,60 @@ def _person(hit: dict) -> dict: return {**src, "id": hit["_id"]} +def _msearch(bodies: list[dict]) -> list[dict]: + searches = [part for body in bodies for part in ({"index": settings.idx_people}, body)] + responses = es.msearch(searches=searches)["responses"] + for r in responses: + if "error" in r: + raise SearchFailed(r["error"]) + return responses + + +def rank_people( + user_id: str, + user: dict, + vector: list | None, + q: str = "", + kind: str | None = None, + post: list | None = None, + aggs: dict | None = None, + size: int = 20, +) -> tuple[list[dict], dict, str]: + """Ranked people (with score, affinity, why), the aggregations, and which mode ran: + `hybrid` (native rrf retriever), `hybrid-client` (RRF in Python on a basic licence) or `bm25` (no vector, + or vector search failed). Failures that change the mode are logged and recorded on the span.""" + global _native_rrf + span = trace.get_current_span() + if vector and _native_rrf is not False: + try: + (res,) = _msearch([match_body(user_id, user, vector, q, kind, post, aggs)]) + _native_rrf = True + return rerank(user, res["hits"]["hits"], 2, size), res.get("aggregations", {}), "hybrid" + except (ApiError, SearchFailed) as exc: + detail = exc.error if isinstance(exc, SearchFailed) else getattr(exc, "body", None) + if is_license_error(detail) or is_license_error(exc): + _native_rrf = False + log.warning("native rrf retriever not licensed; people match fuses in the API from now on: %s", exc) + span.add_event("confox.match.rrf_fallback", {"reason": str(exc)[:500]}) + else: + # The vector field may be missing or mid-rebuild; rank lexically rather than fail the page. + log.warning("people match: vector search failed, ranking lexically: %s", exc, exc_info=exc) + vector = None + span.record_exception(exc) + lexical_body = match_body(user_id, user, None, q, kind, post, aggs) + if vector: + try: + lexical, neighbours = _msearch([lexical_body, knn_body(user_id, vector, q, kind, post)]) + fused = rrf_fuse([lexical["hits"]["hits"], neighbours["hits"]["hits"]], RANK_WINDOW, RRF_K, RANK_WINDOW) + return rerank(user, fused, 2, size), lexical.get("aggregations", {}), "hybrid-client" + except (ApiError, SearchFailed) as exc: + log.warning("people match: kNN failed, ranking lexically: %s", exc, exc_info=exc) + span.record_exception(exc) + (res,) = _msearch([lexical_body]) + fused = rrf_fuse([res["hits"]["hits"]], RANK_WINDOW, RRF_K, RANK_WINDOW) + return rerank(user, fused, 1, size), res.get("aggregations", {}), "bm25" + + @router.get("/match") def match( user_id: str = settings.demo_user, @@ -244,47 +422,30 @@ def match( kind: str = "", size: int = 20, ) -> dict: - """People ranked for the user, each with up to three reasons, plus counts of others sharing the user's values. - - `semantic` says whether embedding similarity took part in the ranking. - Filters other than kind go in post_filter, so group counts stay stable while the user toggles chips. + """People ranked for the user's current profile, each with up to three reasons, plus counts of others sharing + the user's values. `mode` says how the ranking ran and `semantic` whether the profile vector took part. """ filters = {"school": school, "company": company, "community": community, "interest": interest} filters |= {"country": country, "city": city} match_requests.add(1, {"kind": kind or "all", "has_query": bool(q.strip()), "filtered": any(filters.values())}) user, vector = _load_user(user_id) activity.record("match", user_id, q.strip()) # only once the user is known to exist - post = build_filters(filters) - body = { - "size": max(1, min(size, 100)), - "source_excludes": SOURCE_EXCLUDES, - "aggs": build_group_aggs(user), - } - if post: - body["post_filter"] = {"bool": {"filter": post}} - - def run(vec: list | None) -> dict: - query = build_match_query(user_id, user, q.strip(), kind or None, vec) - return es.search(index=settings.idx_people, query=query, **body) - - try: - res = run(vector) - except ApiError as exc: - if not vector: - raise - # The vector field may be missing or being rebuilt; rank without it rather than fail the page. - log.warning("vector scoring failed, falling back to lexical: %s", exc, exc_info=exc) - trace.get_current_span().record_exception(exc) - vector = None - res = run(None) - trace.get_current_span().set_attribute("confox.match.semantic", bool(vector)) - - results = [] - for hit in res["hits"]["hits"]: - person = _person(hit) - results.append({**person, "score": round(float(hit["_score"] or 0), 3), "why": why(user, person)}) - groups = parse_groups(user, res.get("aggregations", {})) - return {"results": results, "groups": groups, "semantic": bool(vector)} + results, aggs, mode = rank_people( + user_id, + user, + vector, + q.strip(), + kind or None, + build_filters(filters), + build_group_aggs(user), + max(1, min(size, RANK_WINDOW)), + ) + span = trace.get_current_span() + span.set_attribute("confox.match.semantic", mode != "bm25") + span.set_attribute("confox.match.mode", mode) + for r in results: + r.pop("affinity", None) + return {"results": results, "groups": parse_groups(user, aggs), "semantic": mode != "bm25", "mode": mode} @router.get("/{person_id}") diff --git a/backend/app/routers/profile.py b/backend/app/routers/profile.py new file mode 100644 index 0000000..92fefc7 --- /dev/null +++ b/backend/app/routers/profile.py @@ -0,0 +1,274 @@ +"""Profile: read and edit the signed-in user's profile, the input to People Match, For you and My brief. + +A save writes the whole document with refresh, so the next Match or Schedule request ranks against it. The +embedding is recomputed from the same text recipe as the loader (`embeddings.person_text`), and only when that +text changed: editing schools or links costs no model call. Without an OpenAI key the profile is saved without a +vector and the response says so; matching then runs on keywords and shared background only. +""" + +import logging +from typing import Annotated, Literal +from urllib.parse import urlparse + +from elasticsearch import ApiError, NotFoundError +from fastapi import APIRouter, HTTPException +from fastapi.exceptions import RequestValidationError +from opentelemetry import metrics, trace +from pydantic import AfterValidator, BaseModel, ConfigDict, Field, StringConstraints + +from .. import embeddings +from ..clock import now +from ..config import settings +from ..es import es +from ..indices import PROFILE_FIELDS +from .people import topics + +log = logging.getLogger(__name__) +router = APIRouter(prefix="/api/profile", tags=["profile"]) +tracer = trace.get_tracer("confox.profile") +updates = metrics.get_meter("confox.profile").create_counter( + "confox.profile.updates", unit="{update}", description="Profile saves" +) + +FIRST_SCHOOL = "University of Utah" # demo data lists it first wherever universities are ranked by default +HIDDEN_TRACKS = {"Registration", "Breaks"} +OPTION_SIZE = 40 + +# ---------- validation ---------- + + +def _dedupe(values: list[str]) -> list[str]: + """Drop repeats, ignoring case; the first spelling wins.""" + seen: set[str] = set() + out = [] + for v in values: + if v.lower() not in seen: + seen.add(v.lower()) + out.append(v) + return out + + +def _url(value: str) -> str: + parsed = urlparse(value) + if parsed.scheme not in ("http", "https") or "." not in parsed.netloc: + raise ValueError("must be a full http or https address, like https://github.com/emma") + return value + + +Text = Annotated[str, StringConstraints(strip_whitespace=True, max_length=80)] +Item = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=80)] +Phrase = Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=40)] +Url = Annotated[str, StringConstraints(strip_whitespace=True, max_length=300), AfterValidator(_url)] + + +def _items(max_items: int, kind=Item): + return Annotated[list[kind], Field(max_length=max_items), AfterValidator(_dedupe)] + + +class ProfileIn(BaseModel): + """Everything the profile editor can change. Unknown fields are refused.""" + + model_config = ConfigDict(extra="forbid") + + name: Annotated[str, StringConstraints(strip_whitespace=True, min_length=1, max_length=80)] + title: Text = "" + company: Text = "" + city: Text = "" + country: Text = "" + bio: Annotated[str, StringConstraints(strip_whitespace=True, max_length=500)] = "" + interests: _items(12, Phrase) = [] + projects: _items(20, Phrase) = [] + tracks: _items(12) = [] + schools: _items(8) = [] + past_companies: _items(10) = [] + communities: _items(10) = [] + looking_for: Annotated[str, StringConstraints(strip_whitespace=True, max_length=200)] = "" + links: _items(3, Url) = [] + visibility: Literal["public", "private"] = "public" + + +EDITABLE = list(ProfileIn.model_fields) +LIST_FIELDS = {name for name, f in ProfileIn.model_fields.items() if f.default == []} + +# ---------- pure helpers ---------- + + +def editable(doc: dict) -> dict: + """The editable fields of a stored profile, with empty defaults for fields it does not have yet.""" + out = {} + for name in EDITABLE: + default = [] if name in LIST_FIELDS else ("public" if name == "visibility" else "") + value = doc.get(name) + out[name] = default if value is None else value + return out + + +def build_doc(existing: dict, update: ProfileIn, at: str) -> dict: + """The stored document after a save: fields the editor does not own (kind, sample, picture, session ids) are + kept, `interests_text` is rebuilt from every topic so BM25 and the embedding see them, the vector is left out.""" + doc = {k: v for k, v in existing.items() if k != "embedding"} | update.model_dump() + doc["interests_text"] = ", ".join(topics(doc)) + doc["updated_at"] = at + return doc + + +def changed_fields(old: dict, new: dict) -> list[str]: + """Editable fields whose value differs, in form order. Missing, empty and default values count as equal.""" + before, after = editable(old), editable(new) + return [name for name in EDITABLE if before[name] != after[name]] + + +def embedding_plan(old: dict, new: dict, has_vector: bool, enabled: bool) -> str: + """`unchanged` (same text, keep the vector), `skipped` (no key: save without one) or `updated` (embed).""" + if has_vector and embeddings.person_text(old) == embeddings.person_text(new): + return "unchanged" + return "updated" if enabled else "skipped" + + +def unknown_tracks(chosen: list[str], known: list[str]) -> list[str]: + allowed = set(known) + return [t for t in chosen if t not in allowed] + + +def _keys(agg: dict) -> list[str]: + return [b["key"] for b in agg.get("buckets", [])] + + +def utah_first(schools: list[str]) -> list[str]: + return sorted(schools, key=lambda s: s != FIRST_SCHOOL) # stable: otherwise by count + + +def merge_counts(*aggs: dict) -> list[str]: + """Bucket keys from several terms aggregations, by total count.""" + counts: dict[str, int] = {} + for agg in aggs: + for b in agg.get("buckets", []): + counts[b["key"]] = counts.get(b["key"], 0) + b["doc_count"] + return sorted(counts, key=lambda k: -counts[k]) + + +def parse_options(people_aggs: dict, session_aggs: dict) -> dict[str, list[str]]: + return { + "interests": _keys(people_aggs["attendees"]["interests"]), + "projects": _keys(session_aggs["projects"]), + "tracks": [t for t in _keys(session_aggs["tracks"]) if t not in HIDDEN_TRACKS], + "schools": utah_first(_keys(people_aggs["schools"])), + "companies": merge_counts(people_aggs["company"], people_aggs["past_companies"])[:OPTION_SIZE], + "communities": _keys(people_aggs["communities"]), + "cities": _keys(people_aggs["city"]), + "countries": _keys(people_aggs["country"]), + } + + +def _terms(field: str, size: int = OPTION_SIZE) -> dict: + return {"terms": {"field": field, "size": size}} + + +OPTION_AGGS = { + "people": { + "attendees": {"filter": {"term": {"kind": "attendee"}}, "aggs": {"interests": _terms("interests", 60)}}, + "schools": _terms("schools"), + "company": _terms("company"), + "past_companies": _terms("past_companies"), + "communities": _terms("communities"), + "city": _terms("city"), + "country": _terms("country"), + }, + "sessions": {"tracks": _terms("track", 60), "projects": _terms("projects", 80)}, +} + +# ---------- Elasticsearch ---------- + + +def _known_tracks() -> list[str]: + r = es.search(index=settings.idx_sessions, size=0, aggs={"tracks": OPTION_AGGS["sessions"]["tracks"]}) + return [t for t in _keys(r["aggregations"]["tracks"]) if t not in HIDDEN_TRACKS] + + +def _stored(user_id: str) -> tuple[dict, list | None]: + try: + doc = es.get(index=settings.idx_people, id=user_id, source_exclude_vectors=False) + except NotFoundError as exc: + raise HTTPException(status_code=404, detail=f"unknown user {user_id}") from exc + src = dict(doc["_source"]) + vector = src.pop("embedding", None) + return src, vector if isinstance(vector, list) and vector else None + + +def _ensure_mapping() -> None: + """Add the profile-only fields to an index loaded before they existed (additive; a no-op when present).""" + try: + es.indices.put_mapping(index=settings.idx_people, properties=PROFILE_FIELDS) + except ApiError as exc: # the save still works with dynamic mapping; say so rather than fail it + log.warning("profile: could not add profile fields to the mapping: %s", exc) + trace.get_current_span().record_exception(exc) + + +def _response(user_id: str, doc: dict, has_vector: bool) -> dict: + meta = {k: doc.get(k) for k in ("kind", "sample", "updated_at")} + return {"id": user_id, **editable(doc), **meta, "has_embedding": has_vector} + + +@router.get("/options") +def options() -> dict[str, list[str]]: + """Suggestions for the editor's chip inputs, from aggregations over people and sessions, most common first.""" + searches = [ + {"index": settings.idx_people}, + {"size": 0, "aggs": OPTION_AGGS["people"]}, + {"index": settings.idx_sessions}, + {"size": 0, "aggs": OPTION_AGGS["sessions"]}, + ] + people, sessions = es.msearch(searches=searches)["responses"] + for r in (people, sessions): + if "error" in r: + raise HTTPException(status_code=502, detail="could not load suggestions") + return parse_options(people["aggregations"], sessions["aggregations"]) + + +@router.get("/{user_id}") +def get_profile(user_id: str) -> dict: + doc, vector = _stored(user_id) + return _response(user_id, doc, vector is not None) + + +@router.put("/{user_id}") +def save_profile(user_id: str, update: ProfileIn) -> dict: + """Validate, rebuild interests_text and the embedding, write with refresh, return the profile and what changed. + + Until real sign-in exists, the only person who can save is the signed-in demo user. + """ + if user_id != settings.demo_user: + raise HTTPException(status_code=403, detail="you can only edit your own profile") + with tracer.start_as_current_span("profile.save") as span: + span.set_attribute("confox.profile.user", user_id) + if bad := unknown_tracks(update.tracks, _known_tracks()): + raise RequestValidationError( + [{"type": "value_error", "loc": ("body", "tracks"), "msg": f"unknown track: {', '.join(bad)}"}] + ) + old, vector = _stored(user_id) + doc = build_doc(old, update, now().isoformat(timespec="seconds")) + changed = changed_fields(old, doc) + plan = embedding_plan(old, doc, vector is not None, embeddings.enabled()) + note = "" + if plan == "unchanged": + doc["embedding"] = vector + elif plan == "updated": + try: + doc["embedding"] = embeddings.embed([embeddings.person_text(doc)])[0] + except Exception as exc: + # Save the edit anyway; without a vector Match and For you run on keywords and shared background. + log.warning("profile: embedding failed, saving without a vector: %s", exc, exc_info=exc) + span.record_exception(exc) + plan = "failed" + note = "Saved, but the embedding could not be computed; matching uses keywords only until next save." + else: + note = "Saved without an embedding (no OPENAI_API_KEY); matching uses keywords and shared background only." + + _ensure_mapping() + es.index(index=settings.idx_people, id=user_id, document=doc, refresh="wait_for") + span.set_attribute("confox.profile.changed", ",".join(changed)) + span.set_attribute("confox.profile.embedding", plan) + updates.add(1, {"embedding": plan, "changed": bool(changed)}) + log.info("profile %s saved: changed=%s embedding=%s", user_id, changed, plan) + has_vector = "embedding" in doc + return {"profile": _response(user_id, doc, has_vector), "changed": changed, "embedding": plan, "note": note} diff --git a/backend/app/routers/schedule.py b/backend/app/routers/schedule.py index 1fcff15..99bfb8f 100644 --- a/backend/app/routers/schedule.py +++ b/backend/app/routers/schedule.py @@ -20,7 +20,7 @@ from ..clock import now from ..config import settings from ..es import es -from .people import build_match_query +from .people import SearchFailed, rank_people router = APIRouter(prefix="/api/schedule", tags=["schedule"]) log = logging.getLogger(__name__) @@ -80,8 +80,10 @@ def for_you( interests: list[str], on_agenda: bool = False, knn_score: float | None = None, + tracks: list[str] | tuple[str, ...] = (), ) -> tuple[bool, list[str], float]: - """Return (for_you, why, fit) for one session. `knn_score` is set only for the day's top kNN neighbours.""" + """Return (for_you, why, fit) for one session. `knn_score` is set only for the day's top kNN neighbours; + `tracks` are the schedule tracks the user picked in their profile.""" reasons: list[str] = [] fit = 0.0 if on_agenda: @@ -99,6 +101,9 @@ def for_you( score = PLACE_FIT[matches[0][1]] + 0.05 * (len(matches) - 1) score += 0.02 * min(3, _title_words(session.get("title") or "", interests)) fit = max(fit, min(score, 0.95)) + elif session.get("track") and session.get("track") in tracks: + reasons.append(f"in your track {session['track']}") + fit = max(fit, PLACE_FIT["track"]) if knn_score is not None: reasons.append("close to your interests") fit = max(fit, min(max(knn_score, 0.0), 0.9)) @@ -163,16 +168,20 @@ def annotate( agenda: list[dict], knn_scores: dict[str, float] | None = None, ) -> list[dict]: - """Add for_you, why, fit, on_agenda and clashes to each session (new dicts; the input is not changed).""" + """Add for_you, why, fit, on_agenda and clashes to each session (new dicts; the input is not changed). + + `profile` is the user's profile as stored now: interests and keywords or projects are matched as phrases, and + chosen tracks match the session track.""" knn_scores = knn_scores or {} interests = list(profile.get("interests") or []) + list(profile.get("projects") or []) interests = list(dict.fromkeys(interests)) + tracks = list(profile.get("tracks") or []) on_agenda_ids = {i.get("session_id") for i in agenda if i.get("kind") == "session" and i.get("session_id")} blockers = blocking_items(agenda, {s["id"]: s.get("kind", "") for s in sessions}) out = [] for s in sessions: is_on = s["id"] in on_agenda_ids - mine, why, fit = for_you(s, interests, is_on, knn_scores.get(s["id"])) + mine, why, fit = for_you(s, interests, is_on, knn_scores.get(s["id"]), tracks) out.append(s | {"for_you": mine, "why": why, "fit": fit, "on_agenda": is_on, "clashes": clashes(s, blockers)}) return pick_per_slot(out) @@ -307,8 +316,9 @@ def _day_sessions(day: str) -> list[dict]: def _profile(user_id: str) -> tuple[dict, list[float] | None]: - """The profile and its vector, if the vector exists yet. Elasticsearch 9 leaves dense vectors out of _source - unless asked.""" + """The profile as stored right now and its vector, if the vector exists yet. Read on every request, never + cached, so a profile edit changes For you at once. Elasticsearch 9 leaves dense vectors out of _source unless + asked.""" try: doc = es.get(index=settings.idx_people, id=user_id, source_exclude_vectors=False) except NotFoundError: @@ -342,33 +352,17 @@ def _all_agenda(user_id: str) -> list[dict]: def _top_matches(user_id: str, profile: dict, vector: list[float] | None) -> list[dict]: - """The top Match results (same query as /api/people/match), names only; lexical if vector scoring fails.""" + """The top Match results (the same ranking as /api/people/match), names only. Empty if ranking fails.""" if not profile: return [] - - def run(vec: list[float] | None) -> list[dict]: - r = es.search( - index=settings.idx_people, - query=build_match_query(user_id, profile, vector=vec), - size=FRIENDS, - source_includes=["name"], - ) - return [{"id": h["_id"], "name": h["_source"].get("name")} for h in r["hits"]["hits"]] - - try: - return run(vector) - except ApiError as exc: - # The vector may be missing or mid-rebuild; rank without it, and without names only if that fails too. - log.warning("schedule: match for going names failed (vector=%s): %s", bool(vector), exc) - trace.get_current_span().record_exception(exc) - if not vector: - return [] try: - return run(None) - except ApiError as exc: - log.warning("schedule: lexical match for going names failed: %s", exc) + ranked, _, _ = rank_people(user_id, profile, vector, size=FRIENDS) + except (ApiError, SearchFailed) as exc: + # Going names are a nicety: the day still loads without them. + log.warning("schedule: match for going names failed: %s", exc) trace.get_current_span().record_exception(exc) return [] + return [{"id": r["id"], "name": r.get("name")} for r in ranked] def _going(session_ids: list[str], user_id: str, people: dict[str, str]) -> dict[str, dict]: diff --git a/backend/tests/test_people.py b/backend/tests/test_people.py index 5be593c..fbfe728 100644 --- a/backend/tests/test_people.py +++ b/backend/tests/test_people.py @@ -1,12 +1,23 @@ """Pure parts of People Match: reasons, query building and group parsing. No Elasticsearch needed.""" +import pytest + +from app.routers import people as pp from app.routers.people import ( BOOST, + RRF_K, + RRF_WEIGHT, + affinity, build_filters, build_group_aggs, build_match_query, + knn_clause, + match_body, parse_groups, + rank_people, related_topics, + rerank, + topics, why, ) @@ -78,17 +89,151 @@ def test_query_boosts_shared_values_with_schools_highest(): assert len([f for f, _ in boosts if "terms" in f and "interests" in f["terms"]]) == 5 # one per interest company = [f for f, b in boosts if b == BOOST["company"]] assert company[0]["bool"]["should"][1] == {"terms": {"past_companies": ["Wasatch Cloud", "Copperleaf"]}} - assert query["bool"]["must_not"] == [{"ids": {"values": ["emma"]}}] + assert query["bool"]["must_not"] == [{"ids": {"values": ["emma"]}}, {"term": {"visibility": "private"}}] + assert ({"terms": {"country": ["United States"]}}, BOOST["country"]) in boosts assert query["bool"]["minimum_should_match"] == 0 assert "must" not in query["bool"] and "filter" not in query["bool"] -def test_query_with_keywords_kind_and_vector(): - query = build_match_query("emma", EMMA, q="kserve", kind="speaker", vector=[0.1, 0.2]) - inner = query["script_score"]["query"] - assert inner["bool"]["must"][0]["multi_match"]["query"] == "kserve" - assert inner["bool"]["filter"] == [{"term": {"kind": "speaker"}}] - assert query["script_score"]["script"]["params"]["v"] == [0.1, 0.2] +def test_query_with_keywords_and_kind(): + query = build_match_query("emma", EMMA, q="kserve", kind="speaker") + assert query["bool"]["must"][0]["multi_match"]["query"] == "kserve" + assert query["bool"]["filter"] == [{"term": {"kind": "speaker"}}] + + +def test_topics_join_interests_projects_and_tracks_without_case_repeats(): + user = {"interests": ["eBPF", "GitOps"], "projects": ["Cilium", "ebpf"], "tracks": ["Security"]} + assert topics(user) == ["eBPF", "GitOps", "Cilium", "Security"] + assert topics({}) == [] + + +def test_profile_topics_drive_boosts_and_reasons(): + emma = EMMA | {"interests": ["eBPF"], "schools": ["University of Utah", "BUET"], "projects": ["Cilium"]} + buet = {"kind": "attendee", "interests": ["eBPF", "Cilium"], "schools": ["Georgia Tech", "BUET"], "city": "Tokyo"} + query = build_match_query("emma", emma) + assert ({"terms": {"schools": ["BUET"]}}, BOOST["schools"]) in _constant_scores(query) + assert ({"terms": {"interests": ["Cilium"]}}, BOOST["interests"]) in _constant_scores(query) + assert why(emma, buet) == [ + {"label": "BUET alumni", "field": "schools", "value": "BUET"}, + {"label": "Both into eBPF", "field": "interests", "value": "eBPF"}, + {"label": "Both into Cilium", "field": "interests", "value": "Cilium"}, + ] + assert affinity(emma, buet) == BOOST["schools"] + 2 * BOOST["interests"] + + +def test_country_reason_only_when_the_city_differs(): + person = {"city": "Austin", "country": "United States"} + assert why(EMMA, person) == [{"label": "Also from United States", "field": "country", "value": "United States"}] + assert affinity(EMMA, person) == BOOST["country"] + same_city = {"city": "Salt Lake City", "country": "United States"} + assert [w["field"] for w in why(EMMA, same_city)] == ["city"] + assert affinity(EMMA, same_city) == BOOST["city"] + BOOST["country"] + + +def test_speakers_sharing_a_chosen_track_speak_on_it(): + speaker = {"kind": "speaker", "interests": ["Security"]} + assert why(EMMA | {"tracks": ["Security"]}, speaker) == [ + {"label": "Speaks on Security", "field": "interests", "value": "Security"} + ] + + +VEC = [0.1, 0.2] + + +def test_hybrid_body_fuses_lexical_and_knn_with_the_same_filters(): + post = build_filters({"school": "BUET"}) + body = match_body("emma", EMMA, VEC, q="cilium", kind="attendee", post=post, aggs={"a": {}}) + rrf = body["retriever"]["rrf"] + assert rrf["rank_constant"] == RRF_K and rrf["rank_window_size"] == body["size"] + standard, knn = (r for r in rrf["retrievers"]) + assert standard["standard"]["query"] == build_match_query("emma", EMMA, "cilium", "attendee") + flt = knn["knn"]["filter"] + assert knn["knn"]["query_vector"] == VEC + assert {"bool": {"must_not": [{"ids": {"values": ["emma"]}}, {"term": {"visibility": "private"}}]}} in flt + assert {"term": {"kind": "attendee"}} in flt and {"term": {"schools": "BUET"}} in flt + assert any("multi_match" in f for f in flt) # a keyword narrows the semantic side too + assert body["post_filter"] == {"bool": {"filter": post}} and body["aggs"] == {"a": {}} + assert body["_source"] == {"excludes": ["embedding"]} + + +def test_lexical_body_without_vector(): + body = match_body("emma", EMMA) + assert "retriever" not in body and body["query"] == build_match_query("emma", EMMA) + assert "post_filter" not in body and "aggs" not in body + + +def test_knn_clause_without_keyword_or_kind(): + clause = knn_clause("emma", VEC) + assert len(clause["filter"]) == 1 and clause["k"] == pp.RANK_WINDOW + + +def _hit(pid: str, score: float, **src) -> dict: + return {"_id": pid, "_score": score, "_source": {"name": pid, **src}} + + +def test_rerank_adds_boosts_on_top_of_the_fused_rank(): + top = 2 / (RRF_K + 1) # first in both lists + fused = [_hit("near", top), _hit("alum", 1 / (RRF_K + 50), schools=["University of Utah"])] + ranked = rerank(EMMA, fused, lists=2, size=10) + assert [p["id"] for p in ranked] == ["alum", "near"] # one shared school beats any embedding + assert ranked[1]["score"] == RRF_WEIGHT and ranked[1]["why"] == [] + assert ranked[0]["affinity"] == BOOST["schools"] + assert ranked[0]["why"][0]["label"] == "University of Utah alumni" + assert "_score" not in ranked[0] and "embedding" not in ranked[0] + assert len(rerank(EMMA, fused, lists=2, size=1)) == 1 + + +class FakePeopleES: + """msearch stand-in. `native` is how a body with a retriever answers: 'ok', 'licence' or 'broken'.""" + + def __init__(self, native: str = "ok"): + self.native = native + self.calls: list[list[dict]] = [] + + def msearch(self, searches): + bodies = searches[1::2] + self.calls.append(bodies) + out = [] + for b in bodies: + if "retriever" in b and self.native == "licence": + out.append( + {"error": {"type": "security_exception", "reason": "current license is non-compliant for [rrf]"}} + ) + elif "retriever" in b and self.native == "broken": + out.append({"error": {"type": "illegal_argument_exception", "reason": "no embedding field"}}) + elif "knn" in b: + out.append({"hits": {"hits": [_hit("k1", 0.9), _hit("both", 0.8)]}}) + else: + hits = [_hit("both", 3.0), _hit("alum", 2.0, schools=["University of Utah"])] + out.append({"hits": {"hits": hits}, "aggregations": {"schools": {}}}) + return {"responses": out} + + +@pytest.mark.parametrize( + ("native", "mode", "calls"), + [("ok", "hybrid", 1), ("licence", "hybrid-client", 2), ("broken", "bm25", 2)], +) +def test_rank_people_modes(monkeypatch, native, mode, calls): + fake = FakePeopleES(native) + monkeypatch.setattr(pp, "es", fake) + monkeypatch.setattr(pp, "_native_rrf", None) + ranked, aggs, used = rank_people("emma", EMMA, VEC, size=5) + assert used == mode and len(fake.calls) == calls + assert ranked[0]["id"] == "alum" # the shared school wins in every mode + if mode == "hybrid-client": + assert pp._native_rrf is False and {r["id"] for r in ranked} == {"alum", "both", "k1"} + rank_people("emma", EMMA, VEC) # remembered: no second native attempt + assert not any("retriever" in b for b in fake.calls[-1]) + if mode == "bm25": + assert not any("knn" in b for b in fake.calls[-1]) + + +def test_rank_people_without_vector_is_lexical(monkeypatch): + fake = FakePeopleES() + monkeypatch.setattr(pp, "es", fake) + ranked, aggs, used = rank_people("emma", EMMA, None) + assert used == "bm25" and len(fake.calls) == 1 and aggs == {"schools": {}} + assert [r["id"] for r in ranked] == ["alum", "both"] def test_filters_are_exact_terms_and_company_covers_past(): diff --git a/backend/tests/test_profile.py b/backend/tests/test_profile.py new file mode 100644 index 0000000..4314ccd --- /dev/null +++ b/backend/tests/test_profile.py @@ -0,0 +1,183 @@ +"""Profile editing: validation, the stored document, embeddings and suggestions. No Elasticsearch, no OpenAI.""" + +import pytest +from fastapi.testclient import TestClient +from pydantic import ValidationError + +from app import embeddings +from app.main import app +from app.routers import profile as pr + +STORED = { + "name": "Emma Carter", + "title": "Platform Engineer", + "company": "Wasatch Cloud", + "bio": "Runs the internal platform for ML teams.", + "interests": ["AI inference", "Kubeflow"], + "interests_text": "AI inference, Kubeflow", + "schools": ["University of Utah"], + "city": "Salt Lake City", + "country": "United States", + "kind": "attendee", + "sample": True, +} + + +def form(**changes) -> dict: + base = {k: v for k, v in pr.editable(STORED).items()} + return base | changes + + +def test_valid_profile_is_trimmed_and_deduplicated(): + p = pr.ProfileIn(**form(name=" Emma ", interests=["eBPF", "ebpf", " GitOps "], links=["https://github.com/emma"])) + assert p.name == "Emma" and p.interests == ["eBPF", "GitOps"] and p.links == ["https://github.com/emma"] + + +@pytest.mark.parametrize( + ("field", "value"), + [ + ("name", " "), + ("bio", "b" * 501), + ("looking_for", "x" * 201), + ("interests", [f"topic {i}" for i in range(13)]), + ("interests", ["x" * 41]), + ("interests", [""]), + ("links", ["https://a.dev", "https://b.dev", "https://c.dev", "https://d.dev"]), + ("links", ["github.com/emma"]), + ("links", ["ftp://example.com"]), + ("visibility", "friends"), + ("embedding", [0.1]), + ("kind", "speaker"), + ], +) +def test_invalid_values_are_refused(field, value): + with pytest.raises(ValidationError) as err: + pr.ProfileIn(**form(**{field: value})) + assert err.value.errors()[0]["loc"][0] == field + + +def test_editable_fills_defaults(): + out = pr.editable({"name": "X"}) + assert out["interests"] == [] and out["looking_for"] == "" and out["visibility"] == "public" + assert set(out) == set(pr.EDITABLE) + + +def test_build_doc_keeps_other_fields_and_rebuilds_interests_text(): + update = pr.ProfileIn(**form(interests=["AI inference", "eBPF"], projects=["Cilium"], tracks=["Security"])) + doc = pr.build_doc(STORED | {"embedding": [1.0]}, update, "2026-11-09T08:41:00") + assert doc["interests_text"] == "AI inference, eBPF, Cilium, Security" + assert doc["kind"] == "attendee" and doc["sample"] is True and "embedding" not in doc + assert doc["updated_at"] == "2026-11-09T08:41:00" + assert pr.changed_fields(STORED, doc) == ["interests", "projects", "tracks"] + assert pr.changed_fields(STORED, pr.build_doc(STORED, pr.ProfileIn(**form()), "t")) == [] + + +def test_embedding_is_recomputed_only_when_the_text_changes(): + same = pr.build_doc(STORED, pr.ProfileIn(**form(schools=["University of Utah", "BUET"])), "t") + assert pr.embedding_plan(STORED, same, has_vector=True, enabled=True) == "unchanged" + new_topic = pr.build_doc(STORED, pr.ProfileIn(**form(interests=["eBPF"])), "t") + assert pr.embedding_plan(STORED, new_topic, has_vector=True, enabled=True) == "updated" + assert pr.embedding_plan(STORED, new_topic, has_vector=True, enabled=False) == "skipped" + assert pr.embedding_plan(STORED, same, has_vector=False, enabled=True) == "updated" + assert embeddings.person_text(new_topic).splitlines()[3] == "eBPF" # same recipe as the loader + + +def test_options_rank_by_count_with_utah_first(): + def terms(*keys): + return {"buckets": [{"key": k, "doc_count": 10 - i} for i, k in enumerate(keys)]} + + people = { + "attendees": {"interests": terms("eBPF", "GitOps")}, + "schools": terms("TU Munich", "BUET", "University of Utah"), + "company": terms("Google", "Wasatch Cloud"), + "past_companies": {"buckets": [{"key": "Wasatch Cloud", "doc_count": 30}]}, + "communities": terms("CNCF Ambassadors"), + "city": terms("Tokyo"), + "country": terms("Japan"), + } + sessions = {"tracks": terms("Maintainer Track", "Registration", "Security", "Breaks"), "projects": terms("Cilium")} + out = pr.parse_options(people, sessions) + assert out["schools"] == ["University of Utah", "TU Munich", "BUET"] + assert out["companies"] == ["Wasatch Cloud", "Google"] + assert out["tracks"] == ["Maintainer Track", "Security"] + assert out["interests"] == ["eBPF", "GitOps"] and out["projects"] == ["Cilium"] + assert pr.unknown_tracks(["Security", "Made up"], out["tracks"]) == ["Made up"] + + +class FakeES: + """Just enough Elasticsearch for a save: the stored doc, the track list and the write.""" + + def __init__(self, vector=None): + self.source = STORED | ({"embedding": vector} if vector else {}) + self.written: dict | None = None + self.indices = self + + def get(self, index, id, **kw): + if id != "emma": + from elasticsearch import NotFoundError + + raise NotFoundError("not found", meta=None, body={}) + return {"_id": id, "_source": dict(self.source)} + + def search(self, index, size, aggs): + return {"aggregations": {"tracks": {"buckets": [{"key": "Security", "doc_count": 3}]}}} + + def put_mapping(self, index, properties): + self.mapping = properties + + def index(self, index, id, document, refresh): + self.written = {"id": id, "document": document, "refresh": refresh} + + +def test_save_without_key_writes_with_refresh_and_says_so(monkeypatch): + fake = FakeES(vector=[0.5, 0.5]) + monkeypatch.setattr(pr, "es", fake) + monkeypatch.setattr(embeddings.settings, "openai_api_key", "") + body = form(interests=["AI inference", "eBPF"], tracks=["Security"]) + r = TestClient(app).put("/api/profile/emma", json=body) + assert r.status_code == 200, r.text + out = r.json() + assert ( + out["changed"] == ["interests", "tracks"] and out["embedding"] == "skipped" and "OPENAI_API_KEY" in out["note"] + ) + assert out["profile"]["has_embedding"] is False and out["profile"]["interests"] == ["AI inference", "eBPF"] + assert fake.written["refresh"] == "wait_for" and "embedding" not in fake.written["document"] + assert fake.written["document"]["interests_text"] == "AI inference, eBPF, Security" + assert "tracks" in fake.mapping + + +def test_save_keeps_the_vector_when_the_text_is_the_same(monkeypatch): + fake = FakeES(vector=[0.5, 0.5]) + monkeypatch.setattr(pr, "es", fake) + monkeypatch.setattr(embeddings, "embed", lambda texts: pytest.fail("no embedding call for a school change")) + r = TestClient(app).put("/api/profile/emma", json=form(schools=["University of Utah", "BUET"])) + assert r.json()["embedding"] == "unchanged" and fake.written["document"]["embedding"] == [0.5, 0.5] + + +def test_save_embeds_new_text(monkeypatch): + fake = FakeES(vector=[0.5, 0.5]) + monkeypatch.setattr(pr, "es", fake) + monkeypatch.setattr(embeddings.settings, "openai_api_key", "test-key-not-real") + monkeypatch.setattr(embeddings, "embed", lambda texts: [[0.1, 0.9]] if "eBPF" in texts[0] else []) + r = TestClient(app).put("/api/profile/emma", json=form(interests=["eBPF"])) + assert r.json()["embedding"] == "updated" and fake.written["document"]["embedding"] == [0.1, 0.9] + + +def test_save_refuses_unknown_tracks_and_users(monkeypatch): + fake = FakeES() + monkeypatch.setattr(pr, "es", fake) + client = TestClient(app) + r = client.put("/api/profile/emma", json=form(tracks=["Made up"])) + assert r.status_code == 422 and r.json()["detail"][0]["loc"] == ["body", "tracks"] + assert client.put("/api/profile/nobody", json=form()).status_code == 403 # only the signed-in user can save + assert client.put("/api/profile/emma", json=form(bio="b" * 501)).status_code == 422 + assert fake.written is None + + +def test_only_the_signed_in_user_can_save_a_profile(): + from fastapi.testclient import TestClient + + from app.main import app + + r = TestClient(app).put("/api/profile/alice", json={"name": "Mallory"}) + assert r.status_code == 403 diff --git a/backend/tests/test_schedule.py b/backend/tests/test_schedule.py index 1561022..dfd1b7f 100644 --- a/backend/tests/test_schedule.py +++ b/backend/tests/test_schedule.py @@ -116,3 +116,17 @@ def test_truncate(): assert truncate("short") == "short" assert len(truncate("x" * 500)) == 300 assert truncate(None) == "" + + +def test_profile_tracks_mark_sessions_in_that_track(): + talk = session("t", "11:00", "11:30", "Hardening clusters") | {"track": "Security"} + assert for_you(talk, [], tracks=["Security"]) == (True, ["in your track Security"], 0.65) + assert for_you(talk, [], tracks=["Observability"]) == (False, [], 0.0) + out = annotate([talk], {"interests": [], "tracks": ["Security"]}, []) + assert out[0]["for_you"] and out[0]["why"] == ["in your track Security"] + + +def test_profile_projects_count_as_interest_phrases(): + talk = session("e", "11:17", "11:22", "eBPF Observability with Inspektor Gadget") + out = annotate([talk], {"interests": [], "projects": ["eBPF"]}, []) + assert out[0]["for_you"] and out[0]["why"] == ["matches eBPF"] diff --git a/backend/tests/test_schedule_day.py b/backend/tests/test_schedule_day.py index 10ea48e..b845665 100644 --- a/backend/tests/test_schedule_day.py +++ b/backend/tests/test_schedule_day.py @@ -111,3 +111,30 @@ def test_summary_and_facets(): assert facets["level"] == [{"key": "Beginner", "count": 1}] assert facets["venue"][0] == {"key": "Hyatt", "count": 2} assert day_facets([])["track"] == [] + + +def test_top_matches_uses_the_people_ranking(monkeypatch): + """Going names come from the same ranking as People; a signature change there must not break the day view.""" + from app.routers import schedule + + calls = [] + + def fake_rank(user_id, user, vector, q="", kind=None, post=None, aggs=None, size=20): + calls.append((user_id, size)) + return [{"id": "alice", "name": "Alice Moreno"}], {}, "bm25" + + monkeypatch.setattr(schedule, "rank_people", fake_rank) + assert schedule._top_matches("emma", {"interests": ["AI inference"]}, None) == [ + {"id": "alice", "name": "Alice Moreno"} + ] + assert calls == [("emma", schedule.FRIENDS)] + + +def test_top_matches_is_empty_when_ranking_fails(monkeypatch): + from app.routers import people, schedule + + def failing(*_args, **_kwargs): + raise people.SearchFailed("people index is rebuilding") + + monkeypatch.setattr(schedule, "rank_people", failing) + assert schedule._top_matches("emma", {"interests": ["AI inference"]}, None) == [] diff --git a/backend/tests/test_search.py b/backend/tests/test_search.py index 2e0b296..fabecee 100644 --- a/backend/tests/test_search.py +++ b/backend/tests/test_search.py @@ -125,7 +125,7 @@ def test_embed_is_skipped_without_key(no_key): def test_embedding_text_is_trimmed(): text = load.session_text({"title": "T", "track": "AI", "projects": ["vLLM", "KServe"], "description": "x" * 5000}) - assert text.startswith("T\nAI\nvLLM, KServe\n") and len(text) == load.EMBED_CHARS + assert text.startswith("T\nAI\nvLLM, KServe\n") and len(text) == embeddings.EMBED_CHARS def test_embedding_cost(): diff --git a/docs/architecture.md b/docs/architecture.md index 708f531..43a6137 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -73,16 +73,57 @@ flowchart LR | Current or past company (any overlap) | 3 | "Works at ..." / "Worked at ..." | | Community | 2 each | "Both in ..." | | City | 2 | "Also in ..." | -| Interest | 1.5 each | "Both into ..." | -| User's interests as text in a speaker's tracks or bio | BM25 x 0.5 | "Speaks on ..." / "Mentions ..." | +| Country | 1 | "Also from ..." (only when the city differs) | +| Topic: interest, keyword or project, chosen track | 1.5 each | "Both into ..." (attendees) / "Speaks on ..." (speakers) | +| User's topics as text in someone's interests or bio | BM25 x 0.5, lexical list only | "Speaks on ..." / "Mentions ..." | -- **One query.** A `bool` of `constant_score` clauses, one per shared value, so each overlap adds a fixed, explainable amount; `minimum_should_match: 0` keeps people with nothing in common at the bottom rather than hiding them. A keyword `q` becomes a `multi_match` must clause on name, title, company, interests and bio. `kind` (Attendees or Speakers tab) is a query filter. -- **Vectors when present.** If the user's profile has an `embedding`, the query is wrapped in `script_score` adding `4 x max(0, cosine)`. A weighted sum, not RRF: the boosts stay in charge (one shared school outweighs any embedding), scores stay readable, and aggregations and `post_filter` keep working on one plain query. If vector scoring fails (field missing mid-rebuild) the request logs a warning, records it on the span and ranks lexically; `semantic` in the response says which happened. +- **Lexical list.** A `bool` of `constant_score` clauses, one per shared value, plus BM25 of the user's topics on `interests_text` and `bio`; `minimum_should_match: 0` keeps people with nothing in common at the bottom rather than hiding them. A keyword `q` becomes a `multi_match` must clause on name, title, company, interests and bio. `kind` (Attendees or Speakers tab) is a query filter. The user and private profiles are excluded. +- **Hybrid ranking.** With a profile vector, the lexical list and a kNN list are fused with RRF, then the boosts are added on top. See "Profile drives matching" below; `mode` in the response says which path ran (`hybrid`, `hybrid-client`, `bm25`) and `semantic` whether the vector took part. - **Reasons in Python.** `why` is computed from the same overlap the query boosts, at most three, schools first, so every reason is true and clickable. Each reason names its field; clicking it applies that exact filter (`school`, `company`, `community`, `city`, `interest`) or, for a bio mention, a keyword search. - **Group chips.** `filters` aggregations restricted to the user's own schools, companies, communities, city and country count the other people sharing each. Background filters go in `post_filter`, so chip counts stay stable while chips are toggled. - **Telemetry.** Requests count on `confox.match.requests` (attributes `kind`, `has_query`, `filtered`); the request span carries `confox.match.semantic`. - Attendees are generated samples and every card says "Sample"; speakers are public schedule profiles. +## Profile drives matching + +The signed-in user's profile document in `confox-people` is the input to People, For you and My brief. `GET /api/profile/{user_id}` returns the editable fields; `PUT /api/profile/{user_id}` saves them; `GET /api/profile/options` returns suggestions for the editor's chips (top attendee interests, CNCF projects and tracks from the sessions, schools with University of Utah first, current and past companies merged, communities, cities, countries), all from one `msearch` of `terms` aggregations. Code: `backend/app/routers/profile.py`; editor: `src/components/ProfileDrawer.tsx` and `src/components/profile/`. + +```mermaid +flowchart LR + F[Profile editor] -->|PUT, validated| T[interests_text
interests + projects + tracks] + T --> X[person_text
name, title, company, interests_text, bio] + X -->|only if the text changed| V[embedding
text-embedding-3-small] + V --> W[(confox-people
write with refresh)] + W --> L[BM25 list: boosts per shared value
+ topics on interests_text, bio] + W --> K[kNN list on the profile vector] + L --> R[RRF, k 60, window 100
native rrf retriever or in the API] + K --> R + R --> B[score = boosts + 4 x fused rank] + B --> Y[why reasons from the same overlap] +``` + +| Step | What happens | +|---|---| +| Validate | Pydantic, unknown fields refused: name (1 to 80), title, company, city, country (80), bio (500), interests (12 phrases of 40), keywords or projects (20), tracks (12, each must be a schedule track), schools (8), past companies and communities (10), looking for (200), links (3 full http or https addresses), visibility `public` or `private`. Lists are trimmed and de-duplicated ignoring case. Errors come back as FastAPI 422 details per field | +| Text | `interests_text` is rebuilt from interests, then projects, then tracks. The embedding text is `embeddings.person_text`, the same recipe the loader uses, so an edited profile and a loaded one are comparable | +| Embedding | Recomputed only when that text changed (a new school or link costs no model call). No `OPENAI_API_KEY`: saved without a vector (`embedding: "skipped"` and a `note` in the response), and matching runs lexically. An embedding error saves without a vector too (`failed`, logged and on the span) rather than losing the edit | +| Write | The whole document is indexed with `refresh=wait_for`, so the next request sees it. Fields the editor does not own (`kind`, `sample`, `picture`, `session_ids`) are kept. Each save also puts the profile-only fields (`projects`, `tracks`, `looking_for`, `links`, `visibility`, `updated_at`) into the mapping; additive, a no-op once present | +| Response | `{profile, changed, embedding, note}`; `changed` lists the editable fields whose value differs | +| Telemetry | Span `profile.save` (`confox.profile.user`, `confox.profile.changed`, `confox.profile.embedding`); counter `confox.profile.updates` (attributes `embedding`, `changed`) | + +**Ranking.** `/api/people/match`, `/api/schedule/day` and `/api/brief` read the profile with a realtime `get` on every request; nothing is cached, so an edit changes the very next ranking. + +1. **Two lists.** Lexical: the boost table in "People and Match" (shared schools, companies, communities, city, country, topics) plus BM25 of the topics on `interests_text` and `bio`. Semantic: kNN on the profile `embedding` (`k` 100, 200 candidates) under the same filters (kind, keyword, chip filters, the user and private profiles excluded). +2. **RRF.** One request with the native `rrf` retriever (rank constant 60, window 100), with the group aggregations and the chip `post_filter` on the same request. On a basic licence the rejection is recorded (`confox.match.rrf_fallback` event), remembered for the process, and both lists come from one `msearch` and are fused in Python with the same `rrf_fuse` as session search. Any other vector failure, or no vector, ranks by the lexical list alone (`bm25`). +3. **Boosts.** The fused score is scaled to 0..1 (first in every list is 1) and multiplied by 4, then the shared-value boosts are added in Python (`affinity`). One shared school (6) outweighs any amount of semantic closeness; within equal overlap, BM25 and the embedding decide. +4. **Why.** `why` reads the same overlap, at most three, schools first: "BUET alumni", "Both into eBPF", "Works at ...", "Also in ...", "Speaks on ...", "Mentions ...". Every reason is a clickable filter. + +**For you** (Schedule and My brief) uses the same profile: interest and project phrases in the title, projects, track or description; a chosen track matching the session track ("in your track Security", fit 0.65); and the day's 12 nearest sessions to the profile vector. + +**Refreshing the pages.** The app shell keeps the profile and a `version` in `ProfileContext` (`src/profile.ts`). A save sets the returned profile, bumps `version`, closes the editor and shows "Profile saved · matches updated". People, Schedule, Now, the Dashboard hero row and My brief put `version` in their fetch dependencies, so they refetch without a page reload. + +**Sample data.** Every 13th generated attendee also lists BUET as a second school (six people), assigned without the random generator so every other generated value is unchanged; it appears after the next `--only people` load. + ## Telemetry (pull request 1) | Signal | Source | Where it goes | @@ -279,7 +320,7 @@ The People page has three tabs, kept in the address as `?tab=connections|groups` ## My brief (pull request 10) -One calm page for the signed-in attendee's day. `GET /api/brief?user_id=emma` (day of `clock.now()`) lives in `backend/app/routers/brief.py`; the page is `src/pages/Brief.tsx` with `src/components/brief/` and `src/styles/brief.css`. Nothing new is stored: the endpoint reads `confox-sessions`, `confox-people` and `confox-agenda` and reuses the other features' helpers (schedule `_day_sessions`, `annotate`, `_knn`; Match `build_match_query`, `why`; `next_food()`). +One calm page for the signed-in attendee's day. `GET /api/brief?user_id=emma` (day of `clock.now()`) lives in `backend/app/routers/brief.py`; the page is `src/pages/Brief.tsx` with `src/components/brief/` and `src/styles/brief.css`. Nothing new is stored: the endpoint reads `confox-sessions`, `confox-people` and `confox-agenda` and reuses the other features' helpers (schedule `_day_sessions`, `annotate`, `_knn`; Match `rank_people`, `why`; `next_food()`). | Part | Rule | |---|---| @@ -287,7 +328,7 @@ One calm page for the signed-in attendee's day. `GET /api/brief?user_id=emma` (d | `is_next` | The first item not yet ended; a co-located day already under way is skipped while something else is still to come, so the marker moves to the coffee, then lunch | | `gaps` | Free windows of 60+ minutes between 08:00 and 19:00, from now on; all-day co-located events do not block (they would hide every gap) | | `requests` | Pending meetings today split into `incoming` (no direction counts as incoming) and `outgoing`; a request without a room takes the room of the food break at the same time | -| `people` | The Match ranking (same query, vector when present, lexical fallback logged on the span), minus anyone the user already has a meeting, request or declined request with today; up to 3, each with the first `why` reason and `free_at`: the first food break after now that does not overlap the user's confirmed plans | +| `people` | The Match ranking (`rank_people`, the same pipeline as People; the mode is on the span as `confox.brief.people_mode`), minus anyone the user already has a meeting, request or declined request with today; up to 3, each with the first `why` reason and `free_at`: the first food break after now that does not overlap the user's confirmed plans | | `suggested` | Up to 3 for-you sessions (interest phrase or kNN) not on the agenda, not started, not clashing; other co-located days and breaks left out | | `summary` | Plain sentences from the data, no LLM: the anchor event, confirmed meetings, waiting requests | diff --git a/frontend/src/api.ts b/frontend/src/api.ts index 6e5932d..d0e2eec 100644 --- a/frontend/src/api.ts +++ b/frontend/src/api.ts @@ -6,9 +6,12 @@ export const DEMO_USER = 'emma' export class ApiError extends Error { status: number - constructor(status: number, message: string) { + /** The parsed error body, when the API sent JSON (FastAPI puts validation errors in `detail`). */ + detail?: unknown + constructor(status: number, message: string, detail?: unknown) { super(message) this.status = status + this.detail = detail } } @@ -43,3 +46,14 @@ export async function deleteJSON(path: string, params?: Params, init?: Reques if (!r.ok) throw new ApiError(r.status, `${r.status} ${r.statusText}`) return (await r.json()) as T } + +export async function putJSON(path: string, body: unknown, init?: RequestInit): Promise { + const headers = new Headers(init?.headers) + headers.set('Content-Type', 'application/json') + const r = await fetch(apiUrl(path), { ...init, method: 'PUT', headers, body: JSON.stringify(body) }) + if (!r.ok) { + const detail = await r.json().then((b: { detail?: unknown }) => b.detail).catch(() => undefined) + throw new ApiError(r.status, `${r.status} ${r.statusText}`, detail) + } + return (await r.json()) as T +} diff --git a/frontend/src/components/ProfileDrawer.tsx b/frontend/src/components/ProfileDrawer.tsx index 1ade3c2..dd59313 100644 --- a/frontend/src/components/ProfileDrawer.tsx +++ b/frontend/src/components/ProfileDrawer.tsx @@ -1,11 +1,20 @@ import { useEffect, useRef } from 'react' -import { GraduationCap, X } from 'lucide-react' -import { DEMO_PROFILE } from '../profile.ts' - -type Props = { open: boolean; onClose: () => void } +import { RefreshCw, X } from 'lucide-react' +import type { Profile, SaveResponse } from '../profile.ts' +import ProfileForm from './profile/ProfileForm.tsx' +import '../styles/profile.css' + +type Props = { + open: boolean + profile: Profile | null + failed: boolean + onRetry: () => void + onClose: () => void + onSaved: (res: SaveResponse) => void +} // A native modal dialog gives focus trapping, Escape to close and focus return for free. -export default function ProfileDrawer({ open, onClose }: Props) { +export default function ProfileDrawer({ open, profile, failed, onRetry, onClose, onSaved }: Props) { const ref = useRef(null) useEffect(() => { @@ -15,51 +24,38 @@ export default function ProfileDrawer({ open, onClose }: Props) { if (!open && dialog.open) dialog.close() }, [open]) + const close = () => ref.current?.close() + return ( { // The body fills the dialog, so a click on the dialog itself is a backdrop click. - if (e.target === e.currentTarget) ref.current?.close() + if (e.target === e.currentTarget) close() }} >
-

Profile

-
-
- -
-

{DEMO_PROFILE.name}

-

{DEMO_PROFILE.role}

+ {/* Mounted only while open, so every opening starts from the saved profile. */} + {open && profile && } + {open && !profile && !failed &&

Loading your profile…

} + {open && !profile && failed && ( +
+

Could not load your profile. Is the API running?

+
-
- -

-

- -
-

Interests

-
    - {DEMO_PROFILE.interests.map((interest) => ( -
  • {interest}
  • - ))} -
-
- -
- Sample profile -

Generated demo data. The demo user is signed in by default.

-
+ )}
) diff --git a/frontend/src/components/Shell.tsx b/frontend/src/components/Shell.tsx index 5984118..57671b2 100644 --- a/frontend/src/components/Shell.tsx +++ b/frontend/src/components/Shell.tsx @@ -1,26 +1,70 @@ -import { useState } from 'react' +import { useCallback, useEffect, useMemo, useState } from 'react' import { Outlet } from 'react-router' +import { DEMO_USER, getJSON } from '../api.ts' +import { ProfileContext, type Profile, type SaveResponse } from '../profile.ts' import ProfileDrawer from './ProfileDrawer.tsx' -import type { ShellContext } from './shellContext.ts' import Rail from './Rail.tsx' import SessionDrawerProvider from './session/SessionDrawerProvider.tsx' +import type { ShellContext } from './shellContext.ts' +import Toast from './Toast.tsx' import TopBar from './TopBar.tsx' export default function Shell() { const [profileOpen, setProfileOpen] = useState(false) - const context: ShellContext = { openProfile: () => setProfileOpen(true) } + const [profile, setProfile] = useState(null) + const [profileFailed, setProfileFailed] = useState(false) + const [version, setVersion] = useState(0) + const [toast, setToast] = useState<{ id: number; text: string } | null>(null) + + const loadProfile = useCallback(() => { + getJSON(`profile/${DEMO_USER}`) + .then((p) => { + setProfile(p) + setProfileFailed(false) + }) + .catch((err: unknown) => { + console.warn('profile failed to load', err) + setProfileFailed(true) + }) + }, []) + + useEffect(loadProfile, [loadProfile]) + + const openEditor = useCallback(() => setProfileOpen(true), []) + const ctx = useMemo(() => ({ profile, version, openEditor }), [profile, version, openEditor]) + // Pages reached through the router (Schedule's "edit" link) open the same editor. + const outlet: ShellContext = { openProfile: openEditor } + + const onSaved = (res: SaveResponse) => { + setProfile(res.profile) + // Every page that ranks or filters by the profile refetches when this changes. + setVersion((v) => v + 1) + const text = res.changed.length ? 'Profile saved · matches updated' : 'Profile saved · nothing changed' + setToast({ id: Date.now(), text: res.note ? `${text}. ${res.note}` : text }) + setProfileOpen(false) + } return ( -
- Skip to content - setProfileOpen(true)} /> - - -
- -
-
- setProfileOpen(false)} /> -
+ +
+ Skip to content + + + +
+ +
+
+ setProfileOpen(false)} + onSaved={onSaved} + /> + {toast && setToast(null)} />} +
+
) } diff --git a/frontend/src/components/Toast.tsx b/frontend/src/components/Toast.tsx new file mode 100644 index 0000000..91b6039 --- /dev/null +++ b/frontend/src/components/Toast.tsx @@ -0,0 +1,22 @@ +import { useEffect } from 'react' +import { CircleCheck, X } from 'lucide-react' + +type Props = { text: string; onDone: () => void; ms?: number } + +/** A short confirmation at the bottom of the screen. The live region announces it; it leaves on its own. */ +export default function Toast({ text, onDone, ms = 4500 }: Props) { + useEffect(() => { + const t = setTimeout(onDone, ms) + return () => clearTimeout(t) + }, [onDone, ms]) + + return ( +
+
+ ) +} diff --git a/frontend/src/components/TopBar.tsx b/frontend/src/components/TopBar.tsx index 823b4d4..5d87345 100644 --- a/frontend/src/components/TopBar.tsx +++ b/frontend/src/components/TopBar.tsx @@ -1,10 +1,12 @@ import { Link } from 'react-router' -import { DEMO_PROFILE } from '../profile.ts' +import { FALLBACK_NAME, firstName, initials, useProfile } from '../profile.ts' import FoxMark from './FoxMark.tsx' type Props = { profileOpen: boolean; onOpenProfile: () => void } export default function TopBar({ profileOpen, onOpenProfile }: Props) { + const { profile } = useProfile() + const name = profile?.name ?? FALLBACK_NAME return (
@@ -18,10 +20,10 @@ export default function TopBar({ profileOpen, onOpenProfile }: Props) { onClick={onOpenProfile} aria-haspopup="dialog" aria-expanded={profileOpen} - aria-label={`Open profile for ${DEMO_PROFILE.name}`} + aria-label={`Edit profile for ${name}`} > - - {DEMO_PROFILE.name} + + {firstName(name)}
) diff --git a/frontend/src/components/dashboard/DashTiles.tsx b/frontend/src/components/dashboard/DashTiles.tsx index a14e242..97d36d2 100644 --- a/frontend/src/components/dashboard/DashTiles.tsx +++ b/frontend/src/components/dashboard/DashTiles.tsx @@ -5,6 +5,7 @@ import { DEMO_USER, getJSON } from '../../api.ts' import { roomLabel } from '../schedule/time.ts' import type { Session } from '../../types.ts' import { type DashboardData, dayLabel, fmt, hhmm, hours, plural } from './types.ts' +import { useProfileVersion } from '../../profile.ts' type NowSummary = { on_now_total: number @@ -44,12 +45,13 @@ export default function DashTiles({ data }: { data: DashboardData }) { const [failed, setFailed] = useState(false) const agendaVersion = useAgendaVersion() + const profileVersion = useProfileVersion() useEffect(() => { getJSON('now', { user_id: DEMO_USER }) .then(setNow) .catch(() => setFailed(true)) - }, [agendaVersion]) // refetch when the session drawer changes the agenda + }, [agendaVersion, profileVersion]) // refetch after agenda or profile changes const people = data.people const peopleTile = ( diff --git a/frontend/src/components/people/fields.ts b/frontend/src/components/people/fields.ts index 8b47dc8..84d877e 100644 --- a/frontend/src/components/people/fields.ts +++ b/frontend/src/components/people/fields.ts @@ -35,6 +35,7 @@ export const WHY_FILTER: Record = { company: 'company', communities: 'community', city: 'city', + country: 'country', interests: 'interest', q: 'q', } diff --git a/frontend/src/components/people/types.ts b/frontend/src/components/people/types.ts index 17b8312..22a0990 100644 --- a/frontend/src/components/people/types.ts +++ b/frontend/src/components/people/types.ts @@ -6,7 +6,7 @@ export type FilterKey = 'school' | 'company' | 'community' | 'interest' | 'city' export type Filters = Partial> /** `field` names the profile field the reason comes from; `q` means "named in the bio", a keyword search. */ -export type WhyField = 'schools' | 'company' | 'communities' | 'city' | 'interests' | 'q' +export type WhyField = 'schools' | 'company' | 'communities' | 'city' | 'country' | 'interests' | 'q' export type Why = { label: string; field: WhyField; value: string } export type Person = { @@ -35,4 +35,6 @@ export type MatchResponse = { results: MatchResult[] groups: Record semantic: boolean + /** How the ranking ran: native RRF, RRF in the API, or keywords only. */ + mode?: 'hybrid' | 'hybrid-client' | 'bm25' } diff --git a/frontend/src/components/profile/ChipInput.tsx b/frontend/src/components/profile/ChipInput.tsx new file mode 100644 index 0000000..b386485 --- /dev/null +++ b/frontend/src/components/profile/ChipInput.tsx @@ -0,0 +1,147 @@ +import { useId, useRef, useState, type KeyboardEvent } from 'react' +import { Plus, X } from 'lucide-react' + +type Props = { + label: string + hint?: string + values: string[] + onChange: (next: string[]) => void + suggestions?: string[] + max: number + maxLength: number + placeholder?: string + error?: string +} + +const SHOWN_SUGGESTIONS = 6 + +/** + * A list of short phrases as removable chips. Type and press Enter (or comma) to add, Backspace on an empty field + * removes the last one. Suggestions come from the browser's native autocomplete list and, for touch, as a few + * one-tap chips filtered by what is typed. + */ +export default function ChipInput({ label, hint, values, onChange, suggestions = [], max, maxLength, placeholder, error }: Props) { + const id = useId() + const inputRef = useRef(null) + const [text, setText] = useState('') + const [note, setNote] = useState('') + const full = values.length >= max + const lower = new Set(values.map((v) => v.toLowerCase())) + const typed = text.trim().toLowerCase() + const open = suggestions.filter((s) => !lower.has(s.toLowerCase())) + const shown = (typed ? open.filter((s) => s.toLowerCase().includes(typed)) : open).slice(0, SHOWN_SUGGESTIONS) + + const add = (raw: string) => { + const value = raw.trim().replace(/,+$/, '').trim() + if (!value) return + if (lower.has(value.toLowerCase())) { + setNote(`${value} is already in the list`) + setText('') + return + } + if (full) { + setNote(`At most ${max}. Remove one first.`) + return + } + onChange([...values, value.slice(0, maxLength)]) + setText('') + setNote('') + } + + const remove = (value: string) => { + onChange(values.filter((v) => v !== value)) + setNote(`Removed ${value}`) + inputRef.current?.focus() + } + + const onKey = (e: KeyboardEvent) => { + if (e.key === 'Enter' || e.key === ',') { + e.preventDefault() + add(text) + } else if (e.key === 'Backspace' && text === '' && values.length > 0) { + remove(values[values.length - 1]) + } + } + + const describedBy = [`${id}-hint`, error ? `${id}-error` : ''].filter(Boolean).join(' ') + + return ( +
+ + {values.length > 0 && ( +
    + {values.map((v) => ( +
  • + {v} + +
  • + ))} +
+ )} +
+ { + const v = e.target.value + // A comma typed or pasted at the end adds the phrase, like Enter. + if (v.endsWith(',')) add(v) + else setText(v) + }} + onKeyDown={onKey} + /> + + {suggestions.length > 0 && ( + + {open.map((s) => ( + + )} +
+

+ {hint ? `${hint} ` : ''} + {values.length} of {max}. +

+ {!full && shown.length > 0 && ( +
+ Suggestions +
    + {shown.map((s) => ( +
  • + +
  • + ))} +
+
+ )} +

+ {note} +

+ {error && ( +

+ {error} +

+ )} +
+ ) +} diff --git a/frontend/src/components/profile/ProfileForm.tsx b/frontend/src/components/profile/ProfileForm.tsx new file mode 100644 index 0000000..72ce433 --- /dev/null +++ b/frontend/src/components/profile/ProfileForm.tsx @@ -0,0 +1,408 @@ +import { useEffect, useId, useRef, useState, type FormEvent, type ReactNode } from 'react' +import { Briefcase, Eye, GraduationCap, Link2, LoaderCircle, Save, Sparkles, Target, UserRound } from 'lucide-react' +import { ApiError, DEMO_USER, getJSON, putJSON } from '../../api.ts' +import { + LIMITS, + initials, + type Profile, + type ProfileFields, + type ProfileOptions, + type SaveResponse, +} from '../../profile.ts' +import ChipInput from './ChipInput.tsx' + +type Props = { profile: Profile; onSaved: (res: SaveResponse) => void; onCancel: () => void } +type Errors = Partial> + +const FIELDS: (keyof ProfileFields)[] = [ + 'name', 'title', 'company', 'city', 'country', 'bio', 'interests', 'projects', 'tracks', + 'schools', 'past_companies', 'communities', 'looking_for', 'links', 'visibility', +] + +function pick(p: ProfileFields): ProfileFields { + return Object.fromEntries(FIELDS.map((f) => [f, p[f]])) as ProfileFields +} + +/** What would be sent: trimmed text, empty link rows dropped. Also what dirty-checking compares. */ +function normalise(d: ProfileFields): ProfileFields { + const out = { ...d } + for (const f of ['name', 'title', 'company', 'city', 'country', 'bio', 'looking_for'] as const) out[f] = d[f].trim() + out.links = d.links.map((l) => l.trim()).filter(Boolean) + return out +} + +function isUrl(value: string): boolean { + try { + const u = new URL(value) + return (u.protocol === 'http:' || u.protocol === 'https:') && u.hostname.includes('.') + } catch { + return false + } +} + +function validate(d: ProfileFields): Errors { + const e: Errors = {} + if (!d.name) e.name = 'Enter your name.' + if (d.bio.length > LIMITS.bio) e.bio = `Keep it to ${LIMITS.bio} characters.` + if (d.looking_for.length > LIMITS.lookingFor) e.looking_for = `Keep it to ${LIMITS.lookingFor} characters.` + const bad = d.links.find((l) => !isUrl(l)) + if (bad) e.links = `"${bad}" is not a full web address. Start with https://` + return e +} + +/** FastAPI validation errors ({loc: ['body', field, ...], msg}) as one message per field. */ +function serverErrors(detail: unknown): Errors { + const e: Errors = {} + if (!Array.isArray(detail)) return e + for (const item of detail as { loc?: unknown[]; msg?: string }[]) { + const field = item.loc?.[1] + const key = typeof field === 'string' && (FIELDS as string[]).includes(field) ? (field as keyof ProfileFields) : 'form' + e[key] ??= (item.msg ?? 'Not valid').replace(/^Value error, /, '') + } + return e +} + +const EMPTY_OPTIONS: ProfileOptions = { + interests: [], projects: [], tracks: [], schools: [], companies: [], communities: [], cities: [], countries: [], +} + +export default function ProfileForm({ profile, onSaved, onCancel }: Props) { + const id = useId() + const formRef = useRef(null) + const saved = pick(profile) + const [draft, setDraft] = useState(() => ({ ...saved, links: [...saved.links, '', '', ''].slice(0, LIMITS.links) })) + const [options, setOptions] = useState(EMPTY_OPTIONS) + const [errors, setErrors] = useState({}) + const [saving, setSaving] = useState(false) + const dirty = JSON.stringify(normalise(draft)) !== JSON.stringify(normalise(saved)) + const errorCount = Object.keys(errors).length + + useEffect(() => { + const ctrl = new AbortController() + getJSON('profile/options', undefined, { signal: ctrl.signal }) + .then(setOptions) + .catch((err: unknown) => !ctrl.signal.aborted && console.warn('profile suggestions failed', err)) + return () => ctrl.abort() + }, []) + + useEffect(() => { + // After a failed submit, move focus to the first field that needs attention. + if (!errorCount) return + const first = formRef.current?.querySelector('[aria-invalid="true"]') + first?.focus() + }, [errorCount, errors]) + + const set = (key: K, value: ProfileFields[K]) => { + setDraft((d) => ({ ...d, [key]: value })) + if (errors[key]) + setErrors((prev) => { + const next = { ...prev } + delete next[key] + return next + }) + } + + const submit = async (e: FormEvent) => { + e.preventDefault() + const body = normalise(draft) + const found = validate(body) + setErrors(found) + if (Object.keys(found).length) return + setSaving(true) + try { + onSaved(await putJSON(`profile/${DEMO_USER}`, body)) + } catch (err) { + const fromServer = err instanceof ApiError && err.status === 422 ? serverErrors(err.detail) : {} + setErrors( + Object.keys(fromServer).length + ? fromServer + : { form: 'Could not save your profile. Check that the API is running and try again.' }, + ) + setSaving(false) + } + } + + const text = (key: 'name' | 'title' | 'company' | 'city' | 'country', label: string, opts: { list?: string[]; required?: boolean; autoComplete?: string } = {}) => ( + + {(props) => ( + <> + set(key, e.target.value)} + /> + {opts.list && opts.list.length > 0 && ( + + {opts.list.map((o) => + )} + + )} + + ) + + const trackSet = new Set(draft.tracks) + const tracksFull = draft.tracks.length >= LIMITS.interests + + return ( +
+
+ +
+

{draft.name || profile.name}

+

{[draft.title, draft.company].filter(Boolean).join(' · ')}

+
+
+
+ Sample profile +

Generated demo data. The demo user is signed in by default.

+
+

+ People, For you and My brief rank against this profile. Saving updates them right away. +

+ + {errors.form && ( +

+ {errors.form} +

+ )} + {errorCount > 0 && !errors.form && ( +

+ {errorCount === 1 ? 'One field needs attention.' : `${errorCount} fields need attention.`} +

+ )} + +