Sangeetha-Grantha

Metadata Value
Status Completed
Version 1.0.0
Last Updated 2026-11-01
Author Sangeetha Grantha Team

Track: Rasika Search over Cycles and Kshetras

ID: TRACK-152 Status: Complete: Phases 0 to C merged; follow-ups listed in the Progress Log Owner: Seshadri Created: 2026-10-16 Updated: 2026-11-01

Goal

Let a Rasika search such as “sixth enclosure” or “fire lingam” return a cycle or kshetra card as well as kritis, using the CYCLE_OVERVIEW and KSHETRA_OVERVIEW documents that are already embedded.

Context

Intent

Status: Accepted Accepted by: Seshadri (2026-10-24)

Problem

The best discriminating content in the index is the cycle and kshetra overview text, and it cannot reach a user. A query about an enclosure or a lingam returns kritis whose text happens to match, not the cycle or the shrine the user is asking about.

Proposed outcome

  1. Macro hits in the live API. Hybrid and semantic search return typed hits: KRITHI, COLLECTION (slug) and KSHETRA (temple id). The join becomes a left join, or the macro documents are unioned, with published-only filtering for each anchor kind.
  2. Backward-compatible contract. Existing clients keep working: kriti hits keep their shape; new hit kinds are additive and only appear for clients that opt in (for example a request flag or the V2 path), so V1 and older apps never receive a hit with no krithiId.
  3. Mobile. Search results render a collection or kshetra card that opens its detail screen.
  4. Proof. The existing macro probes run through the live API, not only the evaluation script.

Constraints

Open questions

  1. Opt-in mechanism: request field, separate endpoint, or V2-only?
  2. How many macro hits per page, and are they interleaved or shown in their own group?
  3. Should the lexical-only fallback (no embedding profile) include macro documents?
  4. What acceptance thresholds on the existing macro probes?

Decisions on open questions (2026-10-24)

  1. Opt-in: V2 path only. V1 and older apps never receive a hit without krithiId.
  2. Macro hits appear as their own group above kriti results, capped at 3 per response, and never displace an exact kriti title match.
  3. The lexical-only fallback includes macro documents (lexical match on overview text).
  4. Acceptance: live-API macro probe results equal the recorded evaluate_retrieval.py outcomes, with no regression on kriti MRR 0.78 / Recall@5 87.1%.

Completion evidence (fixed in Plan)

Repository and route tests including a V1-decoder compatibility test, retrieval probes through the API, presenter tests, simulator walk-through, make test, make test-integration, make check-docs.

Spec

Status: Accepted Accepted by: Seshadri (chat instruction) Accepted at: 2026-10-25

Written from the accepted Intent and its 2026-10-24 decisions, after reading KrithiSearchRepository, HybridSearchService, SemanticSearchRoutes, SearchDtos.kt, KtorCatalogueApi, SearchPresenter, CatalogueRepository (collections, overviewTagIds, cycleOverview), evaluate_retrieval.py with evals/retrieval_benchmarks.json, and TRACK-151’s Spec/Plan plus its Phase 1 code on claude/track-151-kshetra-contract-df8da3 (read with git show, not checked out): TempleEligibility.kt, CatalogueTempleDtos.kt, and the RasikaCatalogue* / ALL_PUBLISHED renames. Nothing is implemented, nothing was measured live (no database was started), and the carnatic-musicologist review was not run: this track adds read-only retrieval over existing reviewed documents and changes no seed, import, raga or tala content.

Names. This Spec uses the TRACK-151 Phase 0 names (RasikaCatalogueContract, RasikaCatalogueRoutes, CatalogueVisibility.ALL_PUBLISHED). The /v2/... URL paths are unchanged by that rename.

Current state (facts the design rests on)

Requirements

A. Hit kinds and opt-in

  1. A V2 search response carries hits of three kinds: KRITHI, COLLECTION, KSHETRA. KRITHI hits are exactly today’s SemanticSearchResultItem, same fields, same ranking, same krithiId non-null.
  2. Macro hits (COLLECTION, KSHETRA) exist only on new V2 endpoints (Intent decision 1):
    • POST /v2/catalogue/search/hybrid
    • POST /v2/catalogue/search/semantic Both take the unchanged SemanticSearchRequest body, are anonymous, and are published-only (no admin branch).
  3. /v1/search/hybrid and /v1/search/semantic are not changed: same paths, same DTO, no macro hit, no new field, and the same response for the same input. V1 and older apps never receive a hit without krithiId.
  4. Macro hits are returned in their own group, separate from kriti hits (Intent decision 2). A client cannot mistake a macro hit for a kriti because the two groups are different arrays with different element types.

B. Response contract (additive, V2-only types)

  1. New shared-domain DTOs in modules/shared/domain/.../model/catalogue/CatalogueSearchDtos.kt:
    • CatalogueSearchHitKindDto { KRITHI, COLLECTION, KSHETRA } (serialised as the names).
    • CatalogueMacroHitDto: kind (COLLECTION or KSHETRA only), title, subtitle? (composer name for a collection; place or region for a kshetra), snippet (bounded excerpt of the matched overview, see 6), collectionSlug? (set only for COLLECTION), templeId? (set only for KSHETRA), memberCount? (collections), publishedKrithiCount? (kshetras), recordedGap (kshetras, default false), similarityScore, lexicalScore?, rrfScore?.
    • CatalogueSearchResponseDto: query, totalMatches (kriti hits + macro hits), macroHits: List<CatalogueMacroHitDto> (default empty, at most 3), items: List<SemanticSearchResultItem>, exactTitleMatchId? (see 11).
  2. snippet is a prefix of the stored overview text cut at a sentence or word boundary, at most 240 characters, never generated at request time. The hit never carries the full overview; the detail screen does.
  3. The only nullable-anchor change is inside the new CatalogueMacroHitDto (collectionSlug?, templeId?, exactly one non-null, enforced by a constructor check and a test). SemanticSearchResultItem and SemanticSearchResponse are not modified, so the frozen V1 decoders cannot break. (Intent asked for a nullable/additive change; making krithiId nullable on the existing item was rejected as the riskier way to get the same result. See open question 1.)
  4. Serialisation follows the server’s encodeDefaults = true, explicitNulls = false. CatalogueV2Contract’s successor RasikaCatalogueContract gains SEARCH_HYBRID_PATH and SEARCH_SEMANTIC_PATH.
  5. V1-decoder compatibility test (blocking). In :modules:shared:domain tests, a decoder configured like the frozen V1 client (strict SemanticSearchResponse, ignoreUnknownKeys = false) decodes the byte-for-byte recorded V1 fixture; and items of a V2 response decode as List<SemanticSearchResultItem> with that same strict decoder. In an API route test, /v1/search/hybrid for a macro-matching query returns zero items without krithiId and the same body as before the change (golden comparison on a seeded database).

C. Retrieval and ranking

  1. Separate macro query, kriti query untouched. The macro group comes from its own query over search_documents of kinds CYCLE_OVERVIEW and KSHETRA_OVERVIEW, run beside the existing kriti query with the same query vector (embedQueryCached; no extra embedding call). The kriti SQL, its JOIN krithis, RRF ranks and krithi_doc_rank partition are not edited, so kriti ordering and metrics cannot move. (A left join or union inside the kriti CTEs was rejected: macro rows would take ranks 1/(60+rank) and shift kriti scores. The Intent’s “left join or union” is satisfied by a union at the response level.)
  2. Exact title match is never displaced. exactTitleMatchId is set when the normalised query equals a published kriti’s title_normalized or incipit_normalized. Clients render that kriti first, then the macro group, then the remaining kritis. When it is null, the macro group renders above all kritis. The kriti items array order is never altered by macro hits.
  3. Cap of 3 macro hits per response, fixed constant MAX_MACRO_HITS = 3, not a request parameter. At most one hit per anchor (one per collection slug, one per temple): multi-chunk overviews (source_chunk_index) collapse to the best chunk.
  4. Relevance floor. The macro group may be empty, and is empty when nothing clears the floor; the cap is a ceiling, not a quota. The floor is a named constant per mode, calibrated in the Plan on the 53 probes (see acceptance 20). Without a floor, every query would return three cards from 105 documents.
  5. Scoring inside the macro group. Hybrid: RRF over a vector branch (cosine against the active profile’s embeddings) and a lexical branch (word_similarity(query, indexed_content) >= 0.3, ILIKE containment and all-token containment, the same lexical predicates as the kriti query), restricted to macro documents. Semantic: vector branch only. Ties break by similarity DESC, then anchor id.
  6. Lexical fallback includes macro documents (Intent decision 3). When no embedding profile is active, hybrid runs the lexical branch only, for both groups, and the macro group is built from the macro lexical branch. Semantic mode with no profile returns empty for both groups, as today. If the embedding service is unavailable, the existing failure behaviour is unchanged (no silent kriti-only success with a missing macro group).
  7. Scope filters. composerId and ragaId in the request are kriti-scoped: when either is set, macroHits is empty. (Mobile sends neither today.)
  8. Profile binding. The macro vector branch uses the same single profile id as the kriti branch (resolveCompatibleProfile), so the two groups cannot mix embedding spaces.

D. Published-only per anchor kind

  1. The kriti branch keeps d.is_published AND k.workflow_state = 'published'. For macro documents:
    • COLLECTION: document_kind = 'CYCLE_OVERVIEW', d.is_published, d.tag_id is in the set of tags that listCollections would return (at least one reviewed, published member). The set comes from one function in CatalogueRepository that listCollections, overviewTagIds consumers and search all call; search does not restate the rule. A tag whose overview is published but whose collection would 404 is never a hit.
    • KSHETRA: document_kind = 'KSHETRA_OVERVIEW', d.is_published, d.temple_id is in TempleEligibility.eligibleIds() (TRACK-151 Phase 1). A recorded-gap temple (Kanyakumari) is eligible and returns recordedGap = true. Search never restates the eligibility rule.
    • A macro document whose anchor columns are both null, or whose anchor kind does not match its document kind, is never returned.
  2. Every returned COLLECTION hit resolves in GET /v2/catalogue/collections/{slug} and every KSHETRA hit in GET /v2/catalogue/temples/{id} (a contract test asserts both for all macro documents in the seeded fixture; a 404 from a card is a defect).

E. Acceptance on the probes (Intent decision 4)

  1. Probes are run through the live API (the new V2 endpoints), not only the evaluation script. evaluate_retrieval.py gains a --via-api <base-url> option that posts each probe to /v2/catalogue/search/{hybrid|semantic}, scores macroHits for is_macro probes (rank within the group) and items for the rest, and prints the same metrics. Acceptance, all required:
    • Macro probes: for each of EVAL-31, SS-146-11, SS-146-12, TY-147-11, hit and reciprocal rank through the API equal the recorded evaluate_retrieval.py outcome for that probe (re-recorded in the Plan before any code, since per-probe results are not in the track files). A recorded hit at rank 4 or 5 cannot survive a cap of 3; if the baseline shows one, that is reported to Seshadri before coding, not hidden by changing the cap or the metric.
    • Kriti probes: the items array for every non-macro probe is identical (same ids, same order) to the V1 endpoint’s output, hence MRR 0.780 and Recall@5 87.1% on the EVAL-01..EVAL-31 battery are unchanged, and the 53-probe baseline re-recorded in the Plan is unchanged to the digit.
    • No false macro cards: the exact-title kriti probes (EVAL-01, 04, 09, 13, 17, 23) return an empty macro group, or the floor is raised until they do, without losing any macro probe above. Any other kriti probe that returns macro hits is listed with its hits for Seshadri’s review; it is not auto-counted as a failure (a query such as EVAL-24 about a fire lingam at Tiruvannamalai may legitimately surface its kshetra).
  2. make test and make test-integration pass; make test-frontend is unaffected (no admin-web change).

F. Mobile (after the backend contract lands)

  1. Search (Hybrid and Semantic modes) calls the V2 endpoints. Lexical mode, ragas and composers are unchanged (see out of scope). V1 paths stay for older apps.
  2. SearchPresenter holds macroHits and exactTitleMatchId beside discoveryItems; the screen shows a “Collections and kshetras” group with a card per hit. A COLLECTION card opens the TRACK-150 collection destination by slug; a KSHETRA card opens the TRACK-151 kshetra detail by id. A card shows kind label (text, not colour only), title, subtitle, snippet, and a recorded-gap marker for gap kshetras. Each card has a content description.
  3. A KSHETRA card is rendered only when the kshetra detail destination exists in the app build (TRACK-151 Phase 2). Until then the client drops KSHETRA hits rather than showing a card that goes nowhere. Unknown future kinds are dropped, never crash.
  4. Empty macro group: no header, no spacing. No new analytics beyond the existing optional session and interaction headers; opening a card reuses the destination’s own tracking.

G. Out of scope

  1. Paid or new embedding runs, changes to document text or source_chunk_index chunking, changes to kriti ranking, facets (TRACK-153), Lexical-mode (/v2/catalogue/krithis?query=) macro results, admin-web search, composer/raga macro hits, a V1 field or path change, any migration, any write, and AUDIT_LOG entries (read-only).

Design

Flagged concerns

Open questions carried forward

All four Intent questions are decided (2026-10-24). New, for acceptance:

  1. Keep SemanticSearchResultItem untouched and carry the nullable anchors in a new V2 CatalogueMacroHitDto (requirement 7), or also make krithiId nullable on the shared item as the Intent sketched? Recommendation: untouched; same safety, smaller blast radius.
  2. When an exact title match exists, place the macro group below that kriti (requirement 11), or suppress the macro group entirely?
  3. Is “one hit per anchor, floor-gated, cap a ceiling” acceptable, i.e. a query may legitimately show zero, one, two or three cards?
  4. May the Plan run evaluate_retrieval.py and the live API probes? They embed the probe queries (a few dozen tiny Gemini calls), not documents; Intent forbids only paid document embedding runs.

Plan

Status: Accepted Accepted by: Seshadri (chat instruction) Accepted at: 2026-10-25

Written from the Spec above; provisional until the Spec is accepted. Nothing is implemented. Phases land separately.

Files that change

Path Phase Change
tools/krithi-extract-enrich-worker/scripts/evaluate_retrieval.py A --via-api <base-url> option; scores macro probes on macroHits, others on items; no change to the DB-path scoring
modules/shared/domain/.../model/catalogue/CatalogueSearchDtos.kt (new) A CatalogueSearchHitKindDto, CatalogueMacroHitDto, CatalogueSearchResponseDto
modules/shared/domain/.../catalogue/RasikaCatalogueDtos.kt (renamed in TRACK-151 Phase 0) A SEARCH_HYBRID_PATH, SEARCH_SEMANTIC_PATH in RasikaCatalogueContract
modules/shared/domain/src/commonTest/.../CatalogueSearchDtosTest.kt (new) and a V1 fixture A Serialisation, anchor invariant, frozen-V1-decoder test
modules/backend/dal/.../repositories/CatalogueRepository.kt A Extract the single collections-eligibility function used by listCollections and search; behaviour of collections unchanged
modules/backend/dal/.../repositories/MacroSearchRepository.kt (new), SangitaDal.kt A, B Macro hybrid and semantic queries; COLLECTION in A, KSHETRA added in B
modules/backend/api/.../services/HybridSearchService.kt A Expose the embedded vector and bound profile for reuse; V1 behaviour unchanged
modules/backend/api/.../services/RasikaSearchService.kt (new) A Compose kriti items, macro group, exactTitleMatchId, cap, floor
modules/backend/api/.../routes/RasikaSearchRoutes.kt (new), plugins/Routing.kt, di/AppModule.kt A Two V2 POST routes, DI wiring
modules/backend/api/src/test/.../routes/RasikaSearchRoutesTest.kt (new), SemanticSearchRoutesTest.kt A, B V2 contract tests; V1 golden untouched-check
modules/backend/dal/src/test/.../MacroSearchRepositoryTest.kt (new) A, B Testcontainers, synthetic 768-dim vectors, per-anchor published-only cases
openapi/sangita-grantha.openapi.yaml, application_documentation/03-api/search.md A V2 paths, schemas, behaviour
modules/shared/mobile-data/.../network/CatalogueApi.kt, KtorCatalogueApi.kt, repository/CatalogueRepository.kt, fixture/CatalogueFixtures.kt, DiscoveryCatalogueClientTest.kt C V2 search call and fixtures
modules/shared/presentation/.../search/SearchPresenter.kt, SearchScreen (and card composable), RasikaCopy.kt, tests C Macro group state and cards, navigation to collection and kshetra detail
conductor/tracks.md any Status line only

No migration, no AUDIT_LOG write, no modules/frontend change, no change to V1 routes or DTOs.

Order of work

Phase 0: baseline and sign-off (no code)

  1. With make db + make migrate, the stack’s active embedding profile and GEMINI credentials available, run evaluate_retrieval.py --mode hybrid and --mode semantic. Record in the Progress Log: per-probe hit and reciprocal rank for all 53 probes, the 31-probe subtotal (expect MRR 0.780 / Recall@5 87.1%), the four macro probes’ ranks, and the number of macro documents by kind and how many are published and anchored to an eligible collection or temple.
  2. If any macro probe’s recorded rank is above 3, stop and report to Seshadri (Spec concern “Cap vs recorded rank”).
  3. Record EXPLAIN for the macro vector query over the eligible set.

Phase A: contract, backend, COLLECTION kind (separately landable; does not need TRACK-151)

  1. Shared DTOs, path constants, serialisation and V1-decoder tests (red first).
  2. Extract the collections-eligibility function; collections tests must still pass unchanged.
  3. MacroSearchRepository COLLECTION branch (hybrid, semantic, lexical-only), one-per-anchor collapse, cap, floor constants (initial placeholder), repository tests: reviewed-and-published collection returned; published overview on a tag with no reviewed member not returned; unpublished overview not returned; two chunks of one tag give one hit; no-profile lexical path returns the lexical macro hit; composer or raga filter empties the group.
  4. RasikaSearchService, routes, DI; route tests with the existing fake embedding client: V2 returns items identical to V1 for the same query, macroHits at most 3, exactTitleMatchId set for a typed full title, V1 body unchanged.
  5. Calibrate the floor from the Phase 0 scores, then run evaluate_retrieval.py --via-api for the three CYCLE_OVERVIEW probes and the 53-probe kriti parity check; record results.
  6. OpenAPI and search.md; make check-docs.

Phase B: KSHETRA kind (blocked on TRACK-151 Phase 1 merged to main)

  1. Merge or rebase onto main once claude/track-151-kshetra-contract-df8da3 lands (do not branch from it, do not copy TempleEligibility). Confirm TempleEligibility.eligibleIds() and the RasikaCatalogue* / ALL_PUBLISHED names exist.
  2. Add the KSHETRA branch (d.temple_id = ANY(eligible), recordedGap, publishedKrithiCount from TempleEligibility.snapshot()); repository tests for each rule: draft-only temple not returned, overview-only temple (including Kanyakumari, recordedGap = true) returned, child-only-eligible parent, unpublished overview not returned.
  3. Contract test that every macro hit resolves through its detail endpoint (Spec 19); run --via-api for EVAL-31 and the fire-lingam probe EVAL-24; update OpenAPI and docs.

Phase C: Rasika mobile (COLLECTION cards need only Phase A; KSHETRA cards also need TRACK-151 Phase 2)

  1. Mobile data layer on the V2 path and fixtures, presenter state and tests (empty group, exact-match ordering, kind filtering, unknown kind dropped, KSHETRA dropped when no destination), then card UI, copy and content descriptions.
  2. iOS simulator walk-through against the live backend (below).

Risks

Completion evidence (fixed)

Implementation Checklist

Progress Log