{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Operating a Fabric + Databricks estate \u2014 a runnable runbook\n",
    "\n",
    "**Version 1.0 \u00b7 2026-09-17 \u00b7 Frank Garofalo**\n",
    "\n",
    "This is a runbook, not a checklist. Every cell either explains a decision or\n",
    "runs a check that returns an answer. Edit the parameters cell below and run\n",
    "top to bottom; nothing else should need changing.\n",
    "\n",
    "It is written for the architecture argued in the companion post: Databricks as\n",
    "the engineering engine, Fabric as the BI and governance surface, one governed\n",
    "data layer underneath, and Entra ID as the single identity plane.\n",
    "\n",
    "---\n",
    "\n",
    "### Three things this runbook exists to stop you getting wrong\n",
    "\n",
    "**1. \"Mirroring\" is two different mechanisms.** Databricks mirroring mirrors\n",
    "*catalog metadata* and shortcuts back to the source \u2014 no data is copied.\n",
    "Snowflake and Azure SQL mirroring *replicate a snapshot* into OneLake as Delta\n",
    "tables. They have different failure modes, different storage costs and\n",
    "different staleness behaviour. Reasoning about one using the other's model is\n",
    "the most common architecture error in this pattern.\n",
    "\n",
    "**2. Unity Catalog permissions do not reach Fabric consumers.** Queries against\n",
    "mirrored Databricks data run under the credentials of whoever configured the\n",
    "mirroring connection. Your Unity Catalog row- and column-level policies are not\n",
    "enforced on the Fabric side. This is not \"enforced slightly differently\" \u2014 it\n",
    "is not enforced. You re-implement in OneLake security or you do not have it.\n",
    "\n",
    "**3. OneLake security is GA.** Row- and column-level security in OneLake reached\n",
    "general availability on 2026-05-04. If a document tells you it is in preview,\n",
    "that document is out of date. Two caveats still worth confirming for your own\n",
    "tenant: status for Mirrored Azure Databricks Catalog items specifically, and\n",
    "that GCC High preview still lacks Spark support for OneLake security.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Parameters\n",
    "\n",
    "Everything environment-specific lives here. This cell is tagged `parameters`,\n",
    "so it also works with papermill-style injection if you schedule this notebook.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "tags": [
     "parameters"
    ]
   },
   "outputs": [],
   "source": [
    "# --- Fabric -----------------------------------------------------------\n",
    "FABRIC_WORKSPACE_ID   = \"\"   # GUID of the Fabric workspace holding the mirror\n",
    "FABRIC_LAKEHOUSE_NAME = \"\"   # lakehouse that consumes the mirrored data\n",
    "FABRIC_CAPACITY_ID    = \"\"   # capacity backing the workspace (for the FinOps cell)\n",
    "\n",
    "# --- Databricks -------------------------------------------------------\n",
    "DATABRICKS_WORKSPACE_URL = \"\"   # https://adb-<id>.<n>.azuredatabricks.net\n",
    "DATABRICKS_CATALOG       = \"\"   # Unity Catalog catalog being mirrored\n",
    "DATABRICKS_SCHEMA        = \"\"   # schema scoped for external use (Gold only)\n",
    "\n",
    "# --- Governance -------------------------------------------------------\n",
    "# The service principal that OWNS the mirroring connection. Every Fabric query\n",
    "# against mirrored data runs as THIS identity, so it must be least-privilege.\n",
    "MIRROR_CONNECTION_SPN_OBJECT_ID = \"\"\n",
    "\n",
    "# --- Thresholds the checks below alert on ------------------------------\n",
    "MIRROR_STALENESS_ALERT_MINUTES = 60      # replicated mirrors only; see cell 3\n",
    "CAPACITY_UTILISATION_ALERT_PCT = 80      # sustained, not instantaneous\n",
    "ACCESS_REVIEW_MAX_AGE_DAYS     = 90\n",
    "\n",
    "# --- Owners: who gets paged. Fill these in; an unowned check is decoration.\n",
    "OWNER_PLATFORM   = \"\"   # e.g. \"data-platform@example.com\"\n",
    "OWNER_GOVERNANCE = \"\"\n",
    "OWNER_FINOPS     = \"\"\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Setup\n",
    "\n",
    "Runs inside a Fabric notebook (uses `notebookutils` for the token when present)\n",
    "and degrades to an explicit message elsewhere, so you can read the notebook\n",
    "outside Fabric without it throwing.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import json, datetime\n",
    "\n",
    "FABRIC_API = 'https://api.fabric.microsoft.com/v1'\n",
    "\n",
    "def _token(audience: str = 'pbi') -> str | None:\n",
    "    \"\"\"Fabric-native token when available; None elsewhere.\"\"\"\n",
    "    try:\n",
    "        import notebookutils  # available inside Fabric notebooks\n",
    "        return notebookutils.credentials.getToken(audience)\n",
    "    except Exception:\n",
    "        return None\n",
    "\n",
    "def _get(url: str):\n",
    "    import urllib.request\n",
    "    tok = _token()\n",
    "    if not tok:\n",
    "        print('NOT RUNNING IN FABRIC - no token. Cells that call the API will skip.')\n",
    "        return None\n",
    "    req = urllib.request.Request(url, headers={'Authorization': f'Bearer {tok}'})\n",
    "    with urllib.request.urlopen(req, timeout=60) as r:\n",
    "        return json.loads(r.read().decode('utf-8'))\n",
    "\n",
    "def check(name: str, ok: bool, detail: str = '', owner: str = ''):\n",
    "    \"\"\"One line per check. An unowned check is decoration, so owner prints.\"\"\"\n",
    "    mark = 'PASS' if ok else 'FAIL'\n",
    "    print(f'[{mark}] {name}' + (f' - {detail}' if detail else '')\n",
    "          + (f'  (owner: {owner})' if owner else ''))\n",
    "    return ok\n",
    "\n",
    "print('runbook loaded', datetime.datetime.now(datetime.UTC).isoformat())\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Identity \u2014 who is your mirror actually running as?\n",
    "\n",
    "**The item the prose version of this runbook omitted, and the one that matters\n",
    "most.** Every Fabric query against mirrored Databricks data executes under the\n",
    "credentials that configured the mirroring connection \u2014 not the end user's. If\n",
    "that identity is a human admin or an over-scoped service principal, then every\n",
    "Fabric consumer effectively inherits that access.\n",
    "\n",
    "What good looks like:\n",
    "\n",
    "- a dedicated **service principal**, used for nothing else\n",
    "- granted `EXTERNAL USE SCHEMA` on the specific Gold schema, not the catalog\n",
    "- no workspace-admin, no `ALL PRIVILEGES`, no account-admin\n",
    "- rotated on the same cadence as your other platform credentials\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Run this in Databricks (SQL editor or a Databricks notebook), not in Fabric.\n",
    "# It shows exactly what the mirroring identity can reach.\n",
    "AUDIT_SQL = f'''\n",
    "SHOW GRANTS `{MIRROR_CONNECTION_SPN_OBJECT_ID}` ON SCHEMA {DATABRICKS_CATALOG}.{DATABRICKS_SCHEMA};\n",
    "SHOW GRANTS `{MIRROR_CONNECTION_SPN_OBJECT_ID}` ON CATALOG {DATABRICKS_CATALOG};\n",
    "'''\n",
    "print(AUDIT_SQL)\n",
    "print('Expected: EXTERNAL USE SCHEMA on the schema. Anything at CATALOG scope,')\n",
    "print('or ALL PRIVILEGES anywhere, is over-scoped for a mirroring identity.')\n",
    "check('mirror SPN is configured', bool(MIRROR_CONNECTION_SPN_OBJECT_ID),\n",
    "      'set MIRROR_CONNECTION_SPN_OBJECT_ID', OWNER_GOVERNANCE)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Which mirror do you have? \u2014 answer this before any other check\n",
    "\n",
    "Everything downstream depends on the answer, and the two kinds look similar in\n",
    "the portal.\n",
    "\n",
    "| | Databricks mirroring | Snowflake / Azure SQL mirroring |\n",
    "|---|---|---|\n",
    "| What moves | catalog metadata + shortcuts | an actual data snapshot |\n",
    "| Data copied into OneLake | **No** | **Yes**, as Delta |\n",
    "| Storage cost in OneLake | none for the data | replicated size |\n",
    "| Meaningful staleness clock | no \u2014 reads pass through | **yes** \u2014 replication lag |\n",
    "| \"Resync\" exists | **No** | Yes |\n",
    "\n",
    "If someone hands you a procedure with a resync step for a Databricks mirror,\n",
    "that procedure was written for the other mechanism.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "items = _get(f'{FABRIC_API}/workspaces/{FABRIC_WORKSPACE_ID}/items') if FABRIC_WORKSPACE_ID else None\n",
    "if items:\n",
    "    mirrors = [i for i in items.get('value', []) if 'Mirrored' in (i.get('type') or '')]\n",
    "    for m in mirrors:\n",
    "        kind = m.get('type')\n",
    "        replicated = 'Databricks' not in kind\n",
    "        print(f\"{m.get('displayName')}: {kind}\")\n",
    "        print('   mechanism :', 'REPLICATION (data copied)' if replicated\n",
    "              else 'METADATA + SHORTCUT (no copy, no resync)')\n",
    "        print('   staleness :', f'alert at {MIRROR_STALENESS_ALERT_MINUTES} min'\n",
    "              if replicated else 'not applicable - reads pass through to source')\n",
    "    check('at least one mirrored item found', bool(mirrors), owner=OWNER_PLATFORM)\n",
    "else:\n",
    "    print('Skipped - set FABRIC_WORKSPACE_ID and run inside Fabric.')\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. Security \u2014 re-implement, do not test propagation\n",
    "\n",
    "Unity Catalog policies are **not** enforced for Fabric consumers of mirrored\n",
    "data. There is no propagation to test. The action is to re-implement the\n",
    "equivalent controls in OneLake security, which is GA as of 2026-05-04.\n",
    "\n",
    "Confirm for your own tenant before relying on it:\n",
    "\n",
    "- status for **Mirrored Azure Databricks Catalog** items specifically\n",
    "- in **GCC High**, preview still lacks **Spark** support for OneLake security\n",
    "\n",
    "The check below lists OneLake security roles on the lakehouse so you can compare\n",
    "them against the Unity Catalog policies they are standing in for. If the list is\n",
    "empty and your source had row- or column-level rules, you have a gap, not a\n",
    "difference.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "if FABRIC_WORKSPACE_ID and FABRIC_LAKEHOUSE_NAME:\n",
    "    print('Compare these against the Unity Catalog RLS/CLS rules on')\n",
    "    print(f'  {DATABRICKS_CATALOG}.{DATABRICKS_SCHEMA}')\n",
    "    print('Any UC rule without an equivalent here is UNENFORCED for Fabric users.')\n",
    "    print()\n",
    "    print('OneLake security roles are managed per-item in the Fabric portal')\n",
    "    print('(Lakehouse > Manage OneLake data access). Record the comparison in')\n",
    "    print('your access review; an empty role list with a non-empty UC policy set')\n",
    "    print('is a finding, not a configuration choice.')\n",
    "else:\n",
    "    print('Skipped - set FABRIC_WORKSPACE_ID and FABRIC_LAKEHOUSE_NAME.')\n",
    "check('governance owner assigned', bool(OWNER_GOVERNANCE),\n",
    "      'nobody is paged for a security gap', OWNER_GOVERNANCE)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Cost \u2014 measure the two curves separately, bill them together\n",
    "\n",
    "Fabric bills capacity units with smoothing and background contention.\n",
    "Databricks bills DBUs. They are different shapes and a single blended number\n",
    "hides which one is moving.\n",
    "\n",
    "One correction to a widely repeated claim: **mirroring compute is free**, and\n",
    "mirrored storage is free up to a capacity-based limit. \"A stale mirror triggers\n",
    "expensive re-sync\" is not a cost model to plan around \u2014 and on the Databricks\n",
    "path there is no resync at all.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "if FABRIC_CAPACITY_ID:\n",
    "    print('Use the Fabric Capacity Metrics app for the authoritative view.')\n",
    "    print(f'Alert threshold configured here: {CAPACITY_UTILISATION_ALERT_PCT}% sustained.')\n",
    "    print('Sustained matters - instantaneous spikes are normal under smoothing and')\n",
    "    print('alerting on them trains people to ignore the alert.')\n",
    "else:\n",
    "    print('Skipped - set FABRIC_CAPACITY_ID.')\n",
    "check('FinOps owner assigned', bool(OWNER_FINOPS), owner=OWNER_FINOPS)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. Access review\n",
    "\n",
    "Run on a cadence, not after an incident. The review has to cover the mirroring\n",
    "identity from section 1 \u2014 it is the account most likely to accumulate scope and\n",
    "least likely to be noticed, because no human logs in as it.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "print(f'Access review cadence: every {ACCESS_REVIEW_MAX_AGE_DAYS} days')\n",
    "print()\n",
    "print('Cover, at minimum:')\n",
    "for item in [\n",
    "    'the mirroring connection identity and its EXTERNAL USE SCHEMA grant',\n",
    "    'OneLake security roles on every lakehouse consuming mirrored data',\n",
    "    'Entra group membership behind Fabric workspace roles',\n",
    "    'any Fabric consumer that reads mirrored data without a OneLake role',\n",
    "]:\n",
    "    print(f'  - {item}')\n",
    "check('platform owner assigned', bool(OWNER_PLATFORM), owner=OWNER_PLATFORM)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6. Incident: a mirror looks wrong\n",
    "\n",
    "Branch on the mechanism from section 2 \u2014 the two paths share almost nothing.\n",
    "\n",
    "**Replicated mirror (Snowflake, Azure SQL)**\n",
    "1. Check replication lag against `MIRROR_STALENESS_ALERT_MINUTES`.\n",
    "2. Check source availability \u2014 a paused or unreachable source stops replication.\n",
    "3. After recovery, confirm the snapshot caught up before trusting downstream reports.\n",
    "4. Re-confirm OneLake security roles still exist on the target item.\n",
    "\n",
    "**Databricks mirror (metadata + shortcut)**\n",
    "1. There is no replication lag and no resync. Reads pass through to the source.\n",
    "2. A failure here is almost always *access*, not staleness \u2014 check the mirroring\n",
    "   identity's grants first (section 1).\n",
    "3. Check the source table still exists and still has `EXTERNAL USE SCHEMA`.\n",
    "4. Do **not** look for a resync job. There isn't one.\n",
    "\n",
    "**Both:** if the incident involved data that should have been filtered, treat it\n",
    "as a security incident, not a data incident \u2014 Unity Catalog was never enforcing\n",
    "on this path.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Sources\n",
    "\n",
    "- OneLake security GA announcement, Microsoft Fabric blog, 2026-05-04 \u2014\n",
    "  <https://community.fabric.microsoft.com/t5/Fabric-Updates-Blog/OneLake-security-Generally-Available/ba-p/5171978>\n",
    "- OneLake table, column, and row-level security \u2014\n",
    "  <https://learn.microsoft.com/en-us/fabric/onelake/security/table-column-row-security>\n",
    "- OneLake data security overview \u2014\n",
    "  <https://learn.microsoft.com/en-us/fabric/onelake/security/get-started-security>\n",
    "- Mirroring from Azure Databricks \u2014\n",
    "  <https://learn.microsoft.com/en-us/fabric/database/mirrored-database/azure-databricks>\n",
    "\n",
    "Verify anything time-sensitive against the source before you plan around it.\n",
    "This notebook is dated at the top for exactly that reason.\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.11"
  },
  "microsoft": {
   "language": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}