{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "# S6 lab notebook — TCO, the move, and the portability scorecard\n\nRebuild the campus media unit's monthly total cost of ownership from usage and public prices, price the archive tier, score the option to leave, and record what the move to a second provider would cost.\n\nThe bundled `data/fact-sheet.json`, `data/prices.json`, `data/scorecard.json` and `data/usage_sample.json` are synthetic teaching data. Prices are list prices checked on the date in `prices.json`; the lab asks you to re-check them before you rely on them.\n\n**You submit:** `tco_results.json`, the five-line TCO table, the Linode/Akamai column, the scored portability scorecard, the archive-trap log, the OpenRouter `/generation` JSON, and the teardown log.\n\n**Starter state:** `ARCHIVE_TIER` starts at `\"block\"`, and the spine assertion in Step 2 fails. That failure is the lab's drill, not a broken notebook. Diagnose the storage line, read the section on the archive trap, change the tier to `\"r2_ia\"`, and re-run.\n\n<details class=\"th\" lang=\"th\">\n<summary>สรุปภาษาไทย</summary>\n\nโน้ตบุ๊กนี้สร้างต้นทุนรวมในการเป็นเจ้าของรายเดือนของหน่วยสื่อจากปริมาณการใช้และราคาสาธารณะ แล้วเพิ่มคอลัมน์ของผู้ให้บริการอิสระ Linode/Akamai ให้คะแนนการพกพาบนห้ามิติ และบันทึกต้นทุนการย้ายออก ข้อมูลทั้งหมดเป็นข้อมูลสังเคราะห์สำหรับการสอน ราคาเป็นราคาหน้าตารางที่ตรวจสอบในวันที่ระบุไว้ในไฟล์ prices.json ค่าเริ่มต้นของ ARCHIVE_TIER คือ block ซึ่งทำให้การตรวจสอบเทียบกับเพดาน 80 ดอลลาร์ล้มเหลว การล้มเหลวนี้คือแบบฝึกหัดของแล็บ ไม่ใช่ข้อผิดพลาดของโน้ตบุ๊ก ให้นักเรียนวินิจฉัยบรรทัดพื้นที่เก็บข้อมูล เปลี่ยนเป็น r2_ia แล้วรันใหม่\n</details>\n\n<details class=\"zh\" lang=\"zh-Hans\"><summary>中文总结</summary>\n\n本 notebook 根据用量和公开价格重建校园媒体单位的每月总拥有成本（TCO），再加上独立提供商 Linode/Akamai 的列，对可移植性在五个维度上打分，并记录迁出的成本。所有数据都是用于教学的合成数据，价格是价格表中在 prices.json 里所记日期核查的标价。ARCHIVE_TIER 的默认值是 block，这使与 80 美元上限的校验失败。这次失败是实验的练习，不是 notebook 的错误。请学生诊断存储那一行，把它改为 r2_ia，然后重新运行。\n\n</details>\n"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": "import json\nimport os\nimport sys\nfrom datetime import date, datetime\nfrom pathlib import Path\n\nSEED = 42\nprint(\"seed\", SEED)\nprint(\"Python\", sys.version.split()[0])\nassert sys.version_info >= (3, 11)\nDEVICE = \"cpu\"\nprint(\"device\", DEVICE, \"(S6 has no accelerator path)\")\n"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## Step 0 — load the data\n\nFour files drive the model. `fact-sheet.json` is the scenario spine: the unit's usage and the rounded $80 teaching bill. `prices.json` is the dated price list. `scorecard.json` is the five weighted portability dimensions. `usage_sample.json` is a synthetic audit for a student who cannot reach the provider APIs; a live audit replaces it with `usage.json` of the same shape.\n\n<details class=\"th\" lang=\"th\">\n<summary>สรุปภาษาไทย</summary>\n\nไฟล์สี่ไฟล์ขับเคลื่อนแบบจำลอง fact-sheet.json คือข้อมูลปริมาณการใช้และบิลการสอน 80 ดอลลาร์ prices.json คือรายการราคาที่ระบุวันที่ scorecard.json คือห้ามิติการพกพาที่ถ่วงน้ำหนัก และ usage_sample.json คือข้อมูลตรวจสอบสังเคราะห์สำหรับนักเรียนที่เข้าถึง API ของผู้ให้บริการไม่ได้ หากตรวจสอบจริงให้ใช้ usage.json ที่มีรูปแบบเดียวกัน\n</details>\n\n<details class=\"zh\" lang=\"zh-Hans\"><summary>中文总结</summary>\n\n四个文件驱动这个模型：fact-sheet.json 是用量数据和 80 美元的教学账单；prices.json 是带日期的价格表；scorecard.json 是五个加权可移植性维度；usage_sample.json 是供无法访问提供商 API 的学生使用的合成审计数据。如果做真实审计，就用同样格式的 usage.json。\n\n</details>\n"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": "def data_dir():\n    candidates = [Path(\"data\"), Path(\"/kaggle/input/economics-vendor-lock\"),\n                  Path(\"../../weeks/06-economics-vendor-lock/data\")]\n    env = os.environ.get(\"COURSE_DATA\")\n    if env:\n        candidates.append(Path(env))\n    required = [\"fact-sheet.json\", \"prices.json\", \"scorecard.json\", \"usage_sample.json\"]\n    for path in candidates:\n        if path and all((path / name).exists() for name in required):\n            return path\n    raise FileNotFoundError(\"put fact-sheet.json, prices.json, scorecard.json and usage_sample.json in data/\")\n\n\nDATA = data_dir()\nfact_sheet = json.loads((DATA / \"fact-sheet.json\").read_text())\nprices = json.loads((DATA / \"prices.json\").read_text())\nscorecard = json.loads((DATA / \"scorecard.json\").read_text())\n\nlive_audit = DATA / \"usage.json\"\nusage_source = \"live\" if live_audit.exists() else \"sample\"\naudit = json.loads((live_audit if live_audit.exists() else DATA / \"usage_sample.json\").read_text())\n\nprint(\"data\", DATA)\nprint(\"usage source\", usage_source)\nprint(\"prices checked\", prices[\"checked\"])\nassert set(prices[\"providers\"]) == {\"our_stack\", \"linode\"}\nassert abs(sum(row[\"weight\"] for row in scorecard[\"dimensions\"]) - 1.0) < 1e-9\nassert usage_source in {\"live\", \"sample\"}\n\nchecked = date.fromisoformat(prices[\"checked\"])\nage_days = (date.today() - checked).days\nprint(\"price age in days\", age_days)\nassert age_days >= 0, \"prices are dated in the future\"\nif age_days > prices[\"freeze_days\"]:\n    print(f\"WARNING: prices are {age_days} days old; the freeze window is \"\n          f\"{prices['freeze_days']} days. Re-check them before relying on the total.\")\n"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## Step 1 — turn the fact sheet into monthly usage\n\nThe egress line is worth deriving rather than quoting: 300 views a day of a 15 MB video is 4.5 GB a day, about 135 GB a month. Thumbnails are small individually and large in total: 5,000 a day at 50 KB is about 7.5 GB a month, carried by the CDN request line rather than the video egress line.\n\n<details class=\"th\" lang=\"th\">\n<summary>สรุปภาษาไทย</summary>\n\nบรรทัดอีเกรสคำนวณได้จาก 300 ครั้งต่อวัน คูณวิดีโอ 15 เมกะไบต์ คูณ 30 วัน ประมาณ 135 จิกะไบต์ต่อเดือน ส่วนภาพตัวอย่าง 5,000 ภาพต่อวัน ขนาด 50 กิโลไบต์ รวมประมาณ 7.5 จิกะไบต์ต่อเดือน ซึ่งอยู่ในบรรทัดคำขอ CDN ไม่ใช่บรรทัดอีเกรสวิดีโอ\n</details>\n\n<details class=\"zh\" lang=\"zh-Hans\"><summary>中文总结</summary>\n\n出站流量那一行可以算出来：每天 300 次观看 × 15 MB 的视频 × 30 天，约为每月 135 GB。缩略图每天 5,000 张、每张 50 KB，合计约为每月 7.5 GB，它落在 CDN 请求那一行，而不是视频出站流量那一行。\n\n</details>\n"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": "egress_gb = fact_sheet[\"video_views_per_day\"] * fact_sheet[\"video_mb\"] * 30 / 1000\nthumbnail_gb = fact_sheet[\"thumbnail_requests_per_day\"] * fact_sheet[\"thumbnail_kb\"] * 30 / 1_000_000\nthumbnail_requests = fact_sheet[\"thumbnail_requests_per_day\"] * 30\n\nprint(\"video egress GB/month\", egress_gb)\nprint(\"thumbnail GB/month\", thumbnail_gb)\nprint(\"thumbnail requests/month\", thumbnail_requests)\nassert abs(egress_gb - fact_sheet[\"egress_gb\"]) < 0.5\nassert abs(thumbnail_gb - (thumbnail_requests * fact_sheet[\"thumbnail_kb\"] / 1_000_000)) < 1e-9\n\nusage = {\n    \"storage_gb\": fact_sheet[\"storage_gb\"],\n    \"archive_gb\": fact_sheet[\"archive_gb\"],\n    \"asset_library_gb\": fact_sheet[\"asset_library_gb\"],\n    \"snapshot_gb\": fact_sheet[\"snapshot_gb\"],\n    \"egress_gb\": round(egress_gb, 1),\n    \"prompt_tokens\": fact_sheet[\"inference_prompt_tokens\"],\n    \"completion_tokens\": fact_sheet[\"inference_completion_tokens\"],\n    \"thumbnail_requests\": thumbnail_requests,\n    \"thumbnail_gb\": round(thumbnail_gb, 1),\n}\nprint(usage)\nassert usage[\"storage_gb\"] == usage[\"archive_gb\"] + usage[\"asset_library_gb\"]\nassert usage[\"prompt_tokens\"] + usage[\"completion_tokens\"] == fact_sheet[\"inference_tokens_per_month\"]\n"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## Step 2 — the five-line bill for our stack\n\nEach line is usage × unit price. The five lines are storage, compute and CDN, egress, inference, and buffer. The buffer is a percentage of the other four, kept separate so you can see it.\n\nStorage has three parts on this stack: the 200 GB asset library on a DigitalOcean Volume, about 300 GB of snapshots, and the 1 TB archive in an object tier. `ARCHIVE_TIER` chooses that tier:\n\n| `ARCHIVE_TIER` | Rate | Where the archive lives |\n|---|---:|---|\n| `\"block\"` | $0.10/GB-month | A block Volume — the starter default |\n| `\"r2_ia\"` | $0.01/GB-month | R2 Infrequent Access |\n| `\"r2_standard\"` | $0.015/GB-month | R2 Standard |\n\n**Run this cell as shipped. It is meant to fail.** The `block` tier puts the 1 TB archive on the most expensive storage in the model, the total blows past the $80 spine, and the assertion at the end stops the notebook. Read the failure, then do Step 3.\n\n<details class=\"th\" lang=\"th\">\n<summary>สรุปภาษาไทย</summary>\n\nแต่ละบรรทัดคือปริมาณการใช้คูณราคาต่อหน่วย ห้าบรรทัดคือพื้นที่เก็บข้อมูล คอมพิวเตอร์และ CDN อีเกรส การอนุมาน และเงินสำรอง เงินสำรองคิดเป็นเปอร์เซ็นต์ของสี่บรรทัดแรกและแสดงแยกไว้ พื้นที่เก็บข้อมูลมีสามส่วนบนสแตกนี้ คือคลังสินทรัพย์ 200 จิกะไบต์บนวอลุ่ม ภาพสแนปช็อตประมาณ 300 จิกะไบต์ และคลังวิดีโอ 1 เทระไบต์ในชั้นวัตถุ ค่าเริ่มต้น block ทำให้คลังวิดีโออยู่บนที่เก็บที่แพงที่สุดในแบบจำลอง ยอดรวมจึงเกินเพดาน 80 ดอลลาร์ และการตรวจสอบจะหยุดโน้ตบุ๊ก นี่คือแบบฝึกหัด\n</details>\n\n<details class=\"zh\" lang=\"zh-Hans\"><summary>中文总结</summary>\n\n每一行都是用量 × 单价。五行分别是存储、计算与 CDN、出站流量、推理和缓冲。缓冲是前四行的百分比，单独列出。存储在这套栈上分三部分：Volume 上 200 GB 的素材库、约 300 GB 的快照，以及对象层中 1 TB 的视频归档。默认的 block 使视频归档位于模型中最贵的存储上，总额因此超过 80 美元的上限，校验会让 notebook 停下。这就是练习。\n\n</details>\n"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": "ARCHIVE_TIER = \"block\"  # starter default: run it, read the failure, then change to \"r2_ia\"\nSPINE = fact_sheet[\"monthly_bill_teaching_figure\"]\nTIER_RATE_KEYS = {\"block\": \"volume_gb\", \"r2_ia\": \"object_ia_gb\", \"r2_standard\": \"object_standard_gb\"}\n\n\ndef tco_our_stack(usage, archive_tier):\n    p = prices[\"providers\"][\"our_stack\"]\n    assert archive_tier in TIER_RATE_KEYS, archive_tier\n    archive_rate = p[TIER_RATE_KEYS[archive_tier]]\n    storage = (usage[\"asset_library_gb\"] * p[\"volume_gb\"]\n               + usage[\"snapshot_gb\"] * p[\"snapshot_gb\"]\n               + usage[\"archive_gb\"] * archive_rate)\n    compute_cdn = p[\"droplet_month\"] + p[\"worker_month\"]\n    egress = usage[\"egress_gb\"] * p[\"egress_gb\"]\n    inference_raw = (usage[\"prompt_tokens\"] / 1_000_000 * p[\"inference_prompt_per_m\"]\n                     + usage[\"completion_tokens\"] / 1_000_000 * p[\"inference_completion_per_m\"])\n    inference = inference_raw * (1 + p[\"credit_fee_pct\"])\n    lines = {\n        \"storage\": round(storage, 2),\n        \"compute_cdn\": round(compute_cdn, 2),\n        \"egress\": round(egress, 2),\n        \"inference\": round(inference, 2),\n    }\n    subtotal = round(sum(lines.values()), 2)\n    buffer = round(subtotal * p[\"buffer_pct\"], 2)\n    lines[\"buffer\"] = buffer\n    total = round(subtotal + buffer, 2)\n    assert all(value >= 0 for value in lines.values())\n    assert abs(sum(lines.values()) - total) < 0.011\n    return {\"label\": p[\"label\"], \"region\": p[\"region\"], \"archive_tier\": archive_tier,\n            \"archive_rate\": archive_rate, \"lines\": lines, \"subtotal\": subtotal,\n            \"buffer\": buffer, \"total\": total}\n\n\nours = tco_our_stack(usage, ARCHIVE_TIER)\ndeltas = {key: round(ours[\"lines\"][key] - fact_sheet[\"spine_lines\"][key], 2)\n          for key in ours[\"lines\"]}\nspine_delta = round(ours[\"total\"] - SPINE, 2)\n\nprint(\"tier\", ARCHIVE_TIER, \"archive rate $/GB-month\", ours[\"archive_rate\"])\nfor key, value in ours[\"lines\"].items():\n    print(f\"{key:12s} ${value:8.2f}   spine ${fact_sheet['spine_lines'][key]:6.2f}   delta ${deltas[key]:+.2f}\")\nprint(\"subtotal\", ours[\"subtotal\"], \"total\", ours[\"total\"], \"spine\", SPINE, \"delta\", spine_delta)\n\nassert abs(sum(deltas.values()) - spine_delta) < 0.02, \"the line deltas must sum to the spine delta\"\nassert ours[\"total\"] <= SPINE * 1.15, (\n    f\"total ${ours['total']:.2f} exceeds the ${SPINE} spine by more than 15%.\\n\"\n    \"The storage line is the outlier. Which tier is the 1 TB archive on?\\n\"\n    \"Set ARCHIVE_TIER to 'r2_ia' and re-run from the top.\")\nprint(\"inside the spine tolerance\")\n"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "### Step 3 — the archive trap\n\nThe failure above is the session's model in miniature. **The bytes were never the expensive part; the tier was.**\n\nAt `$0.10/GB-month`, 1 TB of archive is about **$100 a month on its own** — more than the whole $80 spine. At `$0.01/GB-month` on R2 Infrequent Access the same bytes cost about **$10**. Nothing else changes: same files, same catalogue, same audience. Only the tier the bytes sit in.\n\nChange `ARCHIVE_TIER` in the cell above from `\"block\"` to `\"r2_ia\"` and re-run the cell. The assertion passes, and the total lands near the spine. Then run the comparison below to see all three tiers side by side.\n\n<details class=\"th\" lang=\"th\">\n<summary>สรุปภาษาไทย</summary>\n\nการล้มเหลวข้างต้นคือแบบจำลองของคาบเรียนนี้ในขนาดย่อ ข้อมูลไม่เคยเป็นส่วนที่แพง ส่วนที่แพงคือชั้นเก็บข้อมูล ที่ราคา 0.10 ดอลลาร์ต่อจิกะไบต์ต่อเดือน คลัง 1 เทระไบต์มีค่าใช้จ่ายประมาณ 100 ดอลลาร์ต่อเดือน ซึ่งมากกว่าเพดานทั้งก้อน 80 ดอลลาร์ ที่ราคา 0.01 ดอลลาร์บน R2 Infrequent Access ข้อมูลชุดเดียวกันมีค่าประมาณ 10 ดอลลาร์ ไม่มีอย่างอื่นเปลี่ยน เปลี่ยนค่า ARCHIVE_TIER จาก block เป็น r2_ia แล้วรันใหม่\n</details>\n\n<details class=\"zh\" lang=\"zh-Hans\"><summary>中文总结</summary>\n\n上面这次失败就是本节课模型的缩影。数据从来不是昂贵的那部分，昂贵的是存储层级。按 0.10 美元/GB-month 计算，1 TB 的归档每月就约 100 美元，比整个 80 美元的上限还多。在 R2 Infrequent Access 上按 0.01 美元/GB-month，同样的数据约 10 美元。其他什么都没变：同样的文件、同样的目录、同样的受众，只是数据所在的层级不同。把上面单元格里的 ARCHIVE_TIER 从 block 改为 r2_ia 并重新运行。\n\n</details>\n"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": "tier_table = {tier: tco_our_stack(usage, tier) for tier in TIER_RATE_KEYS}\nfor tier, result in tier_table.items():\n    print(f\"{tier:12s} archive ${result['lines']['storage']:7.2f} storage, \"\n          f\"total ${result['total']:7.2f}, spine delta ${result['total'] - SPINE:+.2f}\")\nassert tier_table[\"block\"][\"total\"] > tier_table[\"r2_ia\"][\"total\"]\nassert tier_table[\"r2_standard\"][\"total\"] > tier_table[\"r2_ia\"][\"total\"]\n"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## Step 4 — how sensitive is the bill to snapshots?\n\nA snapshot is another tier decision. The model keeps about 300 GB of snapshots at $0.06/GB-month on DigitalOcean. Move the slider: what does each extra 150 GB cost per month, and per year? The point is not the exact answer; it is that a line you never chose still moves the total.\n\n<details class=\"th\" lang=\"th\">\n<summary>สรุปภาษาไทย</summary>\n\nสแนปช็อตก็เป็นการตัดสินใจเรื่องชั้นเก็บข้อมูลอีกอย่าง แบบจำลองเก็บสแนปช็อตประมาณ 300 จิกะไบต์ที่ 0.06 ดอลลาร์ต่อจิกะไบต์ต่อเดือนบน DigitalOcean ลองเปลี่ยนปริมาณทีละ 150 จิกะไบต์ ดูว่าต้นทุนเพิ่มเท่าไรต่อเดือนและต่อปี ประเด็นไม่ใช่ตัวเลขที่แน่นอน แต่คือบรรทัดที่คุณไม่ได้เลือกเองก็ทำให้ยอดรวมเปลี่ยนได้\n</details>\n\n<details class=\"zh\" lang=\"zh-Hans\"><summary>中文总结</summary>\n\n快照也是另一种存储层级决策。模型在 DigitalOcean 上以 0.06 美元/GB-month 保存约 300 GB 的快照。试着每次改变 150 GB 的量，看看每月和每年增加多少成本。重点不是确切的数字，而是一行你并没有自己选择的成本也能让总额变化。\n\n</details>\n"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": "snapshot_sensitivity = {}\nfor snapshot_gb in (0, 150, 300, 450, 600):\n    variant = dict(usage, snapshot_gb=snapshot_gb)\n    result = tco_our_stack(variant, \"r2_ia\")\n    snapshot_sensitivity[snapshot_gb] = result[\"total\"]\n    print(f\"snapshots {snapshot_gb:4d} GB -> storage ${result['lines']['storage']:7.2f}, \"\n          f\"total ${result['total']:7.2f}\")\n\ntotals = list(snapshot_sensitivity.values())\nassert totals == sorted(totals)\nmonth_per_150 = round(snapshot_sensitivity[450] - snapshot_sensitivity[300], 2)\nprint(\"each extra 150 GB of snapshots costs about\", month_per_150, \"per month,\", round(month_per_150 * 12, 2), \"per year\")\n"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## Step 5 — the Linode/Akamai column\n\nThe comparison is a real second provider, not a hyperscaler. Price the same usage on Linode/Akamai with the same five lines. Three differences matter:\n\n- **Storage** is 200 GB block + 300 GB images at $0.10, plus $5/month of Object Storage covering 250 GB with excess at $0.02/GB.\n- **Inference** has **no priced managed equivalent** in this comparison, so one notional RTX PRO 6000 hour at $3.00 stands in for the model line.\n- **Egress** is inside the included transfer, so 135 GB costs $0 — the same teaching outcome as our stack, for a different reason.\n\n<details class=\"th\" lang=\"th\">\n<summary>สรุปภาษาไทย</summary>\n\nการเปรียบเทียบใช้ผู้ให้บริการอิสระจริง ไม่ใช่ผู้ให้บริการรายใหญ่ ราคาการใช้งานเดียวกันบน Linode/Akamai ด้วยห้าบรรทัดเดียวกัน ความต่างสามข้อสำคัญคือ พื้นที่เก็บข้อมูลเป็นบล็อก 200 จิกะไบต์และอิมเมจ 300 จิกะไบต์ที่ 0.10 ดอลลาร์ บวกบริการวัตถุ 5 ดอลลาร์ต่อเดือนที่ครอบคลุม 250 จิกะไบต์ ส่วนการอนุมานไม่มีบริการจัดการที่เทียบได้ในราคาที่ประกาศ จึงใช้ชั่วโมง RTX PRO 6000 สมมติที่ 3 ดอลลาร์แทน และอีเกรสอยู่ในโควตาที่รวมมาแล้ว\n</details>\n\n<details class=\"zh\" lang=\"zh-Hans\"><summary>中文总结</summary>\n\n这次比较使用真正的独立提供商，而不是大型云厂商。在 Linode/Akamai 上用同样的五行给同样的用量定价。三处差异很重要：存储是 200 GB 的块存储加 300 GB 的镜像，按 0.10 美元计，再加上每月 5 美元的对象存储服务，覆盖 250 GB；推理在这个比较中没有价格已公布的可比托管服务，因此用一小时名义上的 RTX PRO 6000、3 美元来代替模型那一行；出站流量包含在已计入的流量额度内。\n\n</details>\n"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": "def tco_linode(usage):\n    p = prices[\"providers\"][\"linode\"]\n    object_cost = p[\"object_base_month\"] + max(\n        0, usage[\"archive_gb\"] - p[\"object_included_gb\"]) * p[\"object_excess_gb\"]\n    storage = (usage[\"asset_library_gb\"] * p[\"volume_gb\"]\n               + usage[\"snapshot_gb\"] * p[\"image_gb\"]\n               + object_cost)\n    compute_cdn = p[\"instance_month\"]\n    egress = max(0, usage[\"egress_gb\"] - 1024) * p[\"egress_gb\"]\n    inference = 1 * p[\"gpu_hour\"]\n    lines = {\n        \"storage\": round(storage, 2),\n        \"compute_cdn\": round(compute_cdn, 2),\n        \"egress\": round(egress, 2),\n        \"inference\": round(inference, 2),\n    }\n    subtotal = round(sum(lines.values()), 2)\n    buffer = round(subtotal * p[\"buffer_pct\"], 2)\n    lines[\"buffer\"] = buffer\n    total = round(subtotal + buffer, 2)\n    assert abs(sum(lines.values()) - total) < 0.011\n    return {\"label\": p[\"label\"], \"region\": p[\"region\"], \"lines\": lines,\n            \"subtotal\": subtotal, \"buffer\": buffer, \"total\": total}\n\n\nlinode = tco_linode(usage)\nfor key in linode[\"lines\"]:\n    print(f\"{key:12s} ours ${ours['lines'][key]:8.2f}   linode ${linode['lines'][key]:8.2f}\")\nprint(\"ours\", ours[\"total\"], \"linode\", linode[\"total\"], \"difference\", round(linode[\"total\"] - ours[\"total\"], 2))\nassert abs(sum(linode[\"lines\"].values()) - linode[\"total\"]) < 0.011\n"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## Step 6 — score the option to leave\n\nThe five dimensions are weighted and scored from 1 (locked in) to 5 (easy to leave). The weighted score becomes a number out of 100; the unit's threshold is 60. The default scores describe the move from this stack to Linode/Akamai and give **exactly 60** — the teaching point is that the stack is borderline, and the argument about the weights is where the useful disagreement lives.\n\nEdit the scores and the rationale in `data/scorecard.json` from your own move evidence, then re-run this cell.\n\n<details class=\"th\" lang=\"th\">\n<summary>สรุปภาษาไทย</summary>\n\nมิติทั้งห้าถ่วงน้ำหนักและให้คะแนน 1 ถึง 5 โดย 1 คือถูกล็อก และ 5 คือย้ายออกง่าย คะแนนถ่วงน้ำหนักแปลงเป็นคะแนนเต็ม 100 เกณฑ์ของหน่วยคือ 60 ค่าเริ่มต้นอธิบายการย้ายจากสแตกนี้ไป Linode/Akamai และให้คะแนนพอดี 60 ประเด็นการสอนคือสแตกนี้อยู่ที่เส้นแบ่งพอดี และการโต้แย้งเรื่องน้ำหนักคือจุดที่ความคิดเห็นต่างมีประโยชน์ แก้คะแนนและเหตุผลใน scorecard.json จากหลักฐานการย้ายของคุณเอง\n</details>\n\n<details class=\"zh\" lang=\"zh-Hans\"><summary>中文总结</summary>\n\n五个维度都加权，并按 1 到 5 打分，其中 1 表示被锁定，5 表示容易迁出。加权分数会换算成满分 100 的分数，该单位的标准是 60。默认分数描述的是从这套栈迁移到 Linode/Akamai，得分正好 60。教学重点在于这套栈正好处在分界线上，而关于权重的争论正是不同意见有价值的地方。请根据你自己的迁移证据，修改 scorecard.json 中的分数和理由。\n\n</details>\n"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": "weights = {row[\"key\"]: row[\"weight\"] for row in scorecard[\"dimensions\"]}\nscores = {row[\"key\"]: row[\"score\"] for row in scorecard[\"dimensions\"]}\n\nassert abs(sum(weights.values()) - 1.0) < 1e-9\nassert all(1 <= score <= 5 for score in scores.values())\n\nweighted = sum(scores[key] * weights[key] for key in scores)\nscore_100 = round(weighted / 5 * 100, 1)\nthreshold = scorecard[\"threshold\"]\nband = (\"low lock-in\" if score_100 >= 80\n        else \"moderate lock-in\" if score_100 >= threshold\n        else \"high lock-in\")\n\nfor row in scorecard[\"dimensions\"]:\n    print(f\"{row['label']:28s} score {row['score']} weight {row['weight']:.2f}  {row['rationale'][:60]}\")\nprint(\"weighted score out of 5\", round(weighted, 2))\nprint(\"score out of 100\", score_100, \"threshold\", threshold, \"band\", band)\nfor layer, layer_score in scorecard[\"layers\"].items():\n    print(f\"  layer {layer:9s} {layer_score}\")\nassert 0 <= score_100 <= 100\nassert score_100 == round(weighted / 5 * 100, 1)\n"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## Step 7 — what would leaving cost?\n\nAn exit cost has three parts: the bytes, the re-platforming days, and the option value of the time. On this stack the **bytes are free** — R2 egress is free — so the days dominate. Six re-platforming days at $250/day is the teaching estimate for the Worker→container, OpenRouter→self-host and identity remaps.\n\nThe transfer time below uses a **teaching rate of 100 MB/s**. Replace it with your own measurement: the verified course run moved 1 GB in 77.8 s on a home uplink, about 13 MB/s, which puts 1 TB at roughly 22 hours. The bytes cost nothing here; the *time* is the cost the current stack avoids, and the egress-price dimension scores 5 because of it.\n\nThe sensitivity line is the lesson: if the archive sat behind a priced egress, the same bytes would have a number attached. That is the cost the current stack avoids, and the reason the egress-price dimension scores 5.\n\n<details class=\"th\" lang=\"th\">\n<summary>สรุปภาษาไทย</summary>\n\nต้นทุนการย้ายออกมีสามส่วน คือค่าข้อมูล ค่าวันย้ายระบบ และมูลค่าของทางเลือก บนสแตกนี้ค่าข้อมูลเป็นศูนย์เพราะอีเกรสของ R2 ฟรี ดังนั้นส่วนที่แพงคือจำนวนวัน หกวันในอัตรา 250 ดอลลาร์ต่อวันเป็นค่าประมาณการสอนสำหรับการย้าย Worker ไปคอนเทนเนอร์ การย้าย OpenRouter ไปโฮสต์เอง และการแมปIdentity สามระบบ บรรทัดความอ่อนไหวคือบทเรียน: ถ้าคลังข้อมูลอยู่หลังอีเกรสที่คิดราคา ข้อมูลชุดเดียวกันจะมีตัวเลขต้นทุน\n</details>\n\n<details class=\"zh\" lang=\"zh-Hans\"><summary>中文总结</summary>\n\n迁出成本有三个部分：数据、迁移系统的天数，以及时间的期权价值。在这套栈上数据成本为零，因为 R2 的出站流量免费，所以昂贵的是天数。按每天 250 美元计算的六天，是 Worker 迁移到容器、OpenRouter 迁移到自托管，以及三套身份映射的教学估算。敏感性那一行就是本课的教训：如果归档位于计费的出站流量之后，同样的数据就会带上一个成本数字。\n\n</details>\n"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": "bytes_exit = round(usage[\"archive_gb\"] * prices[\"providers\"][\"our_stack\"][\"egress_gb\"], 2)\npriced_egress_sensitivity = round(\n    usage[\"archive_gb\"] * prices[\"providers\"][\"linode\"][\"egress_gb\"], 2)\nre_platform_days = 6\nday_rate = 250.0\nre_platform = round(re_platform_days * day_rate, 2)\ntransfer_hours = round(usage[\"archive_gb\"] * 1024 / (100 * 3600), 1)  # 100 MB/s\nexit_cost = round(bytes_exit + re_platform, 2)\n\nprint(\"bytes to leave, our stack $\", bytes_exit)\nprint(\"same bytes behind $0.005/GB egress $\", priced_egress_sensitivity)\nprint(\"transfer time at 100 MB/s\", transfer_hours, \"hours\")\nprint(\"re-platforming\", re_platform_days, \"days at\", day_rate, \"=\", re_platform)\nprint(\"exit cost, our stack $\", exit_cost)\nassert exit_cost > bytes_exit\nassert re_platform > bytes_exit\n"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## Step 8 — write the artifact\n\n`tco_results.json` is the machine-readable record of everything above. It names whether the run used a live audit or the synthetic sample, the price date, the tier you chose, the spine delta decomposed by line, the sensitivity tables, the weighted score and the exit cost.\n\n<details class=\"th\" lang=\"th\">\n<summary>สรุปภาษาไทย</summary>\n\ntco_results.json คือบันทึกที่เครื่องอ่านได้ของทุกอย่างข้างต้น ระบุว่ารันด้วยข้อมูลตรวจสอบจริงหรือข้อมูลตัวอย่างสังเคราะห์ วันที่ของราคา ชั้นเก็บข้อมูลที่เลือก ส่วนต่างจากเพดานแยกตามบรรทัด ตารางความอ่อนไหว คะแนนถ่วงน้ำหนัก และต้นทุนการย้ายออก\n</details>\n\n<details class=\"zh\" lang=\"zh-Hans\"><summary>中文总结</summary>\n\ntco_results.json 是上述所有内容的机器可读记录。它说明这次运行用的是真实审计数据还是合成样本数据、价格的日期、你选择的存储层级、按行拆分的与上限的差额、敏感性表格、加权分数以及迁出成本。\n\n</details>\n"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": "results = {\n    \"seed\": SEED,\n    \"device\": DEVICE,\n    \"usage_source\": usage_source,\n    \"prices_checked\": prices[\"checked\"],\n    \"price_age_days\": age_days,\n    \"archive_tier_used\": ARCHIVE_TIER,\n    \"usage\": usage,\n    \"audit\": audit,\n    \"spine\": {\"bill\": SPINE, \"lines\": fact_sheet[\"spine_lines\"], \"delta\": spine_delta,\n              \"line_deltas\": deltas, \"tolerance_pct\": 15},\n    \"tco_ours\": ours,\n    \"tiers\": {tier: {\"total\": result[\"total\"], \"storage\": result[\"lines\"][\"storage\"]}\n              for tier, result in tier_table.items()},\n    \"snapshot_sensitivity\": snapshot_sensitivity,\n    \"tco_linode\": linode,\n    \"lock_in\": {\n        \"dimensions\": scores,\n        \"weights\": weights,\n        \"weighted_5\": round(weighted, 2),\n        \"score_100\": score_100,\n        \"threshold\": threshold,\n        \"band\": band,\n        \"layers\": scorecard[\"layers\"],\n    },\n    \"exit_cost\": {\n        \"bytes\": bytes_exit,\n        \"priced_egress_sensitivity\": priced_egress_sensitivity,\n        \"transfer_hours_at_100_mb_s\": transfer_hours,\n        \"re_platform_days\": re_platform_days,\n        \"day_rate\": day_rate,\n        \"re_platform\": re_platform,\n        \"total\": exit_cost,\n    },\n    \"generated\": datetime.now().isoformat(timespec=\"seconds\"),\n}\nPath(\"tco_results.json\").write_text(json.dumps(results, indent=2))\nprint(json.dumps({k: results[k] for k in (\"usage_source\", \"archive_tier_used\", \"spine\", \"lock_in\", \"exit_cost\")}, indent=2))\n"
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": "## What this proves\n\nWrite 150–250 words: which line dominates the bill now, how the five lines moved away from the rounded spine, what the archive tier saves, which scorecard dimension created the most lock-in, what the exit would cost in bytes and days, and what the unit should do this quarter. Attach `tco_results.json`, the five-line table, the scorecard, the archive-trap log, the OpenRouter `/generation` JSON and the teardown log.\n\n## Verification\n\n**Mac (Apple Silicon, Python 3.14):** the notebook runs end to end with the bundled data and writes `tco_results.json`. The shipped `ARCHIVE_TIER = \"block\"` fails the spine assertion by design; the recorded verification run uses `\"r2_ia\"`. S6 has no accelerator path. Prices are dated list prices: the notebook warns when they leave the freeze window rather than failing.\n\n<details class=\"th\" lang=\"th\">\n<summary>สรุปภาษาไทย</summary>\n\nเขียนสรุป 150–250 คำ ว่าบรรทัดใดครองบิลตอนนี้ ห้าบรรทัดเคลื่อนจากเพดานที่ปัดเศษอย่างไร ชั้นเก็บข้อมูลประหยัดเท่าไร มิติใดสร้างการล็อกมากที่สุด การย้ายออกมีต้นทุนเป็นข้อมูลและจำนวนวันเท่าไร และหน่วยควรทำอะไรในไตรมาสนี้ แนบไฟล์ tco_results.json ตารางห้าบรรทัด คะแนน บันทึกกับดักคลังข้อมูล JSON ของ /generation และบันทึกการรื้อถอน\n</details>\n\n<details class=\"zh\" lang=\"zh-Hans\"><summary>中文总结</summary>\n\n写 150–250 词：现在哪一行主导账单，五行相对取整后的上限如何移动，存储层级节省了多少，哪个维度造成的锁定最多，迁出在数据和天数上要花多少成本，以及该单位本季度应该做什么。附上 tco_results.json、五行表格、评分、归档陷阱记录、/generation 的 JSON 以及拆除记录。\n\n</details>\n"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3.14"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
