yams/formal/topology/Yams/Topology/SelectiveRouting.lean
Trevon a3d065dd8d
feat(search): make topology-assisted retrieval the default (#57)
* fix(release): repair package repo publish

Arch repo metadata and R2 uploads need to be reproducible from CI, with retry hardening for transient Cloudflare failures.

* fix(daemon): stop shutdown log storm

Init waiter must treat ShuttingDown as terminal so daemon shutdown tests do not flood Meson logs while the daemon is stopping.

* refactor(cli): delegate serve to MCP binary

Keep yams serve UX while removing MCP server linkage from yams-cli. The standalone MCP binary owns stdio serving and exits on stdin EOF.

* refactor(cli): move daemon path helpers

Keep CLI path resolution out of YamsDaemon so later link cuts can separate CLI and daemon internals. Full yams_daemon removal still needs a socket-only daemon-client split.

* refactor(daemon): split embedded client

* perf(search): add lean-guided benchmark gates

Add Lean topology/search models, ingestion ablation docs, and focused regression tests for topology and compression threshold behavior.

Extract search observability, keep benchmark-only ablation controls, and make retrieval quality benchmarks default to Simeon while preserving explicit ONNX opt-in.

* refactor(config): move daemon policies

* refactor(daemon): extract plugin runtime

* refactor(daemon): untangle service coordinators

Untangle CLI/MCP from daemon service coordinators and the daemon static lib.

- MetadataRepository uses a daemon-neutral tree-diff callback. The
  GraphComponent wrapper moves to src/daemon/components/metadata_graph_bridge.cpp,
  owned by the daemon library.
- WriteCoordinator moves to a dedicated build-only yams_write_coordinator
  static lib. Drop ResourceGovernor coupling inside the writer loop; batch
  sizing still respects config.maxBatchSize.
- AppContext gains enqueuePostIngest callback. ServiceManager wires it to
  its own enqueuePostIngest; app services no longer call ServiceManager
  directly.
- Embedding repair uses BulkIngestLease/BeginBulkIngestCallback instead of
  concrete VectorIndexCoordinator::BulkScope. Daemon dispatchers provide a
  lease factory backed by the real coordinator.
- CLI daemon_command uses config helpers instead of YamsDaemon::getXDGRuntimeDir.
- Remove explicit dependency('yams_daemon') from src/cli and tools/yams-mcp.
- Declare missing yams_extraction/yams_ingest deps on yams_app_services so
  app services link cleanly without daemon.

Validated:
  meson compile -C build/release -j4 yams-daemon yams-cli yams-mcp-server
  ninja -C build/release -t commands tools/yams-cli/yams-cli tools/yams-mcp/yams-mcp-server | grep -c libyams_daemon.a -> 0
  yams-cli --version, yams-mcp-server init, yams serve --help smoke tests

Size drop on macOS release: yams-cli 41M -> 32M, yams-mcp-server 37M -> 22M.

* fix(cli): keep stdin add local fallback

No embedded daemon now. When yams add - buffers stdin and daemon IPC is missing, store via local app services instead of failing socket_missing.

Validated:
  meson compile -C build/debug -j4 yams-cli catch2_cli_commands
  MESON_BUILD_ROOT=/Users/trevon/work/tools/yams/build/debug build/debug/tests/catch2_cli_commands 'AddCommand - reads from piped stdin and stores content'
  MESON_BUILD_ROOT=/Users/trevon/work/tools/yams/build/debug build/debug/tests/catch2_cli_commands
  meson compile -C build/release -j4 yams-cli yams-mcp-server
  meson compile -C build/asan-api -j2 yams-cli catch2_cli_commands
  MESON_BUILD_ROOT=/Users/trevon/work/tools/yams/build/asan-api ASAN_OPTIONS=halt_on_error=1:abort_on_error=1:print_summary=1 build/asan-api/tests/catch2_cli_commands 'AddCommand - reads from piped stdin and stores content'
  ninja -C build/release -t commands tools/yams-cli/yams-cli tools/yams-mcp/yams-mcp-server | grep libyams_daemon.a -> no output

* feat(bench): add xplan multi-arm experiment harness

Unified plan runner, ablation axes, REPORT/ablation docs, and
KPI snapshot so optimization loops stop living in shell matrices.

* feat(formal): expand topology/search Lean contracts

Boundary models for search provenance, construction gates,
and cluster/route objectives so Lean guides correctness while
xplan ranks performance levers.

* feat(search,topology): construction purity + graph expansion path

Raise topology build defaults (min edge 0.25, max component 64) and
split oversized CC pieces so hybrid assist is quality-positive on
scifact. Add GraphNeighbors expansion with medoid-anchor fallback,
structured helpers instead of nested session logic, and BEIR-default
xplan plans. Search engine extraction (fanout/classic pipeline) rides
along as the integration surface for routing.

* feat(topology): add KMeans engine and SGC identity contracts

Register kmeans in the factory with deterministic spherical k-means
over embeddings, and enforce SGC document-identity invariants in
debug builds with matching unit coverage.

* feat(daemon): topology readiness gates and selectable reranker

Drive topologyReady from published epoch/freshness/rebuild/dirty
ingest state (not just KG drain), surface those fields in search
stats, and wire onnx|simeon|auto|none cross-reranker selection.

* chore(search): drop meta_path tuner knobs

Meta-path routing is gone; remove dead TunedParams fields and the
ConfigResolver test for [search.meta_path].

* feat(bench): add topology_purity_validate plan

Repeats=3 validation matrix for construction-purity winners vs
topo_off so MRR deltas can clear run-to-run noise.

* chore: format add_command and config include order

Mechanical clang-format / include reorder only; no behavior change.

* feat(bench): decision-grade xplan loop for search engine

Document search-engine measurement in AGENTS; harden xplan with
repeats=3 plans, quality×latency primaries, mechanism metrics from
debug.jsonl, multi-rep log promotion, and archive superseded topology
plans.

* feat(graph): denser product semantic_neighbor topK

Raise default YAMS_GRAPH_SEMANTIC_TOPK fallback from 4 to 8 so product
graphs leave fewer degree-0 docs for GraphNeighbors expansion.

* feat(search): extract topology assist and cross-rerank seams

Pull topology assist into search_topology_stage (seed merge, skip
reasons, optional vector seed probe default 0). Extract cross_rerank
compute from search_engine. Wire probe via typed config/ConfigResolver.

* feat(bench): product-path search engine ablation plans

Add topology-off component, vector-weight, and tiered-execution xplan
plans (repeats=3) and wire them into the AGENTS measurement loop table.

* fix(ci): repair pre-push fallbacks

* feat(bench): lock-free mid-run builds + multi-corpus gates

xplan skips meson rebuild when the quality binary exists (flock +
YAMS_BENCH_FORCE_BUILD override) to stop multi-arm link races. Add
graph_vector weight and nfcorpus transfer-gate plans; document in AGENTS.

* fix(daemon): keep SearchEngine alive via shared_ptr cache

getCachedEngine previously published a raw pointer that metrics polling
used through rebuild, racing destructor of SearchEngine::Impl (TSAN).
Store and return a shared_ptr snapshot so diagnostic readers pin the
engine for the duration of getConfig/health checks.

Also adds the cautious vectorWeight 0.30→0.20 multi-corpus xplan plan.

* feat(search): route vectors through cached topology

Build and reuse validated topology snapshots, rank routed members by query similarity, and narrow the vector leg to the accepted document set with explicit work diagnostics.

Remove the retired HDBSCAN engine and vendor dependency, preserve typed topology policy through search tuning, and cover the runtime/configuration contracts.

* feat(bench): consolidate search decision plans

Enforce deterministic experiment identity and declared baselines, expose routed/global vector work metrics, and register the focused benchmark contracts.

Promote the compact repeats=3 routing-budget gate, archive superseded topology mechanism screens, and add multi-corpus product calibration plans.

* feat(search): refine topology vector routing

* fix(search): propagate daemon readiness

* feat(bench): measure generalized memory health

* fix(cli): honor in-process fallbacks

* ci: harden smolvm debug builds

* perf(search): route topology through filtered ANN

* feat(bench): measure read-write pressure

* perf(metadata): index symbol lookups on read pool

* fix(daemon): isolate startup reads and maintenance

* feat(bench): replay isolated generalized corpora

* feat(search): add evidence routing pipeline

Replace the blocking smolvm pre-push path with host ASan/TSan validation, harden sanitizer-sensitive smoke tests, and add recovery cleanup for malformed SQLite WAL sidecars.

* refactor(search): unify topology evidence path

Remove classic and sidecar fusion lanes so topology augments the recall-preserving ANN and lexical candidate pool through one product path.

* refactor(bench): prune superseded search lanes

Measure the topology-plus-ANN product path with stable experiment identity and remove obsolete sidecar and tiered controls.

* docs(search): retire stale experiment notes

Keep the benchmark handoff focused on the topology-plus-ANN product lane and its active decision plans.

* refactor(search): prune dead search surfaces

Remove unused fusion, reranker, policy, and router abstractions.
Bound topology materialization and keep document trace payloads opt-in.

* fix(cli): clear build warnings

* fix(xplan): reject stale run identity

* refactor(search)!: remove legacy query stack

Replace the unused AST/ranker/post-processor surface with focused facet aggregation used by product search.

BREAKING CHANGE: removes query parser, result ranker, search filter, and SearchResults container APIs from yams_search.

* refactor(search): type value stage traces

Remove synthetic ComponentResult markers for embedding and concept stages. Preserve failure and timeout states instead of overwriting them with fake successful results.

* refactor(search): isolate benchmark env overlays

Move test-only search environment parsing behind an injectable internal adapter. Keep all existing overlay keys and tuner pin semantics while restoring SearchEngineBuilder to composition.

* refactor(search): unify topology routing options

Snapshot topology policy once at the assist boundary and pass it through routing sessions and diagnostics. Remove repeated scalar copying without changing routing behavior or metric keys.

* fix(search): unify tuner config ownership

Use one complete config-to-params overlay for runtime seeding and no-tuner policy resolution. Reseed attached tuners on setConfig so reported and executed configuration cannot diverge.

* fix(search): snapshot tuner state per query

Read tuned config, params, and state under one lock before routing. Add a TSAN correlation test so adaptive observation cannot produce a torn logical query snapshot.

* fix(search): enforce topology routing contract

Generated configs must preserve hybrid-assist shadow routing, while daemon-backed search must abstain when published topology artifacts are stale. Keep standalone validation and global ANN recall intact.

* fix(daemon): let SQLite reclaim its file

Directly resizing a live database from sampled page counts can truncate pages allocated by concurrent writers. VACUUM must remain the only file-reclamation mechanism.

* fix(metadata): tolerate missing symbol FTS

Readiness lookups can race an unavailable optional FTS migration. Retain the indexed fast path, but retry against the base table when prepare or cached-statement execution proves the capability absent.

* build(fuzz): drop removed query parser target

The optional AFL build still referenced the deleted legacy query parser API and could no longer compile.

* fix(bench): include writes in drain oracle

A zero post-ingest queue is not durable drain while coordinated writes remain queued or in flight.

* fix(daemon): vacuum padded WAL databases safely
2026-07-13 20:26:43 -04:00

331 lines
14 KiB
Lean4

import Yams.Topology.TopologyInfluence
namespace Yams.SearchEngine
/-!
Selective topology routing for generalized-memory search.
The model deliberately separates three obligations that are easy to conflate in
an implementation:
* topology construction exposes an overlapping, multiscale cover;
* offline observations calibrate an empirical miss-risk certificate;
* the runtime policy may narrow only when both that certificate and a work
budget are satisfied, otherwise it augments or falls back to global ANN.
The deterministic theorems below are conditional on certificate soundness. The
empirical predicates are benchmark obligations; they are not presented as a
distribution-free statistical proof.
-/
/-- One resolution of an overlapping topology cover. `scale` is an ordinal
level, not a metric distance: callers may map it to graph radius, kNN depth, or
another construction-specific resolution. -/
structure TopologyCoverLevel where
scale : Nat := 0
clusters : List TopologyCluster := []
deriving Repr, BEq
/-- Documents represented at one cover level. Repetition is intentional because
a document may be a member of several local neighborhoods. -/
def coverDocs (cover : TopologyCoverLevel) : List Yams.Core.DocumentId :=
fragmentUnionDocs cover.clusters
/-- A cover represents every document in the corpus. Unlike a partition, this
does not require cluster disjointness. -/
def CoversCorpus
(cover : TopologyCoverLevel) (corpus : List Yams.Core.DocumentId) : Prop :=
∀ doc ∈ corpus, doc ∈ coverDocs cover
/-- `fine` refines `coarse` when every fine neighborhood is contained in some
coarse neighborhood. Overlap is allowed at both levels. -/
def RefinesCover (fine coarse : TopologyCoverLevel) : Prop :=
∀ fineCluster ∈ fine.clusters,
∃ coarseCluster ∈ coarse.clusters,
∀ doc ∈ fineCluster.docs, doc ∈ coarseCluster.docs
/-- A finite overlap cap keeps a cover from degenerating into unbounded repeated
candidate work. -/
def BoundedCoverOverlap (cover : TopologyCoverLevel) (maxOverlap : Nat) : Prop :=
∀ doc,
(cover.clusters.filter (fun cluster => cluster.docs.contains doc)).length ≤ maxOverlap
/-- Abstract local relation that a topology construction promises to preserve.
It can represent reciprocal graph edges, semantic neighbors, citations, or
cross-corpus links. -/
structure ProtectedDocumentPair where
left : Yams.Core.DocumentId
right : Yams.Core.DocumentId
deriving Repr, BEq
/-- Every protected local relation has a witnessing neighborhood in the cover. -/
def PreservesLocalPairs
(cover : TopologyCoverLevel) (pairs : List ProtectedDocumentPair) : Prop :=
∀ pair ∈ pairs,
∃ cluster ∈ cover.clusters,
pair.left ∈ cluster.docs ∧ pair.right ∈ cluster.docs
/-- Refinement cannot invent documents outside the coarser cover. -/
theorem refinement_noArbitraryDocuments
{fine coarse : TopologyCoverLevel}
(hRefines : RefinesCover fine coarse)
{doc : Yams.Core.DocumentId}
(hDoc : doc ∈ coverDocs fine) :
doc ∈ coverDocs coarse := by
simp [coverDocs, fragmentUnionDocs] at hDoc ⊢
rcases hDoc with ⟨fineCluster, hFineCluster, hFineDoc⟩
rcases hRefines fineCluster hFineCluster with
⟨coarseCluster, hCoarseCluster, hContained⟩
exact ⟨coarseCluster, hCoarseCluster, hContained doc hFineDoc⟩
/-- If a fine cover represents the corpus and refines a coarse cover, the coarse
cover represents the corpus as well. -/
theorem refinement_preservesCorpusCoverage
{fine coarse : TopologyCoverLevel}
{corpus : List Yams.Core.DocumentId}
(hRefines : RefinesCover fine coarse)
(hCovers : CoversCorpus fine corpus) :
CoversCorpus coarse corpus := by
intro doc hCorpus
exact refinement_noArbitraryDocuments hRefines (hCovers doc hCorpus)
/-- Distance work is kept explicit so routed and global ANN can be compared at
equal candidate and exact-evaluation budgets. -/
structure SearchEffort where
annCandidates : Nat := 0
distanceEvaluations : Nat := 0
exactReranks : Nat := 0
deriving Repr, BEq
structure SearchEffortBudget where
maxAnnCandidates : Nat := 0
maxDistanceEvaluations : Nat := 0
maxExactReranks : Nat := 0
deriving Repr, BEq
def EffortWithinBudget (budget : SearchEffortBudget) (effort : SearchEffort) : Prop :=
effort.annCandidates ≤ budget.maxAnnCandidates ∧
effort.distanceEvaluations ≤ budget.maxDistanceEvaluations ∧
effort.exactReranks ≤ budget.maxExactReranks
/-- Offline validation of a route class. Miss risk is represented as an integer
rate per 1000 protected candidates so the core model needs no floating-point or
probability dependency. -/
structure RouteRiskObservation where
calibrationQueries : Nat := 0
protectedCandidates : Nat := 0
missedProtectedCandidates : Nat := 0
deriving Repr, BEq
structure SelectiveRouteConfig where
minRouteMargin : Nat := 0
minSeedHits : Nat := 0
minCalibrationQueries : Nat := 1
maxMissesPerThousand : Nat := 0
effortBudget : SearchEffortBudget := {}
deriving Repr, BEq
/-- Evidence available to the routing boundary. `risk` comes from an offline
query class or corpus-stratified calibration run; it is not recomputed from
unknown relevance judgments at query time. -/
structure SelectiveRouteCertificate where
allowedDocs : List Yams.Core.DocumentId := []
routeMargin : Nat := 0
seedHits : Nat := 0
risk : RouteRiskObservation := {}
effort : SearchEffort := {}
deriving Repr, BEq
/-- Empirical miss-risk threshold. Non-empty protected evidence prevents a route
class with no relevance observations from being certified accidentally. -/
def EmpiricalMissRiskWithin
(maxMissesPerThousand : Nat) (obs : RouteRiskObservation) : Prop :=
0 < obs.protectedCandidates ∧
obs.missedProtectedCandidates * 1000 ≤
maxMissesPerThousand * obs.protectedCandidates
/-- Complete admission predicate for hard narrowing. -/
def RouteCertificateAdmissible
(cfg : SelectiveRouteConfig) (certificate : SelectiveRouteCertificate) : Prop :=
cfg.minRouteMargin ≤ certificate.routeMargin ∧
cfg.minSeedHits ≤ certificate.seedHits ∧
cfg.minCalibrationQueries ≤ certificate.risk.calibrationQueries ∧
EmpiricalMissRiskWithin cfg.maxMissesPerThousand certificate.risk ∧
EffortWithinBudget cfg.effortBudget certificate.effort
instance routeCertificateAdmissibleDecidable
(cfg : SelectiveRouteConfig)
(certificate : SelectiveRouteCertificate) :
Decidable (RouteCertificateAdmissible cfg certificate) := by
unfold RouteCertificateAdmissible EmpiricalMissRiskWithin EffortWithinBudget
infer_instance
/-- Selective routing is intentionally three-way. Weak evidence with a useful
route augments global ANN; no useful route falls back; only admitted evidence
may replace global candidates. -/
inductive SelectiveRoutingAction where
| global
| augment
| narrow
deriving Repr, BEq, DecidableEq
def selectRoutingAction
(cfg : SelectiveRouteConfig)
(certificate : SelectiveRouteCertificate) : SelectiveRoutingAction :=
if RouteCertificateAdmissible cfg certificate then
.narrow
else if certificate.allowedDocs.isEmpty then
.global
else
.augment
/-- Convert allowed documents into query-score placeholders. The production
implementation must replace the zero score with query similarity before fusion. -/
def allowedDocumentCandidates
(allowedDocs : List Yams.Core.DocumentId) : List ComponentCandidate :=
allowedDocs.map (fun doc => { doc := doc, source := .vector, score := 0 })
def applySelectiveRoute
(cfg : SelectiveRouteConfig)
(certificate : SelectiveRouteCertificate)
(globalCandidates : List ComponentCandidate) : List ComponentCandidate :=
match selectRoutingAction cfg certificate with
| .global => globalCandidates
| .augment => globalCandidates ++ allowedDocumentCandidates certificate.allowedDocs
| .narrow =>
globalCandidates.filter
(fun candidate => certificate.allowedDocs.contains candidate.doc)
/-- An inadmissible empty route is exactly global ANN. -/
theorem selectiveRoute_emptyFallback_identity
{cfg : SelectiveRouteConfig}
{certificate : SelectiveRouteCertificate}
{globalCandidates : List ComponentCandidate}
(hRejected : ¬ RouteCertificateAdmissible cfg certificate)
(hEmpty : certificate.allowedDocs = []) :
applySelectiveRoute cfg certificate globalCandidates = globalCandidates := by
simp [applySelectiveRoute, selectRoutingAction, hRejected, hEmpty]
/-- An inadmissible non-empty route is additive and cannot remove a global ANN
candidate before the ordinary fusion budget is applied. -/
theorem selectiveRoute_augmentation_preservesGlobal
{cfg : SelectiveRouteConfig}
{certificate : SelectiveRouteCertificate}
{globalCandidates : List ComponentCandidate}
{candidate : ComponentCandidate}
(hRejected : ¬ RouteCertificateAdmissible cfg certificate)
(hNonEmpty : certificate.allowedDocs ≠ [])
(hCandidate : candidate ∈ globalCandidates) :
candidate ∈ applySelectiveRoute cfg certificate globalCandidates := by
simp [applySelectiveRoute, selectRoutingAction, hRejected, hNonEmpty]
exact Or.inl hCandidate
/-- Hard narrowing cannot invent a candidate absent from global ANN. -/
theorem selectiveRoute_narrow_subset
{cfg : SelectiveRouteConfig}
{certificate : SelectiveRouteCertificate}
{globalCandidates : List ComponentCandidate}
{candidate : ComponentCandidate}
(hAdmitted : RouteCertificateAdmissible cfg certificate)
(hCandidate : candidate ∈ applySelectiveRoute cfg certificate globalCandidates) :
candidate ∈ globalCandidates := by
have hFiltered : candidate ∈ globalCandidates ∧
candidate.doc ∈ certificate.allowedDocs := by
simpa [applySelectiveRoute, selectRoutingAction, hAdmitted] using hCandidate
exact hFiltered.1
/-- Runtime soundness obligation for a protected candidate set. Calibration may
justify trusting a route class, but the deterministic preservation theorem needs
the selected allowed-document set to cover the protected candidates. -/
def CertificateCoversProtected
(certificate : SelectiveRouteCertificate)
(protectedCandidates : List ComponentCandidate) : Prop :=
∀ candidate ∈ protectedCandidates, candidate.doc ∈ certificate.allowedDocs
/-- The three-way policy preserves every protected global candidate when any
admitted hard route satisfies its coverage obligation. Rejected routes are safe
by construction because they augment or fall back. -/
theorem selectiveRoute_preservesProtected
{cfg : SelectiveRouteConfig}
{certificate : SelectiveRouteCertificate}
{globalCandidates protectedCandidates : List ComponentCandidate}
(hPresent : ∀ candidate ∈ protectedCandidates, candidate ∈ globalCandidates)
(hSound : RouteCertificateAdmissible cfg certificate →
CertificateCoversProtected certificate protectedCandidates) :
∀ candidate ∈ protectedCandidates,
candidate ∈ applySelectiveRoute cfg certificate globalCandidates := by
intro candidate hProtected
by_cases hAdmitted : RouteCertificateAdmissible cfg certificate
· simp [applySelectiveRoute, selectRoutingAction, hAdmitted,
hPresent candidate hProtected, hSound hAdmitted candidate hProtected]
· by_cases hEmpty : certificate.allowedDocs = []
· simpa [applySelectiveRoute, selectRoutingAction, hAdmitted, hEmpty] using
hPresent candidate hProtected
· simp [applySelectiveRoute, selectRoutingAction, hAdmitted, hEmpty,
hPresent candidate hProtected]
/-- Admission exposes each equal-budget comparison obligation directly. -/
theorem admissibleRoute_respectsEffortBudget
{cfg : SelectiveRouteConfig}
{certificate : SelectiveRouteCertificate}
(hAdmitted : RouteCertificateAdmissible cfg certificate) :
EffortWithinBudget cfg.effortBudget certificate.effort := by
exact hAdmitted.2.2.2.2
/-- Per-corpus recall observations use counts rather than rounded floating-point
metrics. Cross multiplication allows baseline and current runs to have different
numbers of relevance judgments. -/
structure CorpusRecallObservation where
corpus : String
relevantJudgments : Nat := 0
retrievedRelevant : Nat := 0
deriving Repr, BEq
def ValidCorpusRecallObservation (obs : CorpusRecallObservation) : Prop :=
0 < obs.relevantJudgments ∧ obs.retrievedRelevant ≤ obs.relevantJudgments
def RecallAtLeast
(baseline current : CorpusRecallObservation) : Prop :=
baseline.retrievedRelevant * current.relevantJudgments ≤
current.retrievedRelevant * baseline.relevantJudgments
structure CorpusRecallComparison where
baseline : CorpusRecallObservation
current : CorpusRecallObservation
deriving Repr, BEq
/-- A product-promotion gate is conjunctive over corpora: an aggregate gain may
not hide a regression on a smaller memory domain. -/
def PreservesCorpusRecall (comparison : CorpusRecallComparison) : Prop :=
comparison.baseline.corpus = comparison.current.corpus ∧
ValidCorpusRecallObservation comparison.baseline ∧
ValidCorpusRecallObservation comparison.current ∧
RecallAtLeast comparison.baseline comparison.current
def GeneralizedMemoryRecallFloor
(comparisons : List CorpusRecallComparison) : Prop :=
∀ comparison ∈ comparisons, PreservesCorpusRecall comparison
/-- One failing corpus is enough to reject default promotion, even if a macro or
pooled metric improved. -/
theorem generalizedMemoryFloor_rejectsCorpusRegression
{comparisons : List CorpusRecallComparison}
{comparison : CorpusRecallComparison}
(hMember : comparison ∈ comparisons)
(hRegression : ¬ PreservesCorpusRecall comparison) :
¬ GeneralizedMemoryRecallFloor comparisons := by
intro hFloor
exact hRegression (hFloor comparison hMember)
/-- With equal relevance judgments, preserving retrieved-relevant count is
sufficient for the rational recall floor. -/
theorem recallAtLeast_of_equalJudgments_and_hits
{baseline current : CorpusRecallObservation}
(hJudgments : baseline.relevantJudgments = current.relevantJudgments)
(hHits : baseline.retrievedRelevant ≤ current.retrievedRelevant) :
RecallAtLeast baseline current := by
unfold RecallAtLeast
rw [← hJudgments]
exact Nat.mul_le_mul_right baseline.relevantJudgments hHits
end Yams.SearchEngine