{
  "nbformat": 4,
  "nbformat_minor": 5,
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "name": "python",
      "version": "3.13.0"
    },
    "blog_metadata": {
      "topic": "Why AI Search Relevance Is Becoming a Data Platform Problem, Not Just an App Feature",
      "slug": "why-ai-search-relevance-is-becoming-a-data-platform-problem-",
      "generated_by": "LinkedIn Post Generator + Azure OpenAI",
      "generated_at": "2026-11-19T20:37:36.702Z"
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Why AI Search Relevance Is Becoming a Data Platform Problem, Not Just an App Feature\n",
        "\n",
        "This notebook turns the blog post into a hands-on validation workflow. The core idea is that AI search relevance is usually limited by upstream data-platform concerns like freshness, metadata quality, chunk design, and access control, not just prompts or rerankers.\n",
        "\n",
        "You will validate that thesis with small Python examples for stale-content detection, auth-aware filtering, evaluation logging, KPI calculation, and simple architecture diagrams."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "%pip install -q pandas matplotlib networkx"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "from dataclasses import dataclass, asdict\n",
        "from datetime import datetime, timedelta, timezone\n",
        "import json\n",
        "import time\n",
        "import math\n",
        "import statistics\n",
        "from pathlib import Path\n",
        "\n",
        "import pandas as pd\n",
        "import matplotlib.pyplot as plt\n",
        "import networkx as nx"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Thesis and operating model\n",
        "\n",
        "The blog argues that enterprise AI search should be run as a data-platform capability. App teams still own interaction design and domain tuning, but retrieval quality depends on shared ingestion contracts, metadata standards, security propagation, freshness guarantees, and observability.\n",
        "\n",
        "The quick self-check below scores whether your organization behaves more like a reusable relevance platform or a collection of isolated search features."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "assessment = {\n",
        "    \"shared_ingestion_contracts\": True,\n",
        "    \"canonical_doc_and_chunk_ids\": True,\n",
        "    \"metadata_validation_rules\": False,\n",
        "    \"authorization_propagation\": True,\n",
        "    \"freshness_slos\": False,\n",
        "    \"evaluation_harness\": True,\n",
        "    \"ranking_signal_logging\": False,\n",
        "    \"incident_paths_to_sources\": False,\n",
        "}\n",
        "\n",
        "score = sum(assessment.values())\n",
        "max_score = len(assessment)\n",
        "rating_5 = round((score / max_score) * 5, 1)\n",
        "\n",
        "print(\"Platform capability checklist:\")\n",
        "for k, v in assessment.items():\n",
        "    print(f\"- {k}: {'yes' if v else 'no'}\")\n",
        "\n",
        "print({\"raw_score\": score, \"max_score\": max_score, \"rating_out_of_5\": rating_5})"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Architecture lifecycle diagram\n",
        "\n",
        "This diagram converts the blog's relevance lifecycle into a simple directed graph. The important point is that retrieval quality starts before query time, with change detection, metadata validation, chunking, and auth-aware retrieval."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "edges = [\n",
        "    (\"Source Systems\", \"Change Detection\"),\n",
        "    (\"Change Detection\", \"Metadata Validation\"),\n",
        "    (\"Metadata Validation\", \"Chunking + Embeddings\"),\n",
        "    (\"Chunking + Embeddings\", \"Vector + Keyword Indexes\"),\n",
        "    (\"Vector + Keyword Indexes\", \"Auth-Aware Retrieval\"),\n",
        "    (\"Auth-Aware Retrieval\", \"Ranking + Reranking\"),\n",
        "    (\"Ranking + Reranking\", \"User Response\"),\n",
        "    (\"Metadata Validation\", \"Exception Report\"),\n",
        "    (\"Auth-Aware Retrieval\", \"Evaluation Harness\"),\n",
        "    (\"Ranking + Reranking\", \"Evaluation Harness\"),\n",
        "    (\"User Response\", \"Evaluation Harness\"),\n",
        "]\n",
        "\n",
        "G = nx.DiGraph()\n",
        "G.add_edges_from(edges)\n",
        "\n",
        "plt.figure(figsize=(14, 7))\n",
        "pos = nx.spring_layout(G, seed=7, k=1.2)\n",
        "nx.draw_networkx(\n",
        "    G,\n",
        "    pos,\n",
        "    with_labels=True,\n",
        "    node_size=3200,\n",
        "    node_color=\"#DCEEFF\",\n",
        "    font_size=9,\n",
        "    arrows=True,\n",
        "    arrowstyle=\"-|>\",\n",
        "    arrowsize=18,\n",
        ")\n",
        "plt.title(\"AI Search Relevance Lifecycle\")\n",
        "plt.axis(\"off\")\n",
        "plt.show()"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Detect stale indexed documents\n",
        "\n",
        "This example validates the blog's claim that freshness is an operational contract. Before tuning prompts or ranking, compare source timestamps with index timestamps and flag stale or missing indexed content."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "# Detect stale indexed documents by comparing source and index timestamps\n",
        "from datetime import datetime, timedelta, timezone\n",
        "\n",
        "source = {\"D1\": datetime.now(timezone.utc), \"D2\": datetime.now(timezone.utc) - timedelta(hours=1)}\n",
        "index = {\"D1\": datetime.now(timezone.utc) - timedelta(minutes=5), \"D2\": datetime.now(timezone.utc) - timedelta(days=2)}\n",
        "\n",
        "stale = []\n",
        "for doc_id, src_ts in source.items():\n",
        "    idx_ts = index.get(doc_id)\n",
        "    if idx_ts is None or idx_ts < src_ts:\n",
        "        stale.append({\"doc_id\": doc_id, \"source_ts\": src_ts.isoformat(), \"index_ts\": idx_ts.isoformat() if idx_ts else None})\n",
        "\n",
        "print(stale)\n",
        "\n",
        "stale_df = pd.DataFrame(stale)\n",
        "stale_df"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Freshness SLO view by source\n",
        "\n",
        "A single stale-document list is useful, but platform teams need measurable signals. This example expands the freshness idea into a small operational table with lag in minutes and a stale-rate summary by source system."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "now = datetime.now(timezone.utc)\n",
        "source_docs = [\n",
        "    {\"doc_id\": \"D1\", \"source_system\": \"SharePoint\", \"source_ts\": now - timedelta(minutes=10)},\n",
        "    {\"doc_id\": \"D2\", \"source_system\": \"SharePoint\", \"source_ts\": now - timedelta(hours=2)},\n",
        "    {\"doc_id\": \"D3\", \"source_system\": \"Confluence\", \"source_ts\": now - timedelta(minutes=30)},\n",
        "    {\"doc_id\": \"D4\", \"source_system\": \"Confluence\", \"source_ts\": now - timedelta(days=1)},\n",
        "]\n",
        "index_docs = {\n",
        "    \"D1\": now - timedelta(minutes=8),\n",
        "    \"D2\": now - timedelta(days=2),\n",
        "    \"D3\": now - timedelta(minutes=25),\n",
        "}\n",
        "\n",
        "rows = []\n",
        "for d in source_docs:\n",
        "    idx_ts = index_docs.get(d[\"doc_id\"])\n",
        "    lag_minutes = None if idx_ts is None else round((d[\"source_ts\"] - idx_ts).total_seconds() / 60, 1)\n",
        "    is_stale = idx_ts is None or idx_ts < d[\"source_ts\"]\n",
        "    rows.append({\n",
        "        \"doc_id\": d[\"doc_id\"],\n",
        "        \"source_system\": d[\"source_system\"],\n",
        "        \"source_ts\": d[\"source_ts\"],\n",
        "        \"index_ts\": idx_ts,\n",
        "        \"lag_minutes\": lag_minutes,\n",
        "        \"is_stale\": is_stale,\n",
        "    })\n",
        "\n",
        "freshness_df = pd.DataFrame(rows)\n",
        "print(freshness_df)\n",
        "print()\n",
        "print(\"Stale rate by source:\")\n",
        "print(freshness_df.groupby(\"source_system\")[\"is_stale\"].mean().round(2))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Enforce metadata and authorization filters before ranking\n",
        "\n",
        "This example demonstrates a hard rule from the blog: metadata filters and ACL checks should happen before final ranking. That keeps the candidate set trustworthy and avoids misleading relevance metrics."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "# Enforce metadata and authorization filters before ranking to keep relevance trustworthy\n",
        "chunks = [\n",
        "    {\"chunk_id\": \"c1\", \"region\": \"US\", \"acl\": {\"alice\", \"bob\"}, \"score\": 0.91},\n",
        "    {\"chunk_id\": \"c2\", \"region\": \"EU\", \"acl\": {\"bob\"}, \"score\": 0.95},\n",
        "    {\"chunk_id\": \"c3\", \"region\": \"US\", \"acl\": {\"alice\"}, \"score\": 0.72},\n",
        "]\n",
        "\n",
        "user = \"alice\"\n",
        "filters = {\"region\": \"US\"}\n",
        "\n",
        "eligible = [\n",
        "    c for c in chunks\n",
        "    if c[\"region\"] == filters[\"region\"] and user in c[\"acl\"]\n",
        "]\n",
        "ranked = sorted(eligible, key=lambda x: x[\"score\"], reverse=True)\n",
        "\n",
        "for item in ranked:\n",
        "    print(item[\"chunk_id\"], item[\"score\"])\n",
        "\n",
        "pd.DataFrame(ranked)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Compare rank-first versus filter-first behavior\n",
        "\n",
        "To make the previous point concrete, this example compares two retrieval paths. One ranks everything first and trims later, while the other filters by policy and metadata first, then ranks only eligible content."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "chunks = [\n",
        "    {\"chunk_id\": \"c1\", \"region\": \"US\", \"acl\": {\"alice\", \"bob\"}, \"score\": 0.91},\n",
        "    {\"chunk_id\": \"c2\", \"region\": \"EU\", \"acl\": {\"bob\"}, \"score\": 0.95},\n",
        "    {\"chunk_id\": \"c3\", \"region\": \"US\", \"acl\": {\"alice\"}, \"score\": 0.72},\n",
        "    {\"chunk_id\": \"c4\", \"region\": \"US\", \"acl\": {\"carol\"}, \"score\": 0.93},\n",
        "]\n",
        "user = \"alice\"\n",
        "filters = {\"region\": \"US\"}\n",
        "\n",
        "rank_first = sorted(chunks, key=lambda x: x[\"score\"], reverse=True)\n",
        "trimmed_after = [c for c in rank_first if c[\"region\"] == filters[\"region\"] and user in c[\"acl\"]]\n",
        "\n",
        "filtered_before = [c for c in chunks if c[\"region\"] == filters[\"region\"] and user in c[\"acl\"]]\n",
        "ranked_after_filter = sorted(filtered_before, key=lambda x: x[\"score\"], reverse=True)\n",
        "\n",
        "print(\"Top ranked before trimming:\")\n",
        "for c in rank_first:\n",
        "    print(c[\"chunk_id\"], c[\"score\"], c[\"region\"], user in c[\"acl\"])\n",
        "\n",
        "print(\"\\nAuthorized results after rank-first trim:\")\n",
        "for c in trimmed_after:\n",
        "    print(c[\"chunk_id\"], c[\"score\"])\n",
        "\n",
        "print(\"\\nAuthorized results with filter-first ranking:\")\n",
        "for c in ranked_after_filter:\n",
        "    print(c[\"chunk_id\"], c[\"score\"])\n",
        "\n",
        "print({\n",
        "    \"rank_first_candidate_count\": len(rank_first),\n",
        "    \"filter_first_candidate_count\": len(filtered_before),\n",
        "    \"authorized_result_count\": len(ranked_after_filter),\n",
        "})"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Query path instrumentation diagram\n",
        "\n",
        "The blog emphasizes that production relevance systems must log filters, candidate chunks, auth outcomes, and latency. This diagram models that request path as a sequence-like flow using a directed graph."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "sequence_edges = [\n",
        "    (\"User Query\", \"Retrieval API\"),\n",
        "    (\"Retrieval API\", \"Search Index\"),\n",
        "    (\"Search Index\", \"Retrieval API\"),\n",
        "    (\"Retrieval API\", \"Policy/Auth Filter\"),\n",
        "    (\"Policy/Auth Filter\", \"Retrieval API\"),\n",
        "    (\"Retrieval API\", \"Eval Logger\"),\n",
        "    (\"Retrieval API\", \"Ranked Authorized Results\"),\n",
        "]\n",
        "\n",
        "SG = nx.DiGraph()\n",
        "SG.add_edges_from(sequence_edges)\n",
        "\n",
        "plt.figure(figsize=(14, 4))\n",
        "pos = {\n",
        "    \"User Query\": (0, 0),\n",
        "    \"Retrieval API\": (2, 0),\n",
        "    \"Search Index\": (4, 0),\n",
        "    \"Policy/Auth Filter\": (6, 0),\n",
        "    \"Eval Logger\": (8, 0.8),\n",
        "    \"Ranked Authorized Results\": (8, -0.8),\n",
        "}\n",
        "\n",
        "nx.draw_networkx(\n",
        "    SG,\n",
        "    pos,\n",
        "    with_labels=True,\n",
        "    node_size=3000,\n",
        "    node_color=\"#F3E8FF\",\n",
        "    font_size=9,\n",
        "    arrows=True,\n",
        "    arrowstyle=\"-|>\",\n",
        "    arrowsize=18,\n",
        ")\n",
        "plt.title(\"Instrumented Query Path\")\n",
        "plt.axis(\"off\")\n",
        "plt.show()"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Retrieval evaluation harness\n",
        "\n",
        "This example captures the minimum record shape needed for useful offline evaluation: query, chunk id, filters, auth outcome, ranking signals, latency, and judgment. The goal is to trace a bad experience back to a pipeline stage instead of blaming the model by default."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "# Retrieval evaluation harness capturing filters, auth outcomes, ranking signals, latency, and judgments\n",
        "from dataclasses import dataclass, asdict\n",
        "import json, time\n",
        "\n",
        "@dataclass\n",
        "class EvalRecord:\n",
        "    query: str; chunk_id: str; filters: dict; auth_allowed: bool\n",
        "    ranking_signals: dict; latency_ms: float; judgment: str\n",
        "\n",
        "tests = [{\"query\": \"SOC2 retention policy\", \"filters\": {\"region\": \"US\"}, \"allowed_docs\": {\"c1\"}}]\n",
        "retrieved = [{\"chunk_id\": \"c1\", \"doc_id\": \"d1\", \"score\": 0.91, \"bm25\": 12.4, \"semantic\": 0.88, \"region\": \"US\"}]\n",
        "\n",
        "records = []\n",
        "for t in tests:\n",
        "    start = time.perf_counter()\n",
        "    for r in retrieved:\n",
        "        auth_allowed = r[\"chunk_id\"] in t[\"allowed_docs\"]\n",
        "        judgment = \"relevant\" if auth_allowed and r[\"score\"] > 0.9 else \"non_relevant\"\n",
        "        records.append(EvalRecord(\n",
        "            query=t[\"query\"], chunk_id=r[\"chunk_id\"], filters=t[\"filters\"],\n",
        "            auth_allowed=auth_allowed,\n",
        "            ranking_signals={\"final\": r[\"score\"], \"bm25\": r[\"bm25\"], \"semantic\": r[\"semantic\"]},\n",
        "            latency_ms=(time.perf_counter() - start) * 1000, judgment=judgment\n",
        "        ))\n",
        "\n",
        "print(json.dumps([asdict(x) for x in records], indent=2))\n",
        "\n",
        "eval_df = pd.DataFrame([asdict(x) for x in records])\n",
        "eval_df"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Expanded evaluation harness with multiple queries\n",
        "\n",
        "A single record proves the shape, but multiple queries make the platform issues easier to see. This example adds mixed auth outcomes, metadata filters, and ranking signals so you can inspect where relevance and permissions diverge."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "@dataclass\n",
        "class EvalRecord2:\n",
        "    query: str\n",
        "    chunk_id: str\n",
        "    filters: dict\n",
        "    auth_allowed: bool\n",
        "    ranking_signals: dict\n",
        "    latency_ms: float\n",
        "    judgment: str\n",
        "\n",
        "\n",
        "tests = [\n",
        "    {\"query\": \"SOC2 retention policy\", \"filters\": {\"region\": \"US\"}, \"allowed_docs\": {\"c1\", \"c5\"}},\n",
        "    {\"query\": \"EU invoice rules\", \"filters\": {\"region\": \"EU\"}, \"allowed_docs\": {\"c2\"}},\n",
        "]\n",
        "retrieved_by_query = {\n",
        "    \"SOC2 retention policy\": [\n",
        "        {\"chunk_id\": \"c1\", \"doc_id\": \"d1\", \"score\": 0.91, \"bm25\": 12.4, \"semantic\": 0.88, \"region\": \"US\"},\n",
        "        {\"chunk_id\": \"c9\", \"doc_id\": \"d9\", \"score\": 0.89, \"bm25\": 11.8, \"semantic\": 0.84, \"region\": \"US\"},\n",
        "    ],\n",
        "    \"EU invoice rules\": [\n",
        "        {\"chunk_id\": \"c2\", \"doc_id\": \"d2\", \"score\": 0.93, \"bm25\": 13.1, \"semantic\": 0.9, \"region\": \"EU\"},\n",
        "        {\"chunk_id\": \"c3\", \"doc_id\": \"d3\", \"score\": 0.87, \"bm25\": 10.2, \"semantic\": 0.82, \"region\": \"EU\"},\n",
        "    ],\n",
        "}\n",
        "\n",
        "records = []\n",
        "for t in tests:\n",
        "    start = time.perf_counter()\n",
        "    for r in retrieved_by_query[t[\"query\"]]:\n",
        "        auth_allowed = r[\"chunk_id\"] in t[\"allowed_docs\"]\n",
        "        region_match = r[\"region\"] == t[\"filters\"][\"region\"]\n",
        "        judgment = \"relevant\" if auth_allowed and region_match and r[\"score\"] >= 0.9 else \"non_relevant\"\n",
        "        records.append(EvalRecord2(\n",
        "            query=t[\"query\"],\n",
        "            chunk_id=r[\"chunk_id\"],\n",
        "            filters=t[\"filters\"],\n",
        "            auth_allowed=auth_allowed,\n",
        "            ranking_signals={\"final\": r[\"score\"], \"bm25\": r[\"bm25\"], \"semantic\": r[\"semantic\"]},\n",
        "            latency_ms=(time.perf_counter() - start) * 1000,\n",
        "            judgment=judgment,\n",
        "        ))\n",
        "\n",
        "expanded_eval_df = pd.DataFrame([asdict(x) for x in records])\n",
        "expanded_eval_df"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Compute simple relevance KPIs\n",
        "\n",
        "This example calculates a few basic metrics from evaluation records. Even simple KPIs like precision-at-k, auth block rate, and average latency can reveal whether the issue is relevance, permissions, or both."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "# Compute simple relevance KPIs from evaluation records to expose data-platform issues\n",
        "records = [\n",
        "    {\"query\": \"SOC2 retention policy\", \"chunk_id\": \"c1\", \"auth_allowed\": True, \"judgment\": \"relevant\", \"latency_ms\": 42},\n",
        "    {\"query\": \"SOC2 retention policy\", \"chunk_id\": \"c9\", \"auth_allowed\": False, \"judgment\": \"non_relevant\", \"latency_ms\": 42},\n",
        "    {\"query\": \"EU invoice rules\", \"chunk_id\": \"c3\", \"auth_allowed\": True, \"judgment\": \"non_relevant\", \"latency_ms\": 65},\n",
        "]\n",
        "\n",
        "total = len(records)\n",
        "relevant = sum(r[\"judgment\"] == \"relevant\" for r in records)\n",
        "blocked = sum(not r[\"auth_allowed\"] for r in records)\n",
        "p_at_k = relevant / total if total else 0.0\n",
        "auth_block_rate = blocked / total if total else 0.0\n",
        "avg_latency = sum(r[\"latency_ms\"] for r in records) / total if total else 0.0\n",
        "\n",
        "print({\"precision_at_k\": round(p_at_k, 2), \"auth_block_rate\": round(auth_block_rate, 2), \"avg_latency_ms\": round(avg_latency, 1)})"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## KPI breakdown by query and signal\n",
        "\n",
        "Platform teams usually need more than one aggregate number. This example computes per-query metrics and visualizes latency so you can separate ranking quality issues from operational health issues."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "kpi_df = expanded_eval_df.copy()\n",
        "kpi_df[\"is_relevant\"] = kpi_df[\"judgment\"].eq(\"relevant\")\n",
        "kpi_df[\"is_blocked\"] = ~kpi_df[\"auth_allowed\"]\n",
        "\n",
        "summary = kpi_df.groupby(\"query\").agg(\n",
        "    precision_at_k=(\"is_relevant\", \"mean\"),\n",
        "    auth_block_rate=(\"is_blocked\", \"mean\"),\n",
        "    avg_latency_ms=(\"latency_ms\", \"mean\"),\n",
        "    retrieved=(\"chunk_id\", \"count\"),\n",
        ").round(3)\n",
        "\n",
        "print(summary)\n",
        "\n",
        "summary[[\"precision_at_k\", \"auth_block_rate\", \"avg_latency_ms\"]].plot(kind=\"bar\", figsize=(10, 4), rot=20)\n",
        "plt.title(\"Per-query relevance and operational KPIs\")\n",
        "plt.ylabel(\"value\")\n",
        "plt.tight_layout()\n",
        "plt.show()"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Metadata completeness as ranking infrastructure\n",
        "\n",
        "The blog argues that metadata is not admin garnish; it is ranking infrastructure. This example checks required fields, computes completeness rates, and shows how missing metadata can be surfaced as a platform signal."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "docs = [\n",
        "    {\"DocumentId\": \"D1\", \"Title\": \"Policy\", \"Owner\": \"Legal\", \"Region\": \"US\", \"LifecycleState\": \"Published\"},\n",
        "    {\"DocumentId\": \"D2\", \"Title\": \"\", \"Owner\": \"\", \"Region\": \"EU\", \"LifecycleState\": \"Published\"},\n",
        "    {\"DocumentId\": \"D3\", \"Title\": \"Invoice Rules\", \"Owner\": \"Finance\", \"Region\": None, \"LifecycleState\": \"Draft\"},\n",
        "    {\"DocumentId\": \"D4\", \"Title\": \"Travel Policy\", \"Owner\": \"HR\", \"Region\": \"US\", \"LifecycleState\": None},\n",
        "]\n",
        "required = [\"DocumentId\", \"Title\", \"Owner\", \"Region\", \"LifecycleState\"]\n",
        "\n",
        "rows = []\n",
        "for d in docs:\n",
        "    missing = [f for f in required if not d.get(f)]\n",
        "    rows.append({\n",
        "        \"DocumentId\": d[\"DocumentId\"],\n",
        "        \"missing_fields\": missing,\n",
        "        \"missing_count\": len(missing),\n",
        "        \"is_complete\": len(missing) == 0,\n",
        "    })\n",
        "\n",
        "metadata_df = pd.DataFrame(rows)\n",
        "print(metadata_df)\n",
        "print()\n",
        "completeness = {f: round(sum(bool(d.get(f)) for d in docs) / len(docs), 2) for f in required}\n",
        "print(\"Field completeness:\", completeness)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Chunking is a data-modeling decision\n",
        "\n",
        "Chunking affects what can be retrieved, secured, refreshed, and cited. This example compares coarse and fine chunking over the same document to show how chunk boundaries change candidate quality and business meaning."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "document = {\n",
        "    \"doc_id\": \"POL-001\",\n",
        "    \"title\": \"Retention Policy\",\n",
        "    \"sections\": [\n",
        "        \"Overview: This policy defines retention requirements for enterprise records.\",\n",
        "        \"US Rules: Keep SOC2 audit evidence for 12 months.\",\n",
        "        \"EU Rules: Keep invoice records for 10 years.\",\n",
        "        \"Exceptions: Legal hold overrides standard retention windows.\",\n",
        "    ],\n",
        "}\n",
        "\n",
        "coarse_chunks = [{\n",
        "    \"chunk_id\": \"POL-001-C1\",\n",
        "    \"doc_id\": document[\"doc_id\"],\n",
        "    \"text\": \" \".join(document[\"sections\"]),\n",
        "    \"parent_id\": document[\"doc_id\"],\n",
        "}]\n",
        "\n",
        "fine_chunks = [\n",
        "    {\n",
        "        \"chunk_id\": f\"POL-001-S{i+1}\",\n",
        "        \"doc_id\": document[\"doc_id\"],\n",
        "        \"text\": section,\n",
        "        \"parent_id\": document[\"doc_id\"],\n",
        "        \"section_index\": i + 1,\n",
        "    }\n",
        "    for i, section in enumerate(document[\"sections\"])\n",
        "]\n",
        "\n",
        "query = \"SOC2 retention policy\"\n",
        "query_terms = set(query.lower().split())\n",
        "\n",
        "def lexical_score(text):\n",
        "    terms = set(text.lower().replace(\":\", \"\").replace(\".\", \"\").split())\n",
        "    return len(query_terms & terms)\n",
        "\n",
        "coarse_results = [{**c, \"score\": lexical_score(c[\"text\"])} for c in coarse_chunks]\n",
        "fine_results = [{**c, \"score\": lexical_score(c[\"text\"])} for c in fine_chunks]\n",
        "\n",
        "print(\"Coarse chunking:\")\n",
        "print(pd.DataFrame(coarse_results)[[\"chunk_id\", \"score\", \"text\"]])\n",
        "print(\"\\nFine chunking:\")\n",
        "print(pd.DataFrame(fine_results)[[\"chunk_id\", \"section_index\", \"score\", \"text\"]].sort_values(\"score\", ascending=False))"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Exception reporting for ingestion quality\n",
        "\n",
        "The blog recommends blocking or at least flagging ingestion when required metadata is missing. This Python version creates an exception report artifact and simulates a pipeline decision based on severity."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "exceptions = [\n",
        "    {\"DocumentId\": \"D2\", \"MissingFields\": \"Title,Owner\", \"Severity\": \"Error\"},\n",
        "    {\"DocumentId\": \"D7\", \"MissingFields\": \"Region\", \"Severity\": \"Warning\"},\n",
        "]\n",
        "\n",
        "report_path = Path(\"ingestion-exceptions.csv\")\n",
        "pd.DataFrame(exceptions).to_csv(report_path, index=False)\n",
        "\n",
        "has_blocking_errors = any(x[\"Severity\"] == \"Error\" for x in exceptions)\n",
        "if has_blocking_errors:\n",
        "    print(f\"Blocking ingestion. See {report_path.resolve()}\")\n",
        "else:\n",
        "    print(f\"No blocking exceptions. Report saved to {report_path.resolve()}\")\n",
        "\n",
        "pd.read_csv(report_path)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Triage flow for relevance incidents\n",
        "\n",
        "Many search incidents are really freshness, metadata, ACL, or indexing incidents. This diagram turns the blog's triage path into a simple graph that emphasizes fixing the data pipeline, not just the interface."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {},
      "source": [
        "triage_edges = [\n",
        "    (\"Relevance Issue\", \"App bug?\"),\n",
        "    (\"App bug?\", \"Check source freshness\"),\n",
        "    (\"Check source freshness\", \"Validate metadata completeness\"),\n",
        "    (\"Validate metadata completeness\", \"Verify ACL propagation\"),\n",
        "    (\"Verify ACL propagation\", \"Inspect chunking and indexing\"),\n",
        "    (\"Inspect chunking and indexing\", \"Review ranking signals and judgments\"),\n",
        "    (\"Review ranking signals and judgments\", \"Fix data pipeline, not just UI\"),\n",
        "]\n",
        "\n",
        "TG = nx.DiGraph()\n",
        "TG.add_edges_from(triage_edges)\n",
        "\n",
        "plt.figure(figsize=(14, 5))\n",
        "pos = nx.spring_layout(TG, seed=11, k=1.5)\n",
        "nx.draw_networkx(\n",
        "    TG,\n",
        "    pos,\n",
        "    with_labels=True,\n",
        "    node_size=3200,\n",
        "    node_color=\"#FFE8CC\",\n",
        "    font_size=9,\n",
        "    arrows=True,\n",
        "    arrowstyle=\"-|>\",\n",
        "    arrowsize=18,\n",
        ")\n",
        "plt.title(\"Relevance Incident Triage\")\n",
        "plt.axis(\"off\")\n",
        "plt.show()"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## Summary\n",
        "\n",
        "This notebook validated the blog's main argument with runnable examples: stale content detection, metadata completeness checks, auth-aware filtering, evaluation logging, KPI calculation, and ingestion exception reporting. Together they show why enterprise AI search relevance depends on platform capabilities upstream of the chat box.\n",
        "\n",
        "## Next Steps\n",
        "\n",
        "1. Add your own source-system freshness data and compute stale rates by connector.\n",
        "2. Define required metadata fields for your corpus and measure completeness weekly.\n",
        "3. Instrument your retrieval API to log filters, candidate chunks, auth outcomes, and latency.\n",
        "4. Build an offline evaluation set with domain judgments separate from live operational monitoring.\n",
        "5. Decide which capabilities belong to the shared platform versus domain app teams."
      ]
    }
  ]
}