[{"data":1,"prerenderedAt":17511},["ShallowReactive",2],{"\u002Fwriting":3,"articles-en":36},{"id":4,"title":5,"body":6,"date":27,"description":23,"extension":28,"head":27,"meta":29,"navigation":30,"ogImage":27,"path":31,"robots":27,"schemaOrg":27,"seo":32,"sitemap":33,"stem":34,"__hash__":35},"content_en\u002F3.writing.md","Writing",{"type":7,"value":8,"toc":24},"minimark",[9],[10,11,12,19],"writing",{},[13,14,16],"template",{"v-slot:title":15},"",[17,18,5],"p",{},[13,20,21],{"v-slot:subtitle":15},[17,22,23],{},"Some writings on technology and thinking",{"title":15,"searchDepth":25,"depth":25,"links":26},2,[],null,"md",{},true,"\u002Fwriting",{"title":5,"description":23},{"loc":31},"3.writing","3CjXjf1YuY8s0rby0R5ijCH3d5_7PLbLVx5c7P7BQZg",[37,1069,1971,3051,5022,7014,7883,8421,9627,12648,13580,15076,15807],{"id":38,"title":39,"body":40,"date":1056,"description":1057,"extension":28,"head":27,"image":1058,"meta":1059,"navigation":30,"ogImage":27,"path":1060,"rating":225,"readingTime":1061,"robots":27,"schemaOrg":27,"seo":1062,"sitemap":1063,"stem":1064,"tags":1065,"__hash__":1068},"articles_en\u002Farticles\u002Fagent-hitl-two-phase-commit.md","Why an AI Agent's \"Commit\" Decision Can't Be Left to the LLM — Production-Grade HITL with Two-Phase Interception and Four Lines of Defense",{"type":7,"value":41,"toc":1045},[42,57,62,65,68,79,85,89,104,177,187,190,289,294,304,308,311,333,336,340,347,365,372,382,419,423,429,436,442,487,492,553,560,566,569,572,654,658,664,670,676,685,691,698,718,721,801,805,812,822,852,872,879,883,998,1005,1009,1035,1041],[43,44,45],"note",{},[17,46,47,48,52,53,56],{},"The thesis in one sentence: ",[49,50,51],"strong",{},"in an agent whose actions have irreversible consequences, the decision of \"should this actually be executed\" cannot be left to the LLM."," Using a production marketing agent (an assistant for a \"referral reward campaign\") as the example, this post explains why you need a \"confirmation intercept\" outside the LLM, how the two-phase commit is implemented, and the ",[49,54,55],{},"four lines of defense that are really running"," behind it. To avoid leaking implementation details, I use role-based names in place of real module names, and the code is reduced to a few pieces of pseudocode that carry the point.",[58,59,61],"h2",{"id":60},"_1-start-with-a-bug","1. Start with a bug",[17,63,64],{},"A merchant has chatted with the bot for a few turns on an IM channel and has pulled up a preview of a \"referral reward campaign\". The bot asks: \"Would you like to adjust the tier-two reward a bit more?\" The merchant replies: \"OK.\"",[17,66,67],{},"What does that \"OK\" mean? Is it \"OK, I want to change tier two\", or \"OK, go ahead and submit it as is\"?",[17,69,70,71,74,75,78],{},"If you hand this judgment to the LLM, there is a decent chance it guesses wrong. And the cost of guessing wrong is ",[49,72,73],{},"asymmetric",": guess \"change\" and the worst case is one extra question; guess \"submit\" and you have just ",[49,76,77],{},"pushed a campaign the merchant hadn't finished thinking through straight to production"," — an irreversible write.",[17,80,81,82],{},"That is the core question of this post: ",[49,83,84],{},"in human-AI collaboration (HITL, Human-in-the-Loop), should the \"commit\" decision be left to the LLM at all?",[58,86,88],{"id":87},"_2-background-what-kind-of-agent-is-this","2. Background: what kind of agent is this",[17,90,91,92,95,96,103],{},"It is a marketing assistant running on IM channels. The merchant talks to it in plain natural language, and it helps the merchant ",[49,93,94],{},"create \u002F edit \u002F enable"," a \"referral reward\" campaign. Technically it is a ReAct agent built on ",[49,97,98,99],{},"LangGraph's ",[100,101,102],"code",{},"create_react_agent",", with 6 tools attached (listed by responsibility):",[105,106,107,120],"table",{},[108,109,110],"thead",{},[111,112,113,117],"tr",{},[114,115,116],"th",{},"Tool (by responsibility)",[114,118,119],{},"Read \u002F Write",[121,122,123,132,139,146,158,165],"tbody",{},[111,124,125,129],{},[126,127,128],"td",{},"Recommend a plan (based on past campaigns + available coupons)",[126,130,131],{},"Read",[111,133,134,137],{},[126,135,136],{},"Look up the coupon library (attached coupons can only come from here, so the LLM cannot invent coupon IDs)",[126,138,131],{},[111,140,141,144],{},[126,142,143],{},"Look up member types \u002F levels",[126,145,131],{},[111,147,148,153],{},[126,149,150],{},[49,151,152],{},"Create campaign",[126,154,155],{},[49,156,157],{},"Write",[111,159,160,163],{},[126,161,162],{},"Look up existing campaigns (the status determines what can be edited)",[126,164,131],{},[111,166,167,173],{},[126,168,169,172],{},[49,170,171],{},"Modify \u002F enable campaign"," (one tool, three operations)",[126,174,175],{},[49,176,157],{},[17,178,179,180,183,184],{},"The key point: \"create\" and \"modify \u002F enable\" are ",[49,181,182],{},"write operations"," that really do create or change a live campaign in the backend. That is completely different from a read-only agent that \"checks the weather\" or \"summarizes a paragraph\" — ",[49,185,186],{},"a wrong read can be retried; a wrong write is an incident.",[17,188,189],{},"The whole agent is strictly split into three layers, with deterministic code and the LLM each owning their own stretch:",[191,192,196],"pre",{"className":193,"code":194,"language":195,"meta":15,"style":15},"language-mermaid shiki shiki-themes github-light github-dark github-dark","flowchart TD\n  U([\"Merchant · IM channel\"]):::entry --> RT[\"Intent routing layer\u003Cbr>classification · sticky session · command short-circuit\"]:::det\n  RT --> SK[\"① I\u002FO orchestration layer\u003Cbr>lock · restore session · confirmation intercept · wrap-up\"]:::det\n  SK --> IC{\"Pending preview exists\u003Cbr>and this turn looks like a confirmation?\"}:::det\n  IC -->|Yes| ITC[\"Confirmation intercept (deterministic)\u003Cbr>4-way classification → commit directly\"]:::det\n  IC -->|No| RA[\"② ReAct orchestration layer\u003Cbr>create_react_agent\"]:::llm\n  RA --> TOOLS[\"③ Business tools (6)\u003Cbr>preview: assemble \u002F validate \u002F stash\"]:::llm\n  ITC --> BE[(\"Backend · campaign write API\")]:::ext\n  TOOLS --> BE\n  SK \u003C--> RDS[(\"Session store (Redis)\")]:::store\n  classDef entry fill:#DBEAFE,stroke:#2563EB,color:#1E3A8A\n  classDef det fill:#DCFCE7,stroke:#16A34A,color:#14532D\n  classDef llm fill:#FEF3C7,stroke:#D97706,color:#78350F\n  classDef ext fill:#E5E7EB,stroke:#6B7280,color:#374151\n  classDef store fill:#EDE9FE,stroke:#7C3AED,color:#4C1D95\n","mermaid",[100,197,198,206,211,217,223,229,235,241,247,253,259,265,271,277,283],{"__ignoreMap":15},[199,200,203],"span",{"class":201,"line":202},"line",1,[199,204,205],{},"flowchart TD\n",[199,207,208],{"class":201,"line":25},[199,209,210],{},"  U([\"Merchant · IM channel\"]):::entry --> RT[\"Intent routing layer\u003Cbr>classification · sticky session · command short-circuit\"]:::det\n",[199,212,214],{"class":201,"line":213},3,[199,215,216],{},"  RT --> SK[\"① I\u002FO orchestration layer\u003Cbr>lock · restore session · confirmation intercept · wrap-up\"]:::det\n",[199,218,220],{"class":201,"line":219},4,[199,221,222],{},"  SK --> IC{\"Pending preview exists\u003Cbr>and this turn looks like a confirmation?\"}:::det\n",[199,224,226],{"class":201,"line":225},5,[199,227,228],{},"  IC -->|Yes| ITC[\"Confirmation intercept (deterministic)\u003Cbr>4-way classification → commit directly\"]:::det\n",[199,230,232],{"class":201,"line":231},6,[199,233,234],{},"  IC -->|No| RA[\"② ReAct orchestration layer\u003Cbr>create_react_agent\"]:::llm\n",[199,236,238],{"class":201,"line":237},7,[199,239,240],{},"  RA --> TOOLS[\"③ Business tools (6)\u003Cbr>preview: assemble \u002F validate \u002F stash\"]:::llm\n",[199,242,244],{"class":201,"line":243},8,[199,245,246],{},"  ITC --> BE[(\"Backend · campaign write API\")]:::ext\n",[199,248,250],{"class":201,"line":249},9,[199,251,252],{},"  TOOLS --> BE\n",[199,254,256],{"class":201,"line":255},10,[199,257,258],{},"  SK \u003C--> RDS[(\"Session store (Redis)\")]:::store\n",[199,260,262],{"class":201,"line":261},11,[199,263,264],{},"  classDef entry fill:#DBEAFE,stroke:#2563EB,color:#1E3A8A\n",[199,266,268],{"class":201,"line":267},12,[199,269,270],{},"  classDef det fill:#DCFCE7,stroke:#16A34A,color:#14532D\n",[199,272,274],{"class":201,"line":273},13,[199,275,276],{},"  classDef llm fill:#FEF3C7,stroke:#D97706,color:#78350F\n",[199,278,280],{"class":201,"line":279},14,[199,281,282],{},"  classDef ext fill:#E5E7EB,stroke:#6B7280,color:#374151\n",[199,284,286],{"class":201,"line":285},15,[199,287,288],{},"  classDef store fill:#EDE9FE,stroke:#7C3AED,color:#4C1D95\n",[43,290,291],{},[17,292,293],{},"Color legend (shared by all diagrams below): 🟩 green = deterministic code (orchestration \u002F interception \u002F gates) | 🟨 yellow = LLM \u002F agent \u002F tools | 🟪 purple = state storage | ⬜ gray = external backend | 🟦 blue = entry point",[17,295,296,297,299,300,303],{},"One implementation detail worth spelling out: the main reasoning runs on LangGraph's ",[100,298,102],{},"; deciding \"is this a confirmation\" uses ",[49,301,302],{},"the same LLM configuration, just as a \"lightweight call\" with the output token limit squeezed very low"," — it is not a different, cheaper model, only a cap on output length.",[58,305,307],{"id":306},"_3-why-the-naive-approach-doesnt-work","3. Why the naive approach doesn't work",[17,309,310],{},"The most intuitive approach: give the LLM a \"submit\" tool and let it judge for itself when the merchant has \"confirmed\", then call it. Three problems:",[312,313,314,321,327],"ol",{},[315,316,317,320],"li",{},[49,318,319],{},"Semantic ambiguity."," \"OK \u002F fine \u002F sure \u002F that's it\" can mean opposite things in different contexts. The very same \"confirm\" means \"change\" when it follows \"do you want to change X\", and only means \"submit\" when it follows \"here is the preview, do you confirm?\".",[315,322,323,326],{},[49,324,325],{},"Asymmetric cost."," A false submit is far worse than a missed submit (a live campaign gets created in the backend out of thin air). But the LLM's loss function has no such asymmetry — it is just \"trying to guess right\".",[315,328,329,332],{},[49,330,331],{},"Not reproducible."," The same sentence may be guessed differently next time, so when something goes wrong it is hard to reproduce and hard to attribute.",[17,334,335],{},"In one sentence: handing a decision where \"one mistake is an incident\" to a probabilistic black box is not a good idea.",[58,337,339],{"id":338},"_4-core-design-take-commit-out-of-the-llms-hands-dry_run-commit-two-phase","4. Core design: take \"commit\" out of the LLM's hands (dry_run \u002F commit two-phase)",[17,341,342,343,346],{},"Split the flow into two calls that go down ",[49,344,345],{},"different code paths",":",[348,349,350,356],"ul",{},[315,351,352,355],{},[49,353,354],{},"dry_run (preview) belongs to the LLM."," Every time the LLM calls the \"create\" tool it is a dry_run: it interprets natural language into a structured config, assembles it, validates it, generates a preview (text + PDF), and stashes the pending content in the session. If this phase gets something wrong, the preview is merely inaccurate, and regenerating fixes it.",[315,357,358,361,362],{},[49,359,360],{},"commit belongs to deterministic code."," Only that code can actually send the stashed content to the backend. ",[49,363,364],{},"The LLM never holds the right to commit.",[17,366,367,368,371],{},"This iron rule lands on a single ",[49,369,370],{},"boolean switch"," in the tool's input: it is off by default, and its field description says so to the LLM directly — \"never touch this field; only the system's confirmation intercept sets it to true\". The tool branches on it internally: only when the switch is true, the stash exists, and the name matches the stash does it really call the backend write API; otherwise it always takes the preview path and never touches the backend.",[17,373,374,375,378,379,346],{},"The most counterintuitive, and most important, point: ",[49,376,377],{},"the interception happens before the LLM."," For every incoming message, first check whether the session has a \"pending preview\"; if so, first decide whether this turn is a confirmation, and if it is, commit directly — ",[49,380,381],{},"without ever entering the ReAct loop",[191,383,387],{"className":384,"code":385,"language":386,"meta":15,"style":15},"language-py shiki shiki-themes github-light github-dark github-dark","# Message entry point: intercept before ReAct (pseudocode)\nintercepted = confirm_intercept(session, text)\nif intercepted is not None:\n    result = intercepted          # confirmation hit → commit directly, skip the LLM\nelse:\n    result = run_react_turn(state)  # only otherwise go through ReAct\n","py",[100,388,389,394,399,404,409,414],{"__ignoreMap":15},[199,390,391],{"class":201,"line":202},[199,392,393],{},"# Message entry point: intercept before ReAct (pseudocode)\n",[199,395,396],{"class":201,"line":25},[199,397,398],{},"intercepted = confirm_intercept(session, text)\n",[199,400,401],{"class":201,"line":213},[199,402,403],{},"if intercepted is not None:\n",[199,405,406],{"class":201,"line":219},[199,407,408],{},"    result = intercepted          # confirmation hit → commit directly, skip the LLM\n",[199,410,411],{"class":201,"line":225},[199,412,413],{},"else:\n",[199,415,416],{"class":201,"line":231},[199,417,418],{},"    result = run_react_turn(state)  # only otherwise go through ReAct\n",[58,420,422],{"id":421},"_5-how-to-decide-is-this-a-confirmation-whitelist-4-way-classification-safety-bias","5. How to decide \"is this a confirmation\": whitelist + 4-way classification + safety bias",[424,425,426],"blockquote",{},[17,427,428],{},"Wait — doesn't deciding \"is this a confirmation\" still require the LLM?",[17,430,431,432,435],{},"Yes, but it is used differently: we don't let the LLM \"decide whether to commit\", we only let it do a ",[49,433,434],{},"narrow, well-defined classification",", and we hard-code \"which side to fall toward when unsure\".",[17,437,438,441],{},[49,439,440],{},"Step one: a hard-rule fast path."," Strict affirmative phrases (a whitelist plus a length guard); a hit is classified as SUBMIT immediately, without even calling the LLM:",[191,443,445],{"className":384,"code":444,"language":386,"meta":15,"style":15},"# Pseudocode\nSTRICT_CONFIRM = {\"确认创建\", \"确认提交\", \"confirm create\", ...}\n\ndef is_strict_confirm(text):\n    t = text.strip().lower().rstrip(\"。.!?~ \")\n    if not t or len(t) > 25:     # anything over 25 characters is never a \"crisp confirmation\"\n        return False\n    return t in STRICT_CONFIRM\n",[100,446,447,452,457,462,467,472,477,482],{"__ignoreMap":15},[199,448,449],{"class":201,"line":202},[199,450,451],{},"# Pseudocode\n",[199,453,454],{"class":201,"line":25},[199,455,456],{},"STRICT_CONFIRM = {\"确认创建\", \"确认提交\", \"confirm create\", ...}\n",[199,458,459],{"class":201,"line":213},[199,460,461],{"emptyLinePlaceholder":30},"\n",[199,463,464],{"class":201,"line":219},[199,465,466],{},"def is_strict_confirm(text):\n",[199,468,469],{"class":201,"line":225},[199,470,471],{},"    t = text.strip().lower().rstrip(\"。.!?~ \")\n",[199,473,474],{"class":201,"line":231},[199,475,476],{},"    if not t or len(t) > 25:     # anything over 25 characters is never a \"crisp confirmation\"\n",[199,478,479],{"class":201,"line":237},[199,480,481],{},"        return False\n",[199,483,484],{"class":201,"line":243},[199,485,486],{},"    return t in STRICT_CONFIRM\n",[17,488,489],{},[49,490,491],{},"Step two: only ambiguous cases go through a lightweight LLM classifier, which picks one of four:",[105,493,494,507],{},[108,495,496],{},[111,497,498,501,504],{},[114,499,500],{},"Class",[114,502,503],{},"Meaning",[114,505,506],{},"Action",[121,508,509,520,531,542],{},[111,510,511,514,517],{},[126,512,513],{},"SUBMIT",[126,515,516],{},"Confirms submitting the preview already shown",[126,518,519],{},"Commit",[111,521,522,525,528],{},[126,523,524],{},"PREVIEW_AGAIN",[126,526,527],{},"Regenerate the preview with the latest changes",[126,529,530],{},"Unlock, regenerate",[111,532,533,536,539],{},[126,534,535],{},"CHANGE",[126,537,538],{},"Yet another new modification",[126,540,541],{},"Stay locked, accumulate, no preview",[111,543,544,547,550],{},[126,545,546],{},"OTHER",[126,548,549],{},"Greeting \u002F cancel \u002F question \u002F off-topic",[126,551,552],{},"Stay locked, reply normally",[17,554,555,556,559],{},"The classifier uses ",[49,557,558],{},"the bot's previous reply"," to disambiguate — a \"confirm\" that follows \"a proposed direction for changes\" is PREVIEW_AGAIN, and only one that follows \"a review request for a preview already shown\" is SUBMIT. And the most important principle is written into the classification prompt, explicitly encoding the \"asymmetric cost\" as a preference:",[561,562,563],"warning",{},[17,564,565],{},"When unsure, prefer PREVIEW_AGAIN over SUBMIT — the cost of a false submit is far greater than generating one more preview.",[17,567,568],{},"Only a SUBMIT result commits; only PREVIEW_AGAIN unlocks regeneration, while CHANGE \u002F OTHER always stay locked and accumulate. This turns \"asymmetric cost\" from a slogan into a hard bias in the code.",[17,570,571],{},"The full decision flow of the confirmation intercept:",[191,573,575],{"className":193,"code":574,"language":195,"meta":15,"style":15},"flowchart TD\n  IN([\"New message arrives\"]):::entry --> HAS{\"Pending preview exists?\"}:::det\n  HAS -->|No| RUN[\"Normal ReAct path\"]:::llm\n  HAS -->|Yes| STRICT{\"Strict affirmative phrase?\u003Cbr>确认创建 \u002F confirm create\"}:::det\n  STRICT -->|Yes| SUBMIT[\"Verdict = SUBMIT\"]:::det\n  STRICT -->|No| LLM[\"Lightweight LLM 4-way classification\u003Cbr>disambiguated by the previous reply\"]:::llm\n  LLM --> CLS{\"Classification result\"}:::det\n  CLS -->|SUBMIT| SUBMIT\n  CLS -->|PREVIEW_AGAIN| UNLOCK[\"Unlock → regenerate preview\"]:::llm\n  CLS -->|CHANGE \u002F OTHER| LOCK[\"Stay locked → accumulate \u002F chat\"]:::llm\n  SUBMIT --> DISP{\"Which pending item is non-empty?\u003Cbr>modify takes priority\"}:::det\n  DISP -->|Modify| CM[\"Commit: modify \u002F enable\"]:::det\n  DISP -->|Create| CC[\"Commit: create\"]:::det\n  classDef entry fill:#DBEAFE,stroke:#2563EB,color:#1E3A8A\n  classDef det fill:#DCFCE7,stroke:#16A34A,color:#14532D\n  classDef llm fill:#FEF3C7,stroke:#D97706,color:#78350F\n",[100,576,577,581,586,591,596,601,606,611,616,621,626,631,636,641,645,649],{"__ignoreMap":15},[199,578,579],{"class":201,"line":202},[199,580,205],{},[199,582,583],{"class":201,"line":25},[199,584,585],{},"  IN([\"New message arrives\"]):::entry --> HAS{\"Pending preview exists?\"}:::det\n",[199,587,588],{"class":201,"line":213},[199,589,590],{},"  HAS -->|No| RUN[\"Normal ReAct path\"]:::llm\n",[199,592,593],{"class":201,"line":219},[199,594,595],{},"  HAS -->|Yes| STRICT{\"Strict affirmative phrase?\u003Cbr>确认创建 \u002F confirm create\"}:::det\n",[199,597,598],{"class":201,"line":225},[199,599,600],{},"  STRICT -->|Yes| SUBMIT[\"Verdict = SUBMIT\"]:::det\n",[199,602,603],{"class":201,"line":231},[199,604,605],{},"  STRICT -->|No| LLM[\"Lightweight LLM 4-way classification\u003Cbr>disambiguated by the previous reply\"]:::llm\n",[199,607,608],{"class":201,"line":237},[199,609,610],{},"  LLM --> CLS{\"Classification result\"}:::det\n",[199,612,613],{"class":201,"line":243},[199,614,615],{},"  CLS -->|SUBMIT| SUBMIT\n",[199,617,618],{"class":201,"line":249},[199,619,620],{},"  CLS -->|PREVIEW_AGAIN| UNLOCK[\"Unlock → regenerate preview\"]:::llm\n",[199,622,623],{"class":201,"line":255},[199,624,625],{},"  CLS -->|CHANGE \u002F OTHER| LOCK[\"Stay locked → accumulate \u002F chat\"]:::llm\n",[199,627,628],{"class":201,"line":261},[199,629,630],{},"  SUBMIT --> DISP{\"Which pending item is non-empty?\u003Cbr>modify takes priority\"}:::det\n",[199,632,633],{"class":201,"line":267},[199,634,635],{},"  DISP -->|Modify| CM[\"Commit: modify \u002F enable\"]:::det\n",[199,637,638],{"class":201,"line":273},[199,639,640],{},"  DISP -->|Create| CC[\"Commit: create\"]:::det\n",[199,642,643],{"class":201,"line":279},[199,644,264],{},[199,646,647],{"class":201,"line":285},[199,648,270],{},[199,650,652],{"class":201,"line":651},16,[199,653,276],{},[58,655,657],{"id":656},"_6-more-than-interception-four-lines-of-defense-that-really-run","6. More than interception: four lines of defense that really run",[17,659,660,661,346],{},"Interception alone is not enough. In production there are several more scenarios where \"stale state gets submitted by mistake\", so multiple layers of defense are stacked on top. I only list the ones that ",[49,662,663],{},"the code really executes",[17,665,666,669],{},[49,667,668],{},"Defense ① Confirmation intercept + 4-way classification"," (covered above) — guards against \"an ambiguous reply being treated as a submit\". It is the only one that uses the LLM, and a \"constrained LLM\" at that.",[17,671,672,675],{},[49,673,674],{},"Defense ② Closure gate + accumulation lock."," Both are deterministic gates, and both return before any write or state change. Once a preview exists, each change the merchant makes does not trigger an immediate regeneration; it is accumulated first: as long as the merchant \"hasn't explicitly closed out\" or \"this turn was classified as a change \u002F small talk\", preview generation is turned back directly — no new preview, and certainly no backend call — until the merchant plainly says \"that's it\".",[17,677,678,681,682],{},[49,679,680],{},"Defense ③ Triple commit condition + name check."," Even if the LLM oversteps and flips that commit switch, the commit only happens when \"the stash exists + the name matches the stash\"; otherwise it degrades to a preview. ",[49,683,684],{},"The only legitimate entry point that triggers a commit is the deterministic confirmation intercept.",[17,686,687,690],{},[49,688,689],{},"Defense ④ Cold-start guard on switching."," When the conversation switches back from another scenario, any leftover pending preview is cleared; otherwise an offhand \"restart-like phrase\" from the merchant could be misjudged and push a stale preview left over from the previous scenario to production.",[17,692,693,694,697],{},"Plus one state-integrity constraint: ",[49,695,696],{},"the \"create\" and \"modify\" pending contents are mutually exclusive"," — writing either new preview clears the other, otherwise the confirmation intercept wouldn't know which one to commit (inside the intercept, modify takes priority, then create).",[699,700,701],"caution",{},[17,702,703,706,707,710,711,714,715],{},[49,704,705],{},"An honest engineering detail (design intent ≠ what shipped)."," The code also has a \"message sequence number\" field that was meant to be a fifth line of defense, the intent being \"use the message sequence number to judge an old preview as expired and refuse to commit it\". But I went through every reference to it in the code, one by one: ",[49,708,709],{},"it is only ever written, never read or compared",", so this defense ",[49,712,713],{},"is currently not actually wired up and not in effect",". Staleness is in practice covered by the mechanisms above: \"the CHANGE lock accumulates without committing + closing out rebuilds a new preview (the old one is discarded) + cleanup on switching\". I'm writing this down to make a point: ",[49,716,717],{},"to judge whether a defense holds, look at whether the code actually reads it, not at how well the field is named.",[17,719,720],{},"The session state machine (state lives in an external cache, remembering across turns \"what was previewed last turn\"):",[191,722,724],{"className":193,"code":723,"language":195,"meta":15,"style":15},"stateDiagram-v2\n  [*] --> Idle\n  Idle --> PendingCreate: create preview (dry_run)\n  Idle --> PendingModify: modify preview (dry_run)\n  PendingCreate --> PendingCreate: CHANGE accumulates, preview rebuilt\n  PendingModify --> PendingModify: CHANGE accumulates, preview rebuilt\n  PendingCreate --> Committed: confirmation intercept SUBMIT\n  PendingModify --> Committed: confirmation intercept SUBMIT\n  Committed --> Idle: clear pending, record \"last committed\"\n  PendingCreate --> Idle: cleared on switch\n  PendingModify --> Idle: cleared on switch\n  note right of PendingModify\n    Create \u002F modify pending items are mutually exclusive\n    writing a new preview clears the other\n  end note\n",[100,725,726,731,736,741,746,751,756,761,766,771,776,781,786,791,796],{"__ignoreMap":15},[199,727,728],{"class":201,"line":202},[199,729,730],{},"stateDiagram-v2\n",[199,732,733],{"class":201,"line":25},[199,734,735],{},"  [*] --> Idle\n",[199,737,738],{"class":201,"line":213},[199,739,740],{},"  Idle --> PendingCreate: create preview (dry_run)\n",[199,742,743],{"class":201,"line":219},[199,744,745],{},"  Idle --> PendingModify: modify preview (dry_run)\n",[199,747,748],{"class":201,"line":225},[199,749,750],{},"  PendingCreate --> PendingCreate: CHANGE accumulates, preview rebuilt\n",[199,752,753],{"class":201,"line":231},[199,754,755],{},"  PendingModify --> PendingModify: CHANGE accumulates, preview rebuilt\n",[199,757,758],{"class":201,"line":237},[199,759,760],{},"  PendingCreate --> Committed: confirmation intercept SUBMIT\n",[199,762,763],{"class":201,"line":243},[199,764,765],{},"  PendingModify --> Committed: confirmation intercept SUBMIT\n",[199,767,768],{"class":201,"line":249},[199,769,770],{},"  Committed --> Idle: clear pending, record \"last committed\"\n",[199,772,773],{"class":201,"line":255},[199,774,775],{},"  PendingCreate --> Idle: cleared on switch\n",[199,777,778],{"class":201,"line":261},[199,779,780],{},"  PendingModify --> Idle: cleared on switch\n",[199,782,783],{"class":201,"line":267},[199,784,785],{},"  note right of PendingModify\n",[199,787,788],{"class":201,"line":273},[199,789,790],{},"    Create \u002F modify pending items are mutually exclusive\n",[199,792,793],{"class":201,"line":279},[199,794,795],{},"    writing a new preview clears the other\n",[199,797,798],{"class":201,"line":285},[199,799,800],{},"  end note\n",[58,802,804],{"id":803},"_7-two-error-proofing-details-the-same-deterministic-philosophy","7. Two \"error-proofing\" details: the same deterministic philosophy",[17,806,807,808,811],{},"Converge the \"error-prone spots\" into a ",[49,809,810],{},"single point"," in deterministic code, rather than scattering them everywhere, and certainly rather than handing them to the LLM — the same thinking shows up in two places in the data modeling:",[17,813,814,817,818,821],{},[49,815,816],{},"① Unit conversion happens exactly once."," The backend stores points in units of 0.01, and the frontend stores \"input value ×100\". So internally everything uses integers from the merchant's point of view, with ×100 applied uniformly at ",[49,819,820],{},"the one place where the outbound payload is assembled",", and \u002F\u002F100 applied uniformly when reading back from the backend. The benefit: interpretation, preview, and validation all use human-readable integers, and there is no ×100 sprinkled around waiting to be missed.",[17,823,824,835,836,838,839,841,842,844,845,848,849,346],{},[49,825,826,827,830,831,834],{},"② The ",[100,828,829],{},"None"," vs ",[100,832,833],{},"0"," sentinel."," Optional numeric values use ",[100,837,829],{}," to tell \"not passed\" apart from \"passed as 0\": ",[100,840,829],{}," = \"the LLM didn't pass it\" → fall back to the default; ",[100,843,833],{}," = \"the merchant explicitly said no reward on this side\" → keep 0. So the check has to be ",[100,846,847],{},"is None",", not ",[100,850,851],{},"not x",[191,853,855],{"className":384,"code":854,"language":386,"meta":15,"style":15},"# Pseudocode: the fallback only happens when \"not passed\"; an explicit 0 is respected\nif cfg.get(\"points\") is None:\n    cfg[\"points\"] = DEFAULT_POINTS\n",[100,856,857,862,867],{"__ignoreMap":15},[199,858,859],{"class":201,"line":202},[199,860,861],{},"# Pseudocode: the fallback only happens when \"not passed\"; an explicit 0 is respected\n",[199,863,864],{"class":201,"line":25},[199,865,866],{},"if cfg.get(\"points\") is None:\n",[199,868,869],{"class":201,"line":213},[199,870,871],{},"    cfg[\"points\"] = DEFAULT_POINTS\n",[17,873,874,875,878],{},"With an ordinary ",[100,876,877],{},"= default",", you can't tell \"didn't say\" from \"said no\".",[58,880,882],{"id":881},"_8-one-complete-round","8. One complete round",[191,884,886],{"className":193,"code":885,"language":195,"meta":15,"style":15},"sequenceDiagram\n  autonumber\n  actor M as Merchant\n  participant S as Orchestration layer (deterministic)\n  participant A as ReAct Agent (LLM)\n  participant B as Backend\n  M->>A: \"50 points for inviting 3 people\"\n  A->>A: dry_run - assemble + validate + stash\n  A-->>M: Preview + PDF (please confirm)\n  M->>S: \"Raise tier two to 300\"\n  Note over S: 4-way classification = CHANGE → stay locked, accumulate\n  S-->>M: \"Got it, anything else to change?\"\n  M->>S: \"That's it\"\n  Note over S: Close out → regenerate preview (old one discarded)\n  S->>A: dry_run (closure=True)\n  A-->>M: New preview\n  M->>S: \"confirm create\"\n  Note over S: Strict affirmative phrase → SUBMIT (bypasses the LLM)\n  S->>B: Commit\n  B-->>S: ok\n  S-->>M: Created ✅ (draft state)\n",[100,887,888,893,898,903,908,913,918,923,928,933,938,943,948,953,958,963,968,974,980,986,992],{"__ignoreMap":15},[199,889,890],{"class":201,"line":202},[199,891,892],{},"sequenceDiagram\n",[199,894,895],{"class":201,"line":25},[199,896,897],{},"  autonumber\n",[199,899,900],{"class":201,"line":213},[199,901,902],{},"  actor M as Merchant\n",[199,904,905],{"class":201,"line":219},[199,906,907],{},"  participant S as Orchestration layer (deterministic)\n",[199,909,910],{"class":201,"line":225},[199,911,912],{},"  participant A as ReAct Agent (LLM)\n",[199,914,915],{"class":201,"line":231},[199,916,917],{},"  participant B as Backend\n",[199,919,920],{"class":201,"line":237},[199,921,922],{},"  M->>A: \"50 points for inviting 3 people\"\n",[199,924,925],{"class":201,"line":243},[199,926,927],{},"  A->>A: dry_run - assemble + validate + stash\n",[199,929,930],{"class":201,"line":249},[199,931,932],{},"  A-->>M: Preview + PDF (please confirm)\n",[199,934,935],{"class":201,"line":255},[199,936,937],{},"  M->>S: \"Raise tier two to 300\"\n",[199,939,940],{"class":201,"line":261},[199,941,942],{},"  Note over S: 4-way classification = CHANGE → stay locked, accumulate\n",[199,944,945],{"class":201,"line":267},[199,946,947],{},"  S-->>M: \"Got it, anything else to change?\"\n",[199,949,950],{"class":201,"line":273},[199,951,952],{},"  M->>S: \"That's it\"\n",[199,954,955],{"class":201,"line":279},[199,956,957],{},"  Note over S: Close out → regenerate preview (old one discarded)\n",[199,959,960],{"class":201,"line":285},[199,961,962],{},"  S->>A: dry_run (closure=True)\n",[199,964,965],{"class":201,"line":651},[199,966,967],{},"  A-->>M: New preview\n",[199,969,971],{"class":201,"line":970},17,[199,972,973],{},"  M->>S: \"confirm create\"\n",[199,975,977],{"class":201,"line":976},18,[199,978,979],{},"  Note over S: Strict affirmative phrase → SUBMIT (bypasses the LLM)\n",[199,981,983],{"class":201,"line":982},19,[199,984,985],{},"  S->>B: Commit\n",[199,987,989],{"class":201,"line":988},20,[199,990,991],{},"  B-->>S: ok\n",[199,993,995],{"class":201,"line":994},21,[199,996,997],{},"  S-->>M: Created ✅ (draft state)\n",[17,999,1000,1001,1004],{},"One more real detail: committing a \"create\" always ",[49,1002,1003],{},"saves a draft only"," — the AI never sets a campaign live directly; going live has to go through the \"modify \u002F enable\" path, which means passing through \"preview → confirm\" once more. One more layer of irreversibility, one more confirmation.",[58,1006,1008],{"id":1007},"_9-transferable-design-principles","9. Transferable design principles",[312,1010,1011,1017,1023,1029],{},[315,1012,1013,1016],{},[49,1014,1015],{},"Irreversible actions need a gate that doesn't go through the LLM."," The LLM handles \"understanding intent and generating content\"; \"should this really be executed\" is left to deterministic code.",[315,1018,1019,1022],{},[49,1020,1021],{},"Let the LLM classify, don't let it decide."," Narrow the open question (should we commit?) into a tight classification, and write \"fall toward the safe side when unsure\" into the prompt.",[315,1024,1025,1028],{},[49,1026,1027],{},"Back state with external storage + deterministic checks."," Keeping the cross-turn \"pending preview\" in an external cache, combined with gates \u002F mutual exclusion \u002F cleanup on switching, is far more robust than \"hoping the LLM remembers the context\".",[315,1030,1031,1034],{},[49,1032,1033],{},"Judge a defense by \"whether the code actually reads it\"."," A field with \"guard\" in its name is not necessarily guarding anything — the unwired \"message sequence number\" in this post is the reminder: a declared defense and a shipped defense are two different things.",[1036,1037,1038],"tip",{},[17,1039,1040],{},"In one sentence: an agent is not \"the LLM wraps everything\", but a division of labor where \"the LLM handles ambiguity and code handles the irreversible\". The more production-grade the agent, the sharper that dividing line.",[1042,1043,1044],"style",{},"html .light .shiki span {color: var(--shiki-light);background: var(--shiki-light-bg);font-style: var(--shiki-light-font-style);font-weight: var(--shiki-light-font-weight);text-decoration: var(--shiki-light-text-decoration);}html.light .shiki span {color: var(--shiki-light);background: var(--shiki-light-bg);font-style: var(--shiki-light-font-style);font-weight: var(--shiki-light-font-weight);text-decoration: var(--shiki-light-text-decoration);}html .default .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html.dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}",{"title":15,"searchDepth":25,"depth":25,"links":1046},[1047,1048,1049,1050,1051,1052,1053,1054,1055],{"id":60,"depth":25,"text":61},{"id":87,"depth":25,"text":88},{"id":306,"depth":25,"text":307},{"id":338,"depth":25,"text":339},{"id":421,"depth":25,"text":422},{"id":656,"depth":25,"text":657},{"id":803,"depth":25,"text":804},{"id":881,"depth":25,"text":882},{"id":1007,"depth":25,"text":1008},"2026-06-09","In an agent whose actions have irreversible consequences, the decision to actually execute cannot be left to the LLM. Using a production marketing agent as the example, this post covers confirmation interception, the dry_run \u002F commit two-phase design, and the four lines of defense that really run.","\u002Farticles\u002Fagent-hitl-two-phase-commit.svg",{},"\u002Farticles\u002Fagent-hitl-two-phase-commit","10",{"title":39,"description":1057},{"loc":1060},"articles\u002Fagent-hitl-two-phase-commit",[1066,1067],"LLM Apps","Agent","2uBETKQwy7wIH_z39mh-uyyID8xRAdmjBq3GcHPRSag",{"id":1070,"title":1071,"body":1072,"date":1960,"description":1961,"extension":28,"head":27,"image":1962,"meta":1963,"navigation":30,"ogImage":27,"path":1964,"rating":219,"readingTime":1965,"robots":27,"schemaOrg":27,"seo":1966,"sitemap":1967,"stem":1968,"tags":1969,"__hash__":1970},"articles_en\u002Farticles\u002Fagent-security-audit-as-skill.md","Why \"Check This for Security Issues\" Isn't Enough: Turning an Audit Workflow into a Skill",{"type":7,"value":1073,"toc":1948},[1074,1082,1086,1089,1094,1097,1120,1123,1127,1130,1133,1136,1144,1148,1151,1171,1178,1181,1184,1189,1192,1242,1245,1249,1252,1255,1263,1289,1292,1301,1304,1313,1317,1320,1323,1369,1372,1375,1378,1382,1385,1388,1394,1400,1408,1411,1417,1420,1424,1427,1430,1441,1444,1448,1451,1457,1460,1466,1477,1480,1549,1602,1605,1608,1679,1682,1693,1697,1700,1703,1771,1774,1777,1782,1786,1789,1839,1842,1939,1942,1945],[43,1075,1076],{},[17,1077,47,1078,1081],{},[49,1079,1080],{},"the hard part of getting an agent to do a security audit is not that the model can't recognize a vulnerability. It is that nobody told it which work isn't its job, what counts as a finding, and when it must stop."," The material here is a code security skill I recently took apart, five files in total. Instead of going file by file, I work backwards: what goes wrong when you ask an agent to check security directly, which design choice in the skill answers each problem, and only then why those choices belong in a skill. Names and code snippets have been neutralized.",[58,1083,1085],{"id":1084},"it-starts-with-one-sentence","It starts with one sentence",[17,1087,1088],{},"Before opening a merge request you want the agent to look over your changes. The cheapest way to ask is:",[424,1090,1091],{},[17,1092,1093],{},"Can you check whether this change has any security issues?",[17,1095,1096],{},"The model reads the code carefully and hands back a professional-looking list. The trouble is that you cannot tell how far to trust it. Spelled out, that one sentence can go wrong in seven ways:",[312,1098,1099,1102,1105,1108,1111,1114,1117],{},[315,1100,1101],{},"It doesn't find every secret, and it repeats the ones it does find into the conversation.",[315,1103,1104],{},"Broken access control only shows up when you follow the call chain, and reading a few files won't get you there.",[315,1106,1107],{},"Even with scanners wired in, hundreds of raw results dumped into context are more than the model can digest.",[315,1109,1110],{},"The \"findings\" have no attack path, so the real ones get buried.",[315,1112,1113],{},"It fixes things on its own initiative, breaks legitimate callers, and then reports the issue as fixed.",[315,1115,1116],{},"Halfway through a full-repo audit, earlier findings are lost to context compaction.",[315,1118,1119],{},"All of the rules above have to be explained again in every new session.",[17,1121,1122],{},"Let's take them one at a time.",[58,1124,1126],{"id":1125},"problem-1-the-model-misses-secrets-and-repeats-them","Problem 1: the model misses secrets, and repeats them",[17,1128,1129],{},"Finding hardcoded secrets is an exhaustive job. The rules are fixed and nothing may be skipped. That is the opposite of how a model reads code: it samples and understands, it does not match byte by byte. Worse is what it does after finding one. It quotes the line to show you. Now the secret is in the conversation log and then in the report, and the exposure has grown.",[17,1131,1132],{},"The fix is to hand this kind of work to deterministic tools. The skill uses two open-source scanners: gitleaks for secrets and semgrep for injection and dangerous functions. gitleaks is called with its redaction flag, so the output carries a rule name and a location and never the secret itself.",[17,1134,1135],{},"In full-repo mode it also scans git history. The reason is in a comment in the script: a secret that has been removed from the working tree but still sits in an old commit is just as leaked. Those results get their own \"history only\" label.",[1036,1137,1138],{},[17,1139,1140,1143],{},[49,1141,1142],{},"The test",": if a task can be written as rules and must have zero misses, don't give it to the model. The model earns its place where rules can't be written.",[58,1145,1147],{"id":1146},"problem-2-a-scanner-cant-tell-who-is-allowed-to-call-an-endpoint","Problem 2: a scanner can't tell who is allowed to call an endpoint",[17,1149,1150],{},"Scanners have a blind spot. No scanner will flag this:",[191,1152,1154],{"className":384,"code":1153,"language":386,"meta":15,"style":15},"@router.get(\"\u002Forders\u002F{order_id}\")\ndef get_order(order_id: int, user = Depends(current_user)):\n    return order_repo.get(order_id)    # logged in, but is this order yours?\n",[100,1155,1156,1161,1166],{"__ignoreMap":15},[199,1157,1158],{"class":201,"line":202},[199,1159,1160],{},"@router.get(\"\u002Forders\u002F{order_id}\")\n",[199,1162,1163],{"class":201,"line":25},[199,1164,1165],{},"def get_order(order_id: int, user = Depends(current_user)):\n",[199,1167,1168],{"class":201,"line":213},[199,1169,1170],{},"    return order_repo.get(order_id)    # logged in, but is this order yours?\n",[17,1172,1173,1174,1177],{},"There is no string concatenation, no dangerous function, and the auth dependency is in place. Change ",[100,1175,1176],{},"order_id"," and you are reading someone else's order. In business systems the most damaging issues tend to be of this kind: broken access control, missing tenant isolation, a hardcoded verification code left as a backdoor. What they share is the question \"who can call this, and whose data can they see?\", and the answer is spread across the entry point, the auth layer and the data access layer.",[17,1179,1180],{},"This half has to go to the model, but not as a free-form exercise. The skill supplies a review checklist and prescribes the method: list every entry point in scope (HTTP routes, message consumers, callbacks, scheduled jobs, agent tools) and trace each one down to data access, until \"who can get in\" and \"what data is read or written\" are both clear.",[17,1182,1183],{},"The checklist is organized by problem type, and each type says two things: how to look for it and how to fix it. The item on where identity comes from reads roughly like this:",[424,1185,1186],{},[17,1187,1188],{},"For each entry point, find where the tenant ID and user ID come from. If they come from request parameters, the body or headers instead of the session, that is an access control lead.",[17,1190,1191],{},"So the work splits into two halves:",[191,1193,1195],{"className":193,"code":1194,"language":195,"meta":15,"style":15},"flowchart LR\n    A[\"Set scope\u003Cbr\u002F>diff or full repo\"] --> B[\"Scanners\u003Cbr\u002F>secrets, injection, dangerous calls\"]\n    B --> C[\"Model triage\u003Cbr\u002F>true or false, one by one\"]\n    A --> D[\"Checklist review\u003Cbr\u002F>entry point to data access\"]\n    C --> E[\"Report\"]\n    D --> E\n    E --> F{\"Did the user ask for fixes?\"}\n    F -- No --> G[\"Stop at the report\"]\n    F -- Yes --> H[\"Fix → rescan → update report\"]\n",[100,1196,1197,1202,1207,1212,1217,1222,1227,1232,1237],{"__ignoreMap":15},[199,1198,1199],{"class":201,"line":202},[199,1200,1201],{},"flowchart LR\n",[199,1203,1204],{"class":201,"line":25},[199,1205,1206],{},"    A[\"Set scope\u003Cbr\u002F>diff or full repo\"] --> B[\"Scanners\u003Cbr\u002F>secrets, injection, dangerous calls\"]\n",[199,1208,1209],{"class":201,"line":213},[199,1210,1211],{},"    B --> C[\"Model triage\u003Cbr\u002F>true or false, one by one\"]\n",[199,1213,1214],{"class":201,"line":219},[199,1215,1216],{},"    A --> D[\"Checklist review\u003Cbr\u002F>entry point to data access\"]\n",[199,1218,1219],{"class":201,"line":225},[199,1220,1221],{},"    C --> E[\"Report\"]\n",[199,1223,1224],{"class":201,"line":231},[199,1225,1226],{},"    D --> E\n",[199,1228,1229],{"class":201,"line":237},[199,1230,1231],{},"    E --> F{\"Did the user ask for fixes?\"}\n",[199,1233,1234],{"class":201,"line":243},[199,1235,1236],{},"    F -- No --> G[\"Stop at the report\"]\n",[199,1238,1239],{"class":201,"line":249},[199,1240,1241],{},"    F -- Yes --> H[\"Fix → rescan → update report\"]\n",[17,1243,1244],{},"One sentence in the instructions ties the halves together: the scan is only complete when both are done, and a report based on one half must say so. It is there to stop the model from seeing \"0 results\" from the scanners and declaring the code safe.",[58,1246,1248],{"id":1247},"problem-3-how-scanner-results-reach-the-model","Problem 3: how scanner results reach the model",[17,1250,1251],{},"Wiring in scanners creates a new problem. Their raw output is made for people and CI: a large JSON file in which one rule may match hundreds of times. Give that to the model directly and the context fills up first.",[17,1253,1254],{},"So a script sits in between and rewrites the output into something a model can read. The scan script in this skill is a little over a hundred lines, and four of its choices are worth copying:",[191,1256,1261],{"className":1257,"code":1259,"language":1260,"meta":15},[1258],"language-text","Scope: changes relative to origin\u002Fmain (merge base a1b2c3d4), 12 files. Raw results: ~\u002F.sec-audit\u002Fmy-repo\u002Fdiff\ngitleaks: 1 finding\nsemgrep: 12 files actually scanned\nsemgrep: 2 findings\ngitleaks | high | generic-api-key | config\u002Fsettings.py:14\nsemgrep | high | formatted-sql-query | api\u002Fuser.py:21\nsemgrep | medium | avoid-v-html | src\u002Fviews\u002FDetail.vue:88\n","text",[100,1262,1259],{"__ignoreMap":15},[348,1264,1265,1271,1277,1283],{},[315,1266,1267,1270],{},[49,1268,1269],{},"One finding per line, four fields",": tool, severity, rule, file and line. The model takes the location and reads the code itself. The script does not paste code for it.",[315,1272,1273,1276],{},[49,1274,1275],{},"A cap",": at most 300 lines are printed, and the rest are left in the raw JSON file.",[315,1278,1279,1282],{},[49,1280,1281],{},"It prints how many files were actually scanned",": zero results can mean nothing is wrong, or that nothing was scanned. This line lets the model tell them apart. Files that failed to parse are listed separately with a note that they were effectively not scanned.",[315,1284,1285,1288],{},[49,1286,1287],{},"The exit code carries meaning",": 0 means every scanner finished, 2 means at least one did not run.",[17,1290,1291],{},"That last point is a single line in the script:",[191,1293,1295],{"className":384,"code":1294,"language":386,"meta":15,"style":15},"sys.exit(2 if skipped else 0)\n",[100,1296,1297],{"__ignoreMap":15},[199,1298,1299],{"class":201,"line":202},[199,1300,1294],{},[17,1302,1303],{},"And the instructions say the matching thing: on exit code 2, install the tool or resolve the error and rerun, and never conclude \"no issues\" while a scanner has not finished. The script reports the state clearly, the instructions say which conclusions that state permits, and the two are written as a pair.",[1036,1305,1306],{},[17,1307,1308,1309,1312],{},"A CLI written for an agent differs from one written for a person. A person scrolls and doubts. A model believes the lines it sees. So ",[49,1310,1311],{},"keep the output short, make it prove its own completeness, and fail loudly",".",[58,1314,1316],{"id":1315},"problem-4-a-pile-of-findings-and-which-ones-are-real","Problem 4: a pile of \"findings\", and which ones are real",[17,1318,1319],{},"An unconstrained model is happy to over-report. \"This endpoint may be vulnerable to unauthorized access\" and \"consider strengthening input validation\" will fill twenty rows. None of them is wrong, and none of them can be prioritized.",[17,1321,1322],{},"The skill sets a bar. Every finding must state four things:",[105,1324,1325,1335],{},[108,1326,1327],{},[111,1328,1329,1332],{},[114,1330,1331],{},"Element",[114,1333,1334],{},"The question it answers",[121,1336,1337,1345,1353,1361],{},[111,1338,1339,1342],{},[126,1340,1341],{},"File and line",[126,1343,1344],{},"Where is the problem",[111,1346,1347,1350],{},[126,1348,1349],{},"Reachable from which entry point",[126,1351,1352],{},"How does an outside request get to this line",[111,1354,1355,1358],{},[126,1356,1357],{},"Who the attacker is",[126,1359,1360],{},"Unauthenticated, regular user, another tenant, sub-account",[111,1362,1363,1366],{},[126,1364,1365],{},"What they can read or change",[126,1367,1368],{},"The consequence",[17,1370,1371],{},"Anything that can't fill all four is not a finding. It goes into a separate \"open questions\" list for a person to judge. The instructions also say why: findings without an attack path bury the real ones and can't be prioritized.",[17,1373,1374],{},"The same rule drives severity. Severity is not decided by vulnerability type. It is decided by what identity the attacker needs: reading or writing other people's data with no login is critical, needing another provisioned business identity is high, needing a specific precondition is medium. Every cell in the severity table is a value of the \"who the attacker is\" column, so a finding that is missing that element can't even be graded.",[17,1376,1377],{},"Scanner results get a similar requirement: open the code for each one and decide whether it is real, and count false positives only at the end of the report. When one rule matches a hundred times, skipping the whole rule is not allowed. Each match's data source has to be checked and the ones fed by user input pulled out.",[58,1379,1381],{"id":1380},"problem-5-it-fixes-things-unasked-then-says-fixed","Problem 5: it fixes things unasked, then says \"fixed\"",[17,1383,1384],{},"A model that sees a problem wants to fix it, which is normally a strength. But some security fixes hurt legitimate users: add authentication to an old endpoint and every existing caller may fail at once.",[17,1386,1387],{},"The skill draws three lines here.",[17,1389,1390,1393],{},[49,1391,1392],{},"First, when it may act."," If the user asked for a scan or a check, stop at the report and ask which items to fix. Continue only when the user asked for fixes or remediation.",[17,1395,1396,1399],{},[49,1397,1398],{},"Second, what it may fix."," Each finding is classified first:",[348,1401,1402,1405],{},[315,1403,1404],{},"Safe to fix directly: the change stays inside the implementation, doesn't alter the interface contract, and doesn't change what legitimate callers see. Examples are parameterizing concatenated SQL, taking identity from the session, adding an ownership check before reading or writing by ID, and masking logs.",[315,1406,1407],{},"Needs a human decision: list it and don't touch it. Examples are endpoints where adding auth would break current callers, legacy endpoints due for removal, cases where nobody has defined the permission rules, anything involving money, and every finding about secrets.",[17,1409,1410],{},"Secrets get an extra sentence: any secret that has been in the repository is treated as leaked, deleting it from code does not resolve it, and rotation has to be done by a person. The report may only say \"removed from code, rotation pending\".",[17,1412,1413,1416],{},[49,1414,1415],{},"Third, what counts as fixed."," After fixing, rerun the scan, confirm the entries are gone and nothing new appeared, then run the project's own tests. The instruction is blunt: nothing may be marked fixed without a rescan.",[17,1418,1419],{},"One more constraint targets a shortcut: don't add ignore rules to make the scanner go quiet. There are two ways to make a warning disappear. You can fix it, or you can add an ignore comment on that line. If all the model is told is \"make the scan pass\", the second is the shorter path.",[58,1421,1423],{"id":1422},"problem-6-halfway-through-the-early-findings-are-gone","Problem 6: halfway through, the early findings are gone",[17,1425,1426],{},"A full-repo audit reads a lot of code. As the session grows, earlier content gets compacted or truncated. If findings live only in the conversation, the conclusions from batch one may be incomplete by batch eight.",[17,1428,1429],{},"The fix is to keep state outside the context:",[348,1431,1432,1435,1438],{},[315,1433,1434],{},"In full-repo mode, list every entry point first, review in batches, and write the findings to the report file after each batch before moving on.",[315,1436,1437],{},"The report and the raw scanner output live in a fixed location under the user's home directory, one folder per repository. Keeping them outside the repo is deliberate. The report describes unfixed vulnerabilities and must not get committed by accident.",[315,1439,1440],{},"Before each scan, check that folder for earlier reports. Issues already reported are marked as pre-existing and not reported again as new.",[17,1442,1443],{},"That last point gives the report an \"origin\" column: introduced by this change, widened by this change, or pre-existing. For a pre-merge check, the ones introduced by this change come first, because those are what this merge request is responsible for.",[58,1445,1447],{"id":1446},"problem-7-explaining-the-rules-again-every-time","Problem 7: explaining the rules again every time",[17,1449,1450],{},"At this point each of the first six problems has an answer, and together they make a long briefing: which script to run first, how to triage results, where the checklist is, what the report looks like, what must not be changed. Pasting that into every session is not realistic. Putting it all in the project's always-loaded instruction file is too heavy, because most sessions never do a security audit and would still pay context for those hundreds of lines.",[17,1452,1453,1454],{},"This is the problem a skill solves: ",[49,1455,1456],{},"store a workflow as files and load it only when it is needed.",[17,1458,1459],{},"Physically it is a directory:",[191,1461,1464],{"className":1462,"code":1463,"language":1260,"meta":15},[1258],"sec-audit\u002F\n├── SKILL.md              # required: trigger description + workflow instructions\n├── references\u002F\n│   └── checklist.md      # the review checklist, read when needed\n└── scripts\u002F\n    ├── scan.py           # the scan script, executed and never read in\n    └── selftest.py       # self-test\n",[100,1465,1463],{"__ignoreMap":15},[17,1467,1468,1469,1472,1473,1476],{},"Placed under ",[100,1470,1471],{},"~\u002F.claude\u002Fskills\u002F"," it applies to all of your projects. Placed under a repository's ",[100,1474,1475],{},".claude\u002Fskills\u002F"," it travels with the project.",[17,1478,1479],{},"Loading happens in three levels, and this is the core mechanism:",[191,1481,1483],{"className":193,"code":1482,"language":195,"meta":15,"style":15},"sequenceDiagram\n    participant U as User\n    participant M as Model\n    participant S as Skill directory\n    Note over M: At session start\u003Cbr\u002F>only each skill's name and description are in context\n    U->>M: Run a security check before I open the MR\n    M->>S: Description matches, read the SKILL.md body\n    S-->>M: Seven-step workflow and constraints\n    M->>S: Execute scripts\u002Fscan.py\n    S-->>M: Only the script output enters context\n    M->>S: Read references\u002Fchecklist.md\n    S-->>M: Review checklist\n    M-->>U: Conclusion and findings table\n",[100,1484,1485,1489,1494,1499,1504,1509,1514,1519,1524,1529,1534,1539,1544],{"__ignoreMap":15},[199,1486,1487],{"class":201,"line":202},[199,1488,892],{},[199,1490,1491],{"class":201,"line":25},[199,1492,1493],{},"    participant U as User\n",[199,1495,1496],{"class":201,"line":213},[199,1497,1498],{},"    participant M as Model\n",[199,1500,1501],{"class":201,"line":219},[199,1502,1503],{},"    participant S as Skill directory\n",[199,1505,1506],{"class":201,"line":225},[199,1507,1508],{},"    Note over M: At session start\u003Cbr\u002F>only each skill's name and description are in context\n",[199,1510,1511],{"class":201,"line":231},[199,1512,1513],{},"    U->>M: Run a security check before I open the MR\n",[199,1515,1516],{"class":201,"line":237},[199,1517,1518],{},"    M->>S: Description matches, read the SKILL.md body\n",[199,1520,1521],{"class":201,"line":243},[199,1522,1523],{},"    S-->>M: Seven-step workflow and constraints\n",[199,1525,1526],{"class":201,"line":249},[199,1527,1528],{},"    M->>S: Execute scripts\u002Fscan.py\n",[199,1530,1531],{"class":201,"line":255},[199,1532,1533],{},"    S-->>M: Only the script output enters context\n",[199,1535,1536],{"class":201,"line":261},[199,1537,1538],{},"    M->>S: Read references\u002Fchecklist.md\n",[199,1540,1541],{"class":201,"line":267},[199,1542,1543],{},"    S-->>M: Review checklist\n",[199,1545,1546],{"class":201,"line":273},[199,1547,1548],{},"    M-->>U: Conclusion and findings table\n",[105,1550,1551,1564],{},[108,1552,1553],{},[111,1554,1555,1558,1561],{},[114,1556,1557],{},"Level",[114,1559,1560],{},"Content",[114,1562,1563],{},"When it costs context",[121,1565,1566,1577,1591],{},[111,1567,1568,1571,1574],{},[126,1569,1570],{},"1",[126,1572,1573],{},"Name and description",[126,1575,1576],{},"Every session",[111,1578,1579,1582,1588],{},[126,1580,1581],{},"2",[126,1583,1584,1587],{},[100,1585,1586],{},"SKILL.md"," body",[126,1589,1590],{},"After the skill triggers",[111,1592,1593,1596,1599],{},[126,1594,1595],{},"3",[126,1597,1598],{},"Reference files, scripts",[126,1600,1601],{},"When the body says to read or run them",[17,1603,1604],{},"In frontend terms, level one is the route table, level two is a lazy-loaded page component, and level three is the modules that page imports on demand. The analogy fails in one place: route matching is deterministic, while a skill triggers because the model read the description and made a judgment. A vague description means the skill may not trigger when it should.",[17,1606,1607],{},"That explains why the description reads like a list of trigger phrases:",[191,1609,1613],{"className":1610,"code":1611,"language":1612,"meta":15,"style":15},"language-yaml shiki shiki-themes github-light github-dark github-dark","---\nname: sec-audit\ndescription: Code security scanning and remediation. Runs scanners for a\n  deterministic pass, then reviews access control, tenant isolation and similar\n  issues against a checklist, writes a report, fixes and rescans. Use when the\n  user says \"security scan\", \"pre-MR security check\", \"full-repo security\n  audit\", \"any broken access control\", \"fix the security issues\". Also use it\n  to confirm a change introduced no security problems before an MR. Do not read\n  the code and conclude from intuition.\n---\n","yaml",[100,1614,1615,1621,1635,1645,1650,1655,1660,1665,1670,1675],{"__ignoreMap":15},[199,1616,1617],{"class":201,"line":202},[199,1618,1620],{"class":1619},"shcOC","---\n",[199,1622,1623,1627,1631],{"class":201,"line":25},[199,1624,1626],{"class":1625},"sByVh","name",[199,1628,1630],{"class":1629},"slsVL",": ",[199,1632,1634],{"class":1633},"sfrk1","sec-audit\n",[199,1636,1637,1640,1642],{"class":201,"line":213},[199,1638,1639],{"class":1625},"description",[199,1641,1630],{"class":1629},[199,1643,1644],{"class":1633},"Code security scanning and remediation. Runs scanners for a\n",[199,1646,1647],{"class":201,"line":219},[199,1648,1649],{"class":1633},"  deterministic pass, then reviews access control, tenant isolation and similar\n",[199,1651,1652],{"class":201,"line":225},[199,1653,1654],{"class":1633},"  issues against a checklist, writes a report, fixes and rescans. Use when the\n",[199,1656,1657],{"class":201,"line":231},[199,1658,1659],{"class":1633},"  user says \"security scan\", \"pre-MR security check\", \"full-repo security\n",[199,1661,1662],{"class":201,"line":237},[199,1663,1664],{"class":1633},"  audit\", \"any broken access control\", \"fix the security issues\". Also use it\n",[199,1666,1667],{"class":201,"line":243},[199,1668,1669],{"class":1633},"  to confirm a change introduced no security problems before an MR. Do not read\n",[199,1671,1672],{"class":201,"line":249},[199,1673,1674],{"class":1633},"  the code and conclude from intuition.\n",[199,1676,1677],{"class":201,"line":255},[199,1678,1620],{"class":1619},[17,1680,1681],{},"It has three parts: what the skill does, the phrases users will actually say, and one negative constraint. That final sentence addresses the scenario this post opened with, where the model believes it can answer directly and bypasses the skill.",[17,1683,1684,1685,1688,1689,1692],{},"The three levels also decide where content goes. The twelve categories of review items run to a hundred lines and sit in ",[100,1686,1687],{},"references\u002F",", and a frontend project needs to read only two of those sections. The scan script sits in ",[100,1690,1691],{},"scripts\u002F",", where the model executes it and its source never enters context. The body keeps only the workflow and constraints, at just over a hundred lines.",[58,1694,1696],{"id":1695},"the-last-step-knowing-the-install-works","The last step: knowing the install works",[17,1698,1699],{},"The skill depends on two external scanners. Whether they are installed, whether the version is right, whether rules can be downloaded: any of these can fail. And the worst way for a scanner to fail is to quietly return zero results.",[17,1701,1702],{},"So the directory includes a self-test script of under forty lines that does something very direct:",[191,1704,1706],{"className":384,"code":1705,"language":386,"meta":15,"style":15},"SAMPLE = '''\nGITHUB_TOKEN = \"\u003Ca correctly formatted fake token>\"\n\n@app.route(\"\u002Fuser\")\ndef user():\n    return str(conn.execute(\"select * from t where id = '%s'\" % request.args[\"id\"]).fetchall())\n'''\n\n# create a repo in a temp directory, write the sample above, run a full scan\nassert proc.returncode == 0,          \"a scanner did not finish\"\nassert \"gitleaks | \" in proc.stdout,  \"the fake secret was not reported\"\nassert \"semgrep | \" in proc.stdout,   \"the SQL concatenation was not reported\"\nassert FAKE_TOKEN not in proc.stdout, \"a secret value appeared in the output\"\n",[100,1707,1708,1713,1718,1722,1727,1732,1737,1742,1746,1751,1756,1761,1766],{"__ignoreMap":15},[199,1709,1710],{"class":201,"line":202},[199,1711,1712],{},"SAMPLE = '''\n",[199,1714,1715],{"class":201,"line":25},[199,1716,1717],{},"GITHUB_TOKEN = \"\u003Ca correctly formatted fake token>\"\n",[199,1719,1720],{"class":201,"line":213},[199,1721,461],{"emptyLinePlaceholder":30},[199,1723,1724],{"class":201,"line":219},[199,1725,1726],{},"@app.route(\"\u002Fuser\")\n",[199,1728,1729],{"class":201,"line":225},[199,1730,1731],{},"def user():\n",[199,1733,1734],{"class":201,"line":231},[199,1735,1736],{},"    return str(conn.execute(\"select * from t where id = '%s'\" % request.args[\"id\"]).fetchall())\n",[199,1738,1739],{"class":201,"line":237},[199,1740,1741],{},"'''\n",[199,1743,1744],{"class":201,"line":243},[199,1745,461],{"emptyLinePlaceholder":30},[199,1747,1748],{"class":201,"line":249},[199,1749,1750],{},"# create a repo in a temp directory, write the sample above, run a full scan\n",[199,1752,1753],{"class":201,"line":255},[199,1754,1755],{},"assert proc.returncode == 0,          \"a scanner did not finish\"\n",[199,1757,1758],{"class":201,"line":261},[199,1759,1760],{},"assert \"gitleaks | \" in proc.stdout,  \"the fake secret was not reported\"\n",[199,1762,1763],{"class":201,"line":267},[199,1764,1765],{},"assert \"semgrep | \" in proc.stdout,   \"the SQL concatenation was not reported\"\n",[199,1767,1768],{"class":201,"line":273},[199,1769,1770],{},"assert FAKE_TOKEN not in proc.stdout, \"a secret value appeared in the output\"\n",[17,1772,1773],{},"It builds a sample with known problems, asserts that both scanners report them, and asserts that the output contains no secret value. The last assertion verifies the redaction promise from problem one.",[17,1775,1776],{},"One detail: the fake token in the script is assembled from two string pieces. Otherwise the self-test file would itself be flagged by the secret scanner.",[1036,1778,1779],{},[17,1780,1781],{},"The deterministic half of a skill is ordinary code and should have tests. The instruction half can't be asserted on. You trigger it a few times, see which step drifts, and add the missing sentence.",[58,1783,1785],{"id":1784},"principles-to-take-with-you","Principles to take with you",[17,1787,1788],{},"This skill is about security audits, but its structure fits anything you want an agent to do repeatedly and reliably:",[312,1790,1791,1797,1803,1809,1815,1821,1827,1833],{},[315,1792,1793,1796],{},[49,1794,1795],{},"Divide the work first."," What can be written as rules and must have zero misses goes to code. What needs an understanding of context goes to the model.",[315,1798,1799,1802],{},[49,1800,1801],{},"Script output is written for the model."," Short, fixed in structure, able to prove it covered everything, and explicit about failure through the exit code.",[315,1804,1805,1808],{},[49,1806,1807],{},"Set an evidence bar for conclusions."," What doesn't meet it is listed separately and kept out of the conclusions.",[315,1810,1811,1814],{},[49,1812,1813],{},"Write down the stopping points."," When to report without acting, and which changes a person must decide.",[315,1816,1817,1820],{},[49,1818,1819],{},"Completion needs a verification step."," Without a rerun, nothing is marked done.",[315,1822,1823,1826],{},[49,1824,1825],{},"Persist state."," Intermediate results of long tasks go into a file, not into conversational memory.",[315,1828,1829,1832],{},[49,1830,1831],{},"Give the reason with the rule."," A model that knows what a rule is guarding against can handle cases the checklist didn't cover in the same spirit.",[315,1834,1835,1838],{},[49,1836,1837],{},"Write the description as trigger phrases."," List what users will actually say, and add a sentence that stops the model from bypassing the skill.",[17,1840,1841],{},"A minimal skeleton to start from:",[191,1843,1847],{"className":1844,"code":1845,"language":1846,"meta":15,"style":15},"language-markdown shiki shiki-themes github-light github-dark github-dark","---\nname: \u003Cskill name>\ndescription: \u003Cwhat it does>. Use when the user says \"\u003Cphrase 1>\" or \"\u003Cphrase 2>\". Also use it when \u003Cthe case where it tends to get bypassed>.\n---\n\n# \u003CTitle>\n\n## Workflow\n### 1. Set scope\n### 2. Run the script\n`python scripts\u002F\u003Cscript>.py`. Draw no conclusion on a non-zero exit code.\n### 3. Judge\nRead `references\u002F\u003Cchecklist>.md` and go through every item.\n### 4. Output\nWrite to \u003Cfixed location> using this template...\n### 5. Verify\n\n## Constraints\n- \u003Cwhat must not be done, and why>\n","markdown",[100,1848,1849,1853,1858,1863,1867,1871,1876,1880,1885,1890,1895,1900,1905,1910,1915,1920,1925,1929,1934],{"__ignoreMap":15},[199,1850,1851],{"class":201,"line":202},[199,1852,1620],{},[199,1854,1855],{"class":201,"line":25},[199,1856,1857],{},"name: \u003Cskill name>\n",[199,1859,1860],{"class":201,"line":213},[199,1861,1862],{},"description: \u003Cwhat it does>. Use when the user says \"\u003Cphrase 1>\" or \"\u003Cphrase 2>\". Also use it when \u003Cthe case where it tends to get bypassed>.\n",[199,1864,1865],{"class":201,"line":219},[199,1866,1620],{},[199,1868,1869],{"class":201,"line":225},[199,1870,461],{"emptyLinePlaceholder":30},[199,1872,1873],{"class":201,"line":231},[199,1874,1875],{},"# \u003CTitle>\n",[199,1877,1878],{"class":201,"line":237},[199,1879,461],{"emptyLinePlaceholder":30},[199,1881,1882],{"class":201,"line":243},[199,1883,1884],{},"## Workflow\n",[199,1886,1887],{"class":201,"line":249},[199,1888,1889],{},"### 1. Set scope\n",[199,1891,1892],{"class":201,"line":255},[199,1893,1894],{},"### 2. Run the script\n",[199,1896,1897],{"class":201,"line":261},[199,1898,1899],{},"`python scripts\u002F\u003Cscript>.py`. Draw no conclusion on a non-zero exit code.\n",[199,1901,1902],{"class":201,"line":267},[199,1903,1904],{},"### 3. Judge\n",[199,1906,1907],{"class":201,"line":273},[199,1908,1909],{},"Read `references\u002F\u003Cchecklist>.md` and go through every item.\n",[199,1911,1912],{"class":201,"line":279},[199,1913,1914],{},"### 4. Output\n",[199,1916,1917],{"class":201,"line":285},[199,1918,1919],{},"Write to \u003Cfixed location> using this template...\n",[199,1921,1922],{"class":201,"line":651},[199,1923,1924],{},"### 5. Verify\n",[199,1926,1927],{"class":201,"line":970},[199,1928,461],{"emptyLinePlaceholder":30},[199,1930,1931],{"class":201,"line":976},[199,1932,1933],{},"## Constraints\n",[199,1935,1936],{"class":201,"line":982},[199,1937,1938],{},"- \u003Cwhat must not be done, and why>\n",[1940,1941],"hr",{},[17,1943,1944],{},"Look back at the opening request, \"can you check whether this change has any security issues?\" What it lacked was not a stronger model. The same model, given a division of labor, an evidence bar, stopping points and a verification step, produces something you can schedule and review. A skill fixes those instructions in place so they are present every time.",[1042,1946,1947],{},"html .light .shiki span {color: var(--shiki-light);background: var(--shiki-light-bg);font-style: var(--shiki-light-font-style);font-weight: var(--shiki-light-font-weight);text-decoration: var(--shiki-light-text-decoration);}html.light .shiki span {color: var(--shiki-light);background: var(--shiki-light-bg);font-style: var(--shiki-light-font-style);font-weight: var(--shiki-light-font-weight);text-decoration: var(--shiki-light-text-decoration);}html .default .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html.dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html pre.shiki code .shcOC, html code.shiki .shcOC{--shiki-light:#6F42C1;--shiki-default:#B392F0;--shiki-dark:#B392F0}html pre.shiki code .sByVh, html code.shiki .sByVh{--shiki-light:#22863A;--shiki-default:#85E89D;--shiki-dark:#85E89D}html pre.shiki code .slsVL, html code.shiki .slsVL{--shiki-light:#24292E;--shiki-default:#E1E4E8;--shiki-dark:#E1E4E8}html pre.shiki code .sfrk1, html code.shiki .sfrk1{--shiki-light:#032F62;--shiki-default:#9ECBFF;--shiki-dark:#9ECBFF}",{"title":15,"searchDepth":25,"depth":25,"links":1949},[1950,1951,1952,1953,1954,1955,1956,1957,1958,1959],{"id":1084,"depth":25,"text":1085},{"id":1125,"depth":25,"text":1126},{"id":1146,"depth":25,"text":1147},{"id":1247,"depth":25,"text":1248},{"id":1315,"depth":25,"text":1316},{"id":1380,"depth":25,"text":1381},{"id":1422,"depth":25,"text":1423},{"id":1446,"depth":25,"text":1447},{"id":1695,"depth":25,"text":1696},{"id":1784,"depth":25,"text":1785},"2026-11-27","Ask a coding agent to look for security problems and it will miss secrets, report findings with no attack path, and call things fixed without checking. This post walks through seven problems and their fixes, then packages the fixes as a skill, covering the directory layout, three-level loading and how to write the trigger description.","\u002Farticles\u002Fagent-security-audit-as-skill.svg",{},"\u002Farticles\u002Fagent-security-audit-as-skill","12",{"title":1071,"description":1961},{"loc":1964},"articles\u002Fagent-security-audit-as-skill",[1066,1067],"1C9KF5Ws0ogMN1lunmeTO4bvn0nf-Oww539u5OvJnHQ",{"id":1972,"title":1973,"body":1974,"date":3038,"description":3039,"extension":28,"head":27,"image":3040,"meta":3041,"navigation":30,"ogImage":27,"path":3042,"rating":219,"readingTime":3043,"robots":27,"schemaOrg":27,"seo":3044,"sitemap":3045,"stem":3046,"tags":3047,"__hash__":3050},"articles_en\u002Farticles\u002Fgeoip-user-country.md","No External API, No DDL: How the \"User Country\" Field Grew Out of a Login IP",{"type":7,"value":1975,"toc":3016},[1976,1988,1992,1995,2009,2023,2026,2030,2035,2129,2133,2136,2142,2149,2158,2162,2165,2180,2184,2189,2195,2236,2243,2252,2256,2263,2410,2413,2418,2425,2470,2476,2481,2503,2508,2511,2515,2519,2529,2535,2587,2594,2599,2603,2610,2616,2630,2634,2643,2650,2654,2658,2665,2677,2681,2688,2696,2702,2771,2782,2786,2791,2802,2811,2864,2873,2883,2889,2903,2907,2965,2969,3013],[424,1977,1978,1985],{},[17,1979,1980,1981,1984],{},"The operations team wanted to see \"which country is this user from\" on the customer detail page. It sounds like a one-line requirement, but the database had no address field at all. The only thing remotely related to geography was a ",[100,1982,1983],{},"login_ip"," column that had been sitting there for half a year without anyone writing to it.",[17,1986,1987],{},"This post documents how the requirement was delivered end to end: a hands-on comparison of four approaches, a zero-DDL design, three hair-pulling pitfalls, and why in the end I still gave it a scheduled job that \"swaps its brain every week\".",[58,1989,1991],{"id":1990},"_1-breaking-down-the-requirement-it-is-really-two-problems","1. Breaking down the requirement: it is really two problems",[17,1993,1994],{},"\"Show the user's country on the detail page\" splits into two things:",[312,1996,1997,2003],{},[315,1998,1999,2002],{},[49,2000,2001],{},"Get the user's IP"," — when do we capture it, and where do we store it?",[315,2004,2005,2008],{},[49,2006,2007],{},"Turn the IP into a country"," — what do we resolve it with?",[17,2010,2011,2012,2015,2016,2019,2020,2022],{},"The first one is easy to agree on: the IP ",[49,2013,2014],{},"at login time"," is the most representative (it is backed by an explicit user action), and the login record table ",[100,2017,2018],{},"login_record"," already had a ",[100,2021,1983],{}," column lying around. Whoever created the table clearly thought of it; the login flow just never wrote to it.",[17,2024,2025],{},"The second one is where the real decision-making happens.",[58,2027,2029],{"id":2028},"_2-comparing-the-options-four-roads-three-ruled-out-by-testing","2. Comparing the options: four roads, three ruled out by testing",[2031,2032,2034],"h3",{"id":2033},"the-candidates","The candidates",[105,2036,2037,2053],{},[108,2038,2039],{},[111,2040,2041,2044,2047,2050],{},[114,2042,2043],{},"Option",[114,2045,2046],{},"How it works",[114,2048,2049],{},"Pros",[114,2051,2052],{},"Fatal flaw",[121,2054,2055,2081,2097,2113],{},[111,2056,2057,2062,2073,2076],{},[126,2058,2059],{},[49,2060,2061],{},"A. Ready-made header from the CDN\u002Fgateway",[126,2063,2064,2065,2068,2069,2072],{},"Cloudflare's ",[100,2066,2067],{},"CF-IPCountry",", CloudFront's ",[100,2070,2071],{},"CloudFront-Viewer-Country","; the backend just reads a header",[126,2074,2075],{},"Zero code, zero dependencies, reusable site-wide",[126,2077,2078],{},[49,2079,2080],{},"You need to have a CDN in the first place",[111,2082,2083,2088,2091,2094],{},[126,2084,2085],{},[49,2086,2087],{},"B. Online IP geolocation API",[126,2089,2090],{},"Call ip-api \u002F ipinfo at login and persist the country",[126,2092,2093],{},"Least code, data is always current",[126,2095,2096],{},"External dependency (quota\u002Flatency\u002Favailability), needs DDL, user IPs leave your system for a third party",[111,2098,2099,2104,2107,2110],{},[126,2100,2101],{},[49,2102,2103],{},"C. Local offline database, GeoLite2",[126,2105,2106],{},"Bundle the mmdb file into the jar and query it in memory",[126,2108,2109],{},"No outbound calls, no quota, microsecond lookups, zero DDL",[126,2111,2112],{},"jar grows by 8MB; the data is a snapshot and goes stale",[111,2114,2115,2120,2123,2126],{},[126,2116,2117],{},[49,2118,2119],{},"D. Local offline database, ip2region",[126,2121,2122],{},"Same as C, with the xdb format instead",[126,2124,2125],{},"Fully open source, can be committed to the repo",[126,2127,2128],{},"Country names are Chinese strings (\"美国|0|0|0|0\"), so a bilingual UI still has to maintain its own Chinese-name → ISO-code mapping table",[2031,2130,2132],{"id":2131},"ruling-out-option-a-a-pleasant-bit-of-dns-detective-work","Ruling out option A (a pleasant bit of DNS detective work)",[17,2134,2135],{},"Option A is the most tempting. If there is a CDN at the entry point, this requirement is practically free. Whether it is worth betting on is something you can find out by probing:",[191,2137,2140],{"className":2138,"code":2139,"language":1260,"meta":15},[1258],"$ Resolve-DnsName api.example.com\n→ no CNAME pointing to a CDN\n\n$ curl -sI https:\u002F\u002Fapi.example.com\u002F\n→ no cf-ray, no via: cloudfront in the response headers\n",[100,2141,2139],{"__ignoreMap":15},[17,2143,2144,2145,2148],{},"Conclusion: testing confirmed that there is ",[49,2146,2147],{},"no CDN on the API request path that would inject a geolocation header",". Going with option A would mean adding a geoip2 module to the production entry gateway myself: installing system libraries and changing the entry configuration that all traffic flows through. The risk far outweighs the benefit. Ruled out.",[424,2150,2151],{},[17,2152,2153,2154,2157],{},"A bonus finding along the way: only once you know exactly which hops are on the request path can you decide which part of ",[100,2155,2156],{},"X-Forwarded-For"," the backend should trust. On our path, taking the real client IP from the head of the chain is reliable.",[2031,2159,2161],{"id":2160},"why-option-b-was-ruled-out","Why option B was ruled out",[17,2163,2164],{},"It is not that an online API cannot work; it is just a bad deal for this scenario:",[348,2166,2167,2174,2177],{},[315,2168,2169,2170,2173],{},"You must ",[49,2171,2172],{},"resolve at login time and persist the result"," (you cannot make an outbound call every time the detail page opens), so you need a DDL change to add a column",[315,2175,2176],{},"Login is a critical path, so the outbound call has to be asynchronous with timeout fallback, and the code ends up more complex than option C",[315,2178,2179],{},"The free quota is a hidden ceiling: the free tier of ip-api explicitly forbids commercial use, and the free tier of ipinfo is 50k\u002Fmonth. It is enough today only because the volume is small today",[2031,2181,2183],{"id":2182},"the-final-choice-c-geolite2-mmdb-resolve-at-query-time","The final choice: C (GeoLite2 mmdb) + resolve at query time",[43,2185,2186],{},[17,2187,2188],{},"GeoLite2 is provided by MaxMind, and using it is subject to MaxMind's license agreement.",[17,2190,2191,2192,1312],{},"Besides the data source, there is an orthogonal decision: ",[49,2193,2194],{},"when to resolve",[105,2196,2197,2209],{},[108,2198,2199],{},[111,2200,2201,2204,2206],{},[114,2202,2203],{},"Timing",[114,2205,2049],{},[114,2207,2208],{},"Cons",[121,2210,2211,2222],{},[111,2212,2213,2216,2219],{},[126,2214,2215],{},"Resolve at login → persist the country",[126,2217,2218],{},"Zero resolution cost on the detail page; can filter\u002Freport by country in SQL",[126,2220,2221],{},"Needs DDL; after an mmdb upgrade the existing rows hold outdated conclusions",[111,2223,2224,2230,2233],{},[126,2225,2226,2229],{},[49,2227,2228],{},"Resolve in real time at query time"," (✅)",[126,2231,2232],{},"Zero DDL; historical data is automatically recomputed when the database is replaced; the country is never persisted, so there is no dirty data",[126,2234,2235],{},"One extra table query per detail request; cannot filter by country in SQL",[17,2237,2238,2239,2242],{},"Right now the only consumer is \"display on the detail page\", so I went with resolving at query time. ",[49,2240,2241],{},"An mmdb is an in-memory prefix tree and a single lookup takes microseconds",", so the cost of computing it on the fly is effectively zero.",[424,2244,2245],{},[17,2246,2247,2248,2251],{},"What is an mmdb? You can think of it as \"an IP → country dictionary shipped inside the bundle\". But it is not JSON; it is a ",[49,2249,2250],{},"binary trie (prefix tree)"," designed specifically for IP matching. An IP is essentially 32 or 128 bits, and a lookup just walks the tree bit by bit, which is why an 8MB file can cover every IP range in the world and still answer in microseconds.",[58,2253,2255],{"id":2254},"_3-the-design-two-flows-decoupled-by-one-column","3. The design: two flows, decoupled by one column",[17,2257,2258,2259,2262],{},"The whole implementation is split by the single column ",[100,2260,2261],{},"login_record.login_ip"," into two flows that do not interfere with each other:",[191,2264,2266],{"className":193,"code":2265,"language":195,"meta":15,"style":15},"sequenceDiagram\n    autonumber\n    participant C as Consumer login page\n    participant L as Login service\n    participant DB as MySQL\u003Cbr\u002F>(login_record)\n    participant A as Admin detail page\n    participant D as Customer detail service\n    participant G as GeoIpService\u003Cbr\u002F>(in-memory mmdb)\n\n    Note over G: Loads GeoLite2-Country.mmdb into memory at startup\n\n    rect rgb(235, 244, 255)\n    Note over C,DB: ① Capture the IP at login\n    C->>L: POST \u002Fauth\u002Flogin\n    L->>L: Take the real IP from X-Forwarded-For\n    L->>DB: Write login_ip (refreshed on every login)\n    L-->>C: token\n    end\n\n    rect rgb(255, 246, 232)\n    Note over A,G: ② Resolve the country in real time on detail\n    A->>D: POST \u002Fadmin\u002Fcustomer\u002Fdetail\n    D->>DB: Query the user's latest login_ip\n    D->>G: resolveCountryIsoCode(ip)\n    G-->>D: \"US\" (private \u002F unavailable → null)\n    D-->>A: country: \"US\"\n    A->>A: Intl.DisplayNames → \"美国 \u002F United States\"\n    end\n",[100,2267,2268,2272,2277,2282,2287,2292,2297,2302,2307,2311,2316,2320,2325,2330,2335,2340,2345,2350,2355,2359,2364,2369,2375,2381,2387,2393,2399,2405],{"__ignoreMap":15},[199,2269,2270],{"class":201,"line":202},[199,2271,892],{},[199,2273,2274],{"class":201,"line":25},[199,2275,2276],{},"    autonumber\n",[199,2278,2279],{"class":201,"line":213},[199,2280,2281],{},"    participant C as Consumer login page\n",[199,2283,2284],{"class":201,"line":219},[199,2285,2286],{},"    participant L as Login service\n",[199,2288,2289],{"class":201,"line":225},[199,2290,2291],{},"    participant DB as MySQL\u003Cbr\u002F>(login_record)\n",[199,2293,2294],{"class":201,"line":231},[199,2295,2296],{},"    participant A as Admin detail page\n",[199,2298,2299],{"class":201,"line":237},[199,2300,2301],{},"    participant D as Customer detail service\n",[199,2303,2304],{"class":201,"line":243},[199,2305,2306],{},"    participant G as GeoIpService\u003Cbr\u002F>(in-memory mmdb)\n",[199,2308,2309],{"class":201,"line":249},[199,2310,461],{"emptyLinePlaceholder":30},[199,2312,2313],{"class":201,"line":255},[199,2314,2315],{},"    Note over G: Loads GeoLite2-Country.mmdb into memory at startup\n",[199,2317,2318],{"class":201,"line":261},[199,2319,461],{"emptyLinePlaceholder":30},[199,2321,2322],{"class":201,"line":267},[199,2323,2324],{},"    rect rgb(235, 244, 255)\n",[199,2326,2327],{"class":201,"line":273},[199,2328,2329],{},"    Note over C,DB: ① Capture the IP at login\n",[199,2331,2332],{"class":201,"line":279},[199,2333,2334],{},"    C->>L: POST \u002Fauth\u002Flogin\n",[199,2336,2337],{"class":201,"line":285},[199,2338,2339],{},"    L->>L: Take the real IP from X-Forwarded-For\n",[199,2341,2342],{"class":201,"line":651},[199,2343,2344],{},"    L->>DB: Write login_ip (refreshed on every login)\n",[199,2346,2347],{"class":201,"line":970},[199,2348,2349],{},"    L-->>C: token\n",[199,2351,2352],{"class":201,"line":976},[199,2353,2354],{},"    end\n",[199,2356,2357],{"class":201,"line":982},[199,2358,461],{"emptyLinePlaceholder":30},[199,2360,2361],{"class":201,"line":988},[199,2362,2363],{},"    rect rgb(255, 246, 232)\n",[199,2365,2366],{"class":201,"line":994},[199,2367,2368],{},"    Note over A,G: ② Resolve the country in real time on detail\n",[199,2370,2372],{"class":201,"line":2371},22,[199,2373,2374],{},"    A->>D: POST \u002Fadmin\u002Fcustomer\u002Fdetail\n",[199,2376,2378],{"class":201,"line":2377},23,[199,2379,2380],{},"    D->>DB: Query the user's latest login_ip\n",[199,2382,2384],{"class":201,"line":2383},24,[199,2385,2386],{},"    D->>G: resolveCountryIsoCode(ip)\n",[199,2388,2390],{"class":201,"line":2389},25,[199,2391,2392],{},"    G-->>D: \"US\" (private \u002F unavailable → null)\n",[199,2394,2396],{"class":201,"line":2395},26,[199,2397,2398],{},"    D-->>A: country: \"US\"\n",[199,2400,2402],{"class":201,"line":2401},27,[199,2403,2404],{},"    A->>A: Intl.DisplayNames → \"美国 \u002F United States\"\n",[199,2406,2408],{"class":201,"line":2407},28,[199,2409,2354],{},[17,2411,2412],{},"A few design points worth mentioning:",[17,2414,2415],{},[49,2416,2417],{},"1. The backend returns only the ISO code; the country name is left to the browser",[17,2419,2420,2421,2424],{},"The backend returns ",[100,2422,2423],{},"\"US\""," rather than \"United States\", and on the frontend one line of native API handles bilingual display for 200+ countries:",[191,2426,2430],{"className":2427,"code":2428,"language":2429,"meta":15,"style":15},"language-ts shiki shiki-themes github-light github-dark github-dark","new Intl.DisplayNames([locale], { type: \"region\" }).of(\"US\");\n\u002F\u002F zh → \"美国\", en → \"United States\"\n","ts",[100,2431,2432,2464],{"__ignoreMap":15},[199,2433,2434,2438,2441,2444,2447,2450,2453,2456,2459,2461],{"class":201,"line":202},[199,2435,2437],{"class":2436},"so5gQ","new",[199,2439,2440],{"class":1629}," Intl.",[199,2442,2443],{"class":1619},"DisplayNames",[199,2445,2446],{"class":1629},"([locale], { type: ",[199,2448,2449],{"class":1633},"\"region\"",[199,2451,2452],{"class":1629}," }).",[199,2454,2455],{"class":1619},"of",[199,2457,2458],{"class":1629},"(",[199,2460,2423],{"class":1633},[199,2462,2463],{"class":1629},");\n",[199,2465,2466],{"class":201,"line":25},[199,2467,2469],{"class":2468},"sCsY4","\u002F\u002F zh → \"美国\", en → \"United States\"\n",[17,2471,2472,2475],{},[49,2473,2474],{},"Zero i18n entries."," If the backend returned country names, I would either have to maintain a multilingual country table or push language negotiation into the API. Both are unnecessary complexity.",[17,2477,2478],{},[49,2479,2480],{},"2. Private IPs deliberately return null",[191,2482,2486],{"className":2483,"code":2484,"language":2485,"meta":15,"style":15},"language-java shiki shiki-themes github-light github-dark github-dark","if (addr.isLoopbackAddress() || addr.isSiteLocalAddress()) {\n    return null;   \u002F\u002F no false country during local debugging \u002F intranet load testing\n}\n","java",[100,2487,2488,2493,2498],{"__ignoreMap":15},[199,2489,2490],{"class":201,"line":202},[199,2491,2492],{},"if (addr.isLoopbackAddress() || addr.isSiteLocalAddress()) {\n",[199,2494,2495],{"class":201,"line":25},[199,2496,2497],{},"    return null;   \u002F\u002F no false country during local debugging \u002F intranet load testing\n",[199,2499,2500],{"class":201,"line":213},[199,2501,2502],{},"}\n",[17,2504,2505],{},[49,2506,2507],{},"3. A database load failure only degrades; it does not block startup",[17,2509,2510],{},"When the mmdb is missing or corrupted, the service logs an error, returns null for every country, and starts up as usual. This \"gentleness\" nearly came back to bite me later (see pitfall ①).",[58,2512,2514],{"id":2513},"_4-pitfalls-three-cases-of-works-fine-locally","4. Pitfalls: three cases of \"works fine locally\"",[2031,2516,2518],{"id":2517},"pitfall-the-pom-resource-whitelist-silently-swallowed-the-mmdb","Pitfall ①: the pom resource whitelist silently swallowed the mmdb",[17,2520,2521,2524,2525,2528],{},[49,2522,2523],{},"Symptom",": after deployment the API returned ",[100,2526,2527],{},"\"country\": null",", always null. Locally, resolving 8.8.8.8 → US worked perfectly.",[17,2530,2531,2532,346],{},"At the end of the investigation it turned out that resource packaging in the pom was in ",[49,2533,2534],{},"whitelist mode",[191,2536,2540],{"className":2537,"code":2538,"language":2539,"meta":15,"style":15},"language-xml shiki shiki-themes github-light github-dark github-dark","\u003Cresource>\n    \u003Cdirectory>src\u002Fmain\u002Fresources\u003C\u002Fdirectory>\n    \u003Cincludes>\n        \u003Cinclude>**\u002F*.xml\u003C\u002Finclude>\n        \u003Cinclude>**\u002F*.yml\u003C\u002Finclude>\n        \u003Cinclude>**\u002F*.properties\u003C\u002Finclude>\n        \u003C!-- mmdb? Not here -->\n    \u003C\u002Fincludes>\n\u003C\u002Fresource>\n","xml",[100,2541,2542,2547,2552,2557,2562,2567,2572,2577,2582],{"__ignoreMap":15},[199,2543,2544],{"class":201,"line":202},[199,2545,2546],{},"\u003Cresource>\n",[199,2548,2549],{"class":201,"line":25},[199,2550,2551],{},"    \u003Cdirectory>src\u002Fmain\u002Fresources\u003C\u002Fdirectory>\n",[199,2553,2554],{"class":201,"line":213},[199,2555,2556],{},"    \u003Cincludes>\n",[199,2558,2559],{"class":201,"line":219},[199,2560,2561],{},"        \u003Cinclude>**\u002F*.xml\u003C\u002Finclude>\n",[199,2563,2564],{"class":201,"line":225},[199,2565,2566],{},"        \u003Cinclude>**\u002F*.yml\u003C\u002Finclude>\n",[199,2568,2569],{"class":201,"line":231},[199,2570,2571],{},"        \u003Cinclude>**\u002F*.properties\u003C\u002Finclude>\n",[199,2573,2574],{"class":201,"line":237},[199,2575,2576],{},"        \u003C!-- mmdb? Not here -->\n",[199,2578,2579],{"class":201,"line":243},[199,2580,2581],{},"    \u003C\u002Fincludes>\n",[199,2583,2584],{"class":201,"line":249},[199,2585,2586],{},"\u003C\u002Fresource>\n",[17,2588,2589,2590,2593],{},"The mmdb had never made it into the jar. And the \"only degrade on load failure\" fault tolerance made this failure ",[49,2591,2592],{},"completely silent",": the service was healthy, the API returned 200, and country was simply always null. Adding one include line fixed it.",[424,2595,2596],{},[17,2597,2598],{},"Lesson: when you build graceful degradation into a feature, also think about \"how will I know it has degraded\". Silent degradation = a failure with a delayed fuse.",[2031,2600,2602],{"id":2601},"pitfall-a-wildcard-in-a-javadoc-blew-up-the-build","Pitfall ②: a wildcard in a javadoc blew up the build",[17,2604,2605,2606,2609],{},"After fixing pitfall ①, I jotted down a note in a javadoc along the lines of \"the pom whitelist must include ",[100,2607,2608],{},"**\u002F*.mmdb","\", and compilation failed immediately:",[191,2611,2614],{"className":2612,"code":2613,"language":1260,"meta":15},[1258],"illegal character: '）'\nclass, interface, or enum expected\n",[100,2615,2613],{"__ignoreMap":15},[17,2617,2618,2619,2621,2622,2625,2626,2629],{},"It took a long stare to see it: ",[100,2620,2608],{}," contains ",[100,2623,2624],{},"*\u002F",", ",[49,2627,2628],{},"the terminator of a block comment",". The comment was cut in half right there, and the rest of the sentence (written in Chinese, full-width punctuation included) became illegal characters. I changed it to a plain-text description, \"the mmdb suffix\", and moved on.",[2031,2631,2633],{"id":2632},"pitfall-always-null-in-the-test-environment-because-you-are-on-the-intranet","Pitfall ③: always null in the test environment, because you are on the intranet",[17,2635,2636,2637,2639,2640,1312],{},"After logging in again, ",[100,2638,1983],{}," finally had a value, but country was still null. A look at the database: ",[100,2641,2642],{},"login_ip = 10.x.x.x",[17,2644,2645,2646,2649],{},"Traffic from the office network to the test environment goes over an internal path. The public IP is lost midway, and what gets written is the address of some NAT hop in between, which is then correctly intercepted by the \"no false country for private IPs\" logic I wrote myself. ",[49,2647,2648],{},"Not a bug, but a property of the path",": from the office intranet, country is always empty in the test environment. To see the real behavior, access it from a phone on mobile data, or simply change the IP in the database to simulate it.",[58,2651,2653],{"id":2652},"_5-improving-the-design-a-scheduled-job-that-swaps-the-brain-every-week-for-the-offline-database","5. Improving the design: a scheduled job that \"swaps the brain every week\" for the offline database",[2031,2655,2657],{"id":2656},"why-this-is-a-must","Why this is a must",[17,2659,2660,2661,2664],{},"The biggest weakness of an offline database: ",[49,2662,2663],{},"it is a snapshot",". Which country an IP range belongs to keeps changing as carriers buy and sell ranges. MaxMind updates the database twice a week, while the file bundled into the jar is frozen at the moment of the build. Without an update mechanism:",[348,2666,2667,2674],{},[315,2668,2669,2670,2673],{},"Accuracy ",[49,2671,2672],{},"degrades slowly"," over time, and with no errors at all, so you will not notice",[315,2675,2676],{},"The only way to replace the database is to ship a release, which ties \"swap a data file\" to \"change the code\"",[2031,2678,2680],{"id":2679},"how-often-to-update-weekly-but-take-a-look-every-day","How often to update: weekly, but take a look every day",[17,2682,2683,2684,2687],{},"Country-level data changes by less than a few tenths of a percent per month, so in terms of accuracy a monthly update would be enough. The real reason I settled on ",[49,2685,2686],{},"weekly"," is operational:",[424,2689,2690],{},[17,2691,2692,2695],{},[49,2693,2694],{},"The more frequent the updates, the sooner a silent failure like \"the download path quietly broke\" gets exposed."," (The lesson from pitfall ① was still fresh.)",[17,2697,2698,2699,1312],{},"The implementation uses a small trick: ",[49,2700,2701],{},"cron fires every day, but only actually downloads once 7 days have passed",[191,2703,2705],{"className":193,"code":2704,"language":195,"meta":15,"style":15},"flowchart TD\n    A[\"Triggered daily at 4:00\"] --> B{\"enabled?\"}\n    B -- No --> Z1[\"Return immediately\"]\n    B -- Yes --> C{\"External mmdb\u003Cbr\u002F>last written ≥ 7 days ago?\"}\n    C -- \"No (6 days a week)\" --> Z2[\"Skip, cost ≈ reading one file attribute\"]\n    C -- \"Yes \u002F file missing\" --> D[\"Fetch the new database from the data source into a temp file\u003Cbr\u002F>(~8.4MB)\"]\n    D --> E[\"Atomically replace the external file\u003Cbr\u002F>ATOMIC_MOVE, fall back to a plain move on failure\"]\n    E --> F{\"reload validation:\u003Cbr\u002F>① Country-type database?\u003Cbr\u002F>② 8.8.8.8 → US?\"}\n    F -- Pass --> G[\"In-memory reference switches to the new database\u003Cbr\u002F>old one closed, takes effect hot ✅\"]\n    F -- Fail --> H[\"Keep the old database in memory\u003Cbr\u002F>error log\"]\n    D -. Download fails .-> I[\"error log, keep the old database\"]\n    I --> J[\"Automatic retry at 4:00 the next day\u003Cbr\u002F>(file is still 'older than 7 days')\"]\n    H --> J\n",[100,2706,2707,2711,2716,2721,2726,2731,2736,2741,2746,2751,2756,2761,2766],{"__ignoreMap":15},[199,2708,2709],{"class":201,"line":202},[199,2710,205],{},[199,2712,2713],{"class":201,"line":25},[199,2714,2715],{},"    A[\"Triggered daily at 4:00\"] --> B{\"enabled?\"}\n",[199,2717,2718],{"class":201,"line":213},[199,2719,2720],{},"    B -- No --> Z1[\"Return immediately\"]\n",[199,2722,2723],{"class":201,"line":219},[199,2724,2725],{},"    B -- Yes --> C{\"External mmdb\u003Cbr\u002F>last written ≥ 7 days ago?\"}\n",[199,2727,2728],{"class":201,"line":225},[199,2729,2730],{},"    C -- \"No (6 days a week)\" --> Z2[\"Skip, cost ≈ reading one file attribute\"]\n",[199,2732,2733],{"class":201,"line":231},[199,2734,2735],{},"    C -- \"Yes \u002F file missing\" --> D[\"Fetch the new database from the data source into a temp file\u003Cbr\u002F>(~8.4MB)\"]\n",[199,2737,2738],{"class":201,"line":237},[199,2739,2740],{},"    D --> E[\"Atomically replace the external file\u003Cbr\u002F>ATOMIC_MOVE, fall back to a plain move on failure\"]\n",[199,2742,2743],{"class":201,"line":243},[199,2744,2745],{},"    E --> F{\"reload validation:\u003Cbr\u002F>① Country-type database?\u003Cbr\u002F>② 8.8.8.8 → US?\"}\n",[199,2747,2748],{"class":201,"line":249},[199,2749,2750],{},"    F -- Pass --> G[\"In-memory reference switches to the new database\u003Cbr\u002F>old one closed, takes effect hot ✅\"]\n",[199,2752,2753],{"class":201,"line":255},[199,2754,2755],{},"    F -- Fail --> H[\"Keep the old database in memory\u003Cbr\u002F>error log\"]\n",[199,2757,2758],{"class":201,"line":261},[199,2759,2760],{},"    D -. Download fails .-> I[\"error log, keep the old database\"]\n",[199,2762,2763],{"class":201,"line":267},[199,2764,2765],{},"    I --> J[\"Automatic retry at 4:00 the next day\u003Cbr\u002F>(file is still 'older than 7 days')\"]\n",[199,2767,2768],{"class":201,"line":273},[199,2769,2770],{},"    H --> J\n",[17,2772,2773,2774,2777,2778,2781],{},"Why not simply ",[100,2775,2776],{},"cron = every 7 days","? Because ",[49,2779,2780],{},"checking daily + downloading only when due = a free retry mechanism",". Downloads can fail, so there has to be a retry, and here, if a download fails one day, it is naturally made up the next, without writing a single line of retry code.",[2031,2783,2785],{"id":2784},"three-engineering-details-of-the-hot-reload","Three engineering details of the hot reload",[17,2787,2788],{},[49,2789,2790],{},"1. Double validation: no pass, no swap",[17,2792,2793,2794,2797,2798,2801],{},"A new database is only allowed into memory if it is both \"a Country-type database\" and \"resolves the sample IP ",[100,2795,2796],{},"8.8.8.8"," to ",[100,2799,2800],{},"US","\". Downloaded half of a corrupted file? Validation fails and the old database stays in service.",[17,2803,2804],{},[49,2805,2806,2807,2810],{},"2. A ",[100,2808,2809],{},"volatile"," reference + atomic swap",[191,2812,2814],{"className":2483,"code":2813,"language":2485,"meta":15,"style":15},"private volatile DatabaseReader reader;\n\npublic synchronized boolean reload(File file) {\n    DatabaseReader candidate = build(file);\n    if (!isValid(candidate)) { candidate.close(); return false; }\n    DatabaseReader old = reader;\n    reader = candidate;      \u002F\u002F swap the reference; immediately visible to query threads\n    old.close();             \u002F\u002F an in-flight query hitting the closed old database → falls into catch and returns null, unnoticed\n    return true;\n}\n",[100,2815,2816,2821,2825,2830,2835,2840,2845,2850,2855,2860],{"__ignoreMap":15},[199,2817,2818],{"class":201,"line":202},[199,2819,2820],{},"private volatile DatabaseReader reader;\n",[199,2822,2823],{"class":201,"line":25},[199,2824,461],{"emptyLinePlaceholder":30},[199,2826,2827],{"class":201,"line":213},[199,2828,2829],{},"public synchronized boolean reload(File file) {\n",[199,2831,2832],{"class":201,"line":219},[199,2833,2834],{},"    DatabaseReader candidate = build(file);\n",[199,2836,2837],{"class":201,"line":225},[199,2838,2839],{},"    if (!isValid(candidate)) { candidate.close(); return false; }\n",[199,2841,2842],{"class":201,"line":231},[199,2843,2844],{},"    DatabaseReader old = reader;\n",[199,2846,2847],{"class":201,"line":237},[199,2848,2849],{},"    reader = candidate;      \u002F\u002F swap the reference; immediately visible to query threads\n",[199,2851,2852],{"class":201,"line":243},[199,2853,2854],{},"    old.close();             \u002F\u002F an in-flight query hitting the closed old database → falls into catch and returns null, unnoticed\n",[199,2856,2857],{"class":201,"line":249},[199,2858,2859],{},"    return true;\n",[199,2861,2862],{"class":201,"line":255},[199,2863,2502],{},[17,2865,2866],{},[49,2867,2868,2869,2872],{},"3. ",[100,2870,2871],{},"FileMode.MEMORY"," to avoid file locks",[17,2874,2875,2876,2879,2880,2882],{},"DatabaseReader defaults to MEMORY_MAPPED (memory mapping), and on Windows a mapped file ",[49,2877,2878],{},"cannot be replaced",", so hot reload in the development environment would simply fall over. Switching to ",[100,2881,2871],{}," reads the whole file onto the heap (it is only 8MB anyway), holds no handle on the file, and lets it be replaced freely.",[17,2884,2885,2886,1312],{},"This goes together with the reworked loading priority: ",[49,2887,2888],{},"external file first, the copy bundled in the jar as the fallback",[348,2890,2891,2894,2900],{},[315,2892,2893],{},"First deployment: the external directory is empty → use the database bundled in the jar → the job downloads and writes the file at 4:00 that day",[315,2895,2896,2897],{},"Afterwards: always use the latest external database, and ",[49,2898,2899],{},"releases never have to worry about swapping the mmdb again",[315,2901,2902],{},"External file corrupted: a load failure at startup automatically falls back to the bundled database, so there is always a safety net",[58,2904,2906],{"id":2905},"_6-honest-boundaries-what-this-approach-cannot-do","6. Honest boundaries: what this approach cannot do",[105,2908,2909,2919],{},[108,2910,2911],{},[111,2912,2913,2916],{},[114,2914,2915],{},"Limitation",[114,2917,2918],{},"Details",[121,2920,2921,2929,2941,2949,2957],{},[111,2922,2923,2926],{},[126,2924,2925],{},"Country ≠ where the user really is",[126,2927,2928],{},"With a VPN\u002Fproxy you see the exit country; anycast IPs (such as 1.1.1.1) have no attribution and return null",[111,2930,2931,2934],{},[126,2932,2933],{},"The head of the XFF chain can be forged",[126,2935,2936,2937,2940],{},"Fine for display, but it must ",[49,2938,2939],{},"never"," be used for risk control, compliance, or purchase-restriction decisions",[111,2942,2943,2946],{},[126,2944,2945],{},"It only represents \"the most recent login\"",[126,2947,2948],{},"When the user travels or switches nodes, the country jumps with them; it is neither the place of registration nor the place of residence",[111,2950,2951,2954],{},[126,2952,2953],{},"Cannot filter by country in SQL",[126,2955,2956],{},"The country is not persisted. The day a PM asks to \"filter customers by country\" or wants a country distribution report is the signal to switch to the \"resolve at login and persist\" approach (GeoIpService can be reused as is, so the migration cost is low)",[111,2958,2959,2962],{},[126,2960,2961],{},"Gap for existing users",[126,2963,2964],{},"country is empty for existing users until their next login; channels where the real IP is unavailable (such as messages forwarded by a bot) stay empty forever",[58,2966,2968],{"id":2967},"_7-takeaways","7. Takeaways",[312,2970,2971,2977,2983,2992,2998,3004],{},[315,2972,2973,2976],{},[49,2974,2975],{},"Probe before you choose; do not guess the architecture from documentation."," Two DNS queries + one curl ruled out the most tempting option A in five minutes, far faster than discussing it in a meeting",[315,2978,2979,2982],{},[49,2980,2981],{},"If \"an existing column + compute at query time\" solves it, do not rush into DDL."," Data that is never persisted never needs to be cleaned up",[315,2984,2985,2991],{},[49,2986,2987,2988,1312],{},"Leave display mappings like country names to ",[100,2989,2990],{},"Intl.DisplayNames"," Browsers natively ship entries for 200+ countries in every language",[315,2993,2994,2997],{},[49,2995,2996],{},"Graceful degradation must come with \"how will I know it has degraded\"."," Otherwise you get the illusion of health from pitfall ①",[315,2999,3000,3003],{},[49,3001,3002],{},"Offline data = a snapshot, and a snapshot needs a mechanism to keep it fresh."," \"Check daily + download when due\" gets retries for free in the dumbest possible way",[315,3005,3006,3007,3009,3010,3012],{},"Do not let ",[100,3008,2624],{}," appear in a javadoc, even when it is growing inside the wildcard ",[100,3011,2608],{}," :)",[1042,3014,3015],{},"html .light .shiki span {color: var(--shiki-light);background: var(--shiki-light-bg);font-style: var(--shiki-light-font-style);font-weight: var(--shiki-light-font-weight);text-decoration: var(--shiki-light-text-decoration);}html.light .shiki span {color: var(--shiki-light);background: var(--shiki-light-bg);font-style: var(--shiki-light-font-style);font-weight: var(--shiki-light-font-weight);text-decoration: var(--shiki-light-text-decoration);}html .default .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html.dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html pre.shiki code .so5gQ, html code.shiki .so5gQ{--shiki-light:#D73A49;--shiki-default:#F97583;--shiki-dark:#F97583}html pre.shiki code .slsVL, html code.shiki .slsVL{--shiki-light:#24292E;--shiki-default:#E1E4E8;--shiki-dark:#E1E4E8}html pre.shiki code .shcOC, html code.shiki .shcOC{--shiki-light:#6F42C1;--shiki-default:#B392F0;--shiki-dark:#B392F0}html pre.shiki code .sfrk1, html code.shiki .sfrk1{--shiki-light:#032F62;--shiki-default:#9ECBFF;--shiki-dark:#9ECBFF}html pre.shiki code .sCsY4, html code.shiki .sCsY4{--shiki-light:#6A737D;--shiki-default:#6A737D;--shiki-dark:#6A737D}",{"title":15,"searchDepth":25,"depth":25,"links":3017},[3018,3019,3025,3026,3031,3036,3037],{"id":1990,"depth":25,"text":1991},{"id":2028,"depth":25,"text":2029,"children":3020},[3021,3022,3023,3024],{"id":2033,"depth":213,"text":2034},{"id":2131,"depth":213,"text":2132},{"id":2160,"depth":213,"text":2161},{"id":2182,"depth":213,"text":2183},{"id":2254,"depth":25,"text":2255},{"id":2513,"depth":25,"text":2514,"children":3027},[3028,3029,3030],{"id":2517,"depth":213,"text":2518},{"id":2601,"depth":213,"text":2602},{"id":2632,"depth":213,"text":2633},{"id":2652,"depth":25,"text":2653,"children":3032},[3033,3034,3035],{"id":2656,"depth":213,"text":2657},{"id":2679,"depth":213,"text":2680},{"id":2784,"depth":213,"text":2785},{"id":2905,"depth":25,"text":2906},{"id":2967,"depth":25,"text":2968},"2026-07-22","The customer detail page needed to show a user's country. I resolve the login IP locally with the GeoLite2 offline database, with zero DDL and zero outbound calls, plus a weekly hot-reload job to keep the data fresh.","\u002Farticles\u002Fgeoip-user-country.svg",{},"\u002Farticles\u002Fgeoip-user-country","9",{"title":1973,"description":3039},{"loc":3042},"articles\u002Fgeoip-user-country",[3048,3049],"Full-Stack","Backend","LawAdj75AECq5aCoChBsVixPronL38oPV7uXmXST1gI",{"id":3052,"title":3053,"body":3054,"date":5011,"description":5012,"extension":28,"head":27,"image":5013,"meta":5014,"navigation":30,"ogImage":27,"path":5015,"rating":225,"readingTime":5016,"robots":27,"schemaOrg":27,"seo":5017,"sitemap":5018,"stem":5019,"tags":5020,"__hash__":5021},"articles_en\u002Farticles\u002Fmessenger-one-click-auth.md","One Click to Connect Messenger: 6 Engineering Decisions Behind Facebook One-Click Authorization",{"type":7,"value":3055,"toc":4994},[3056,3059,3062,3076,3080,3091,3174,3180,3184,3187,3407,3410,3591,3595,3615,3624,3630,3633,3806,3824,3828,3831,3896,3901,3907,3988,3991,4059,4063,4074,4115,4118,4201,4211,4215,4233,4236,4335,4371,4375,4379,4386,4435,4442,4446,4456,4460,4526,4530,4547,4586,4597,4676,4698,4737,4741,4744,4881,4892,4896,4937,4941,4991],[17,3057,3058],{},"Before this change, a merchant who wanted to connect their Facebook Page to our Messenger AI assistant had to wait for someone on the ops side to fetch the credentials and configure them by hand, once per merchant. I wanted to turn that into a single button the merchant clicks in the admin console.",[17,3060,3061],{},"The button is the easy part. The hard part is the trade-offs in the chain behind it. This post walks through the 6 decisions I had to make.",[1036,3063,3064,3073],{},[17,3065,3066,3069,3070,3072],{},[49,3067,3068],{},"In one sentence",": a merchant clicks \"Connect Facebook\" once in the admin console and their Facebook Page is connected to the Messenger AI assistant, replacing the old process where ops wrote Page credentials in by hand. The frontend only produces a ",[100,3071,100],{},"; exchanging the token, validating permissions, fetching Pages, subscribing to the webhook and storing the encrypted credential all happen on the server in one pass. This post breaks down the 6 places in that chain where a real trade-off was needed. The last one is the single-callback webhook problem caused by test and production sharing one Meta App.",[17,3074,3075],{},"Product names, configuration IDs, API paths and config keys have been generalized. The code shown is an excerpt of the core logic.",[58,3077,3079],{"id":3078},"_1-background-from-ops-edits-the-database-to-the-merchant-clicks-once","1. Background: from \"ops edits the database\" to \"the merchant clicks once\"",[17,3081,3082,3083,3086,3087,3090],{},"The platform is a multi-channel conversational AI assistant (Python FastAPI). The Messenger channel had been running in production for a while: after verifying the webhook signature, it looks up the merchant table by the ",[100,3084,3085],{},"entry.id"," in the envelope (the Page ID) to get credentials, then drives the AI reply. Tenant credentials are cached for 24 hours. The problem was ",[49,3088,3089],{},"how merchants got connected",": the Page ID, Page token and authorizer columns in the merchant table were all written by ops, by hand.",[105,3092,3093,3106],{},[108,3094,3095],{},[111,3096,3097,3100,3103],{},[114,3098,3099],{},"Gap",[114,3101,3102],{},"Impact",[114,3104,3105],{},"What this work does",[121,3107,3108,3119,3130,3141,3152,3163],{},[111,3109,3110,3113,3116],{},[126,3111,3112],{},"No self-service authorization for merchants",[126,3114,3115],{},"Ops has to fetch and configure a Page token by hand for every merchant",[126,3117,3118],{},"One-click authorization in the admin console, with automatic subscription and persistence on the server",[111,3120,3121,3124,3127],{},[126,3122,3123],{},"Credential storage needs to follow one security baseline",[126,3125,3126],{},"All channel credentials should share the same key management",[126,3128,3129],{},"Encrypted storage, ciphertext with a version prefix, older format still readable",[111,3131,3132,3135,3138],{},[126,3133,3134],{},"No Page name, no connection time",[126,3136,3137],{},"The admin console cannot show what is connected",[126,3139,3140],{},"Two new columns, returned by the status endpoint",[111,3142,3143,3146,3149],{},[126,3144,3145],{},"No way to unbind",[126,3147,3148],{},"Changing or disabling a Page needs ops",[126,3150,3151],{},"An unbind endpoint: best-effort unsubscribe, clear the columns, clear the cache",[111,3153,3154,3157,3160],{},[126,3155,3156],{},"Messenger and WhatsApp lived in two Meta Apps",[126,3158,3159],{},"Two SDK initializations conflict on the same page",[126,3161,3162],{},"Consolidate into one App; the frontend reuses one SDK instance",[111,3164,3165,3168,3171],{},[126,3166,3167],{},"The Page webhook is a single app-level callback URL",[126,3169,3170],{},"When test and production share an App, only one environment receives messages",[126,3172,3173],{},"Forward the whole webhook payload across environments",[17,3175,3176,3177,3179],{},"The constraints were clear too. Multi-tenant routing stays the same and still looks up by ",[100,3178,3085],{},", so the existing Messenger consumer path can use the new credentials with zero changes. The Java business backend also needs zero changes, because channel credentials have nothing to do with login identity and the agent service already reads and writes the merchant table directly.",[58,3181,3183],{"id":3182},"_2-the-big-picture-the-chain-in-one-diagram","2. The big picture: the chain in one diagram",[17,3185,3186],{},"Blue is new in this work, yellow is modified, everything else already existed.",[191,3188,3190],{"className":193,"code":3189,"language":195,"meta":15,"style":15},"flowchart LR\n  subgraph Admin[\"Merchant admin console · Vue 3\"]\n    FC[\"Facebook channel card\u003Cbr>Disconnected · Page select · Connected\"]\n    HL[\"Login hook\u003Cbr>Meta JS SDK · FB.login\"]\n    HB[\"Binding hook\u003Cbr>status · connect · select · unbind\"]\n  end\n  subgraph Meta[\"Meta platform · one App\"]\n    SDK[\"Authorization dialog\u003Cbr>Facebook Login for Business · config_id\"]\n    GRAPH[\"Graph API\u003Cbr>oauth\u002Faccess_token · debug_token\u003Cbr>\u002FPAGE_ID · subscribed_apps\"]\n    WH[\"Page Webhook\u003Cbr>messages · messaging_postbacks\"]\n  end\n  subgraph Core[\"Agent service · Python FastAPI\"]\n    PA[\"Channel auth endpoints\u003Cbr>Session auth · IP rate limit · error mapping\"]\n    PS[\"Auth orchestration service\u003Cbr>Exchange · validate · fetch Pages · subscribe · persist\"]\n    MC[\"Webhook controller\u003Cbr>HMAC verify · ACK first · cross-env forward\"]\n    FM[\"Messenger message service\u003Cbr>Tenant lookup by page_id · AI reply\"]\n  end\n  DB[(\"MySQL merchant table\u003Cbr>five messenger columns\")]\n  RD[(\"Redis\u003Cbr>Selection stash · tenant cache · merchant lock\")]\n  PEER[\"Peer environment\u003Cbr>Webhook controller\"]\n  FC --> HL\n  HL \u003C--> SDK\n  HL -->|code| HB\n  HB -->|session token and code| PA\n  PA --> PS\n  PS \u003C--> GRAPH\n  PS --> DB\n  PS --> RD\n  WH --> MC\n  MC --> FM\n  FM --> DB\n  FM --> RD\n  MC -.->|forward whole payload for unknown Pages| PEER\n  style FC fill:#dbeafe,stroke:#155dfc\n  style HL fill:#dbeafe,stroke:#155dfc\n  style HB fill:#dbeafe,stroke:#155dfc\n  style PA fill:#dbeafe,stroke:#155dfc\n  style PS fill:#dbeafe,stroke:#155dfc\n  style MC fill:#fef3c7,stroke:#d97706\n  style FM fill:#fef3c7,stroke:#d97706\n  style DB fill:#fef3c7,stroke:#d97706\n",[100,3191,3192,3196,3201,3206,3211,3216,3221,3226,3231,3236,3241,3245,3250,3255,3260,3265,3270,3274,3279,3284,3289,3294,3299,3304,3309,3314,3319,3324,3329,3335,3341,3347,3353,3359,3365,3371,3377,3383,3389,3395,3401],{"__ignoreMap":15},[199,3193,3194],{"class":201,"line":202},[199,3195,1201],{},[199,3197,3198],{"class":201,"line":25},[199,3199,3200],{},"  subgraph Admin[\"Merchant admin console · Vue 3\"]\n",[199,3202,3203],{"class":201,"line":213},[199,3204,3205],{},"    FC[\"Facebook channel card\u003Cbr>Disconnected · Page select · Connected\"]\n",[199,3207,3208],{"class":201,"line":219},[199,3209,3210],{},"    HL[\"Login hook\u003Cbr>Meta JS SDK · FB.login\"]\n",[199,3212,3213],{"class":201,"line":225},[199,3214,3215],{},"    HB[\"Binding hook\u003Cbr>status · connect · select · unbind\"]\n",[199,3217,3218],{"class":201,"line":231},[199,3219,3220],{},"  end\n",[199,3222,3223],{"class":201,"line":237},[199,3224,3225],{},"  subgraph Meta[\"Meta platform · one App\"]\n",[199,3227,3228],{"class":201,"line":243},[199,3229,3230],{},"    SDK[\"Authorization dialog\u003Cbr>Facebook Login for Business · config_id\"]\n",[199,3232,3233],{"class":201,"line":249},[199,3234,3235],{},"    GRAPH[\"Graph API\u003Cbr>oauth\u002Faccess_token · debug_token\u003Cbr>\u002FPAGE_ID · subscribed_apps\"]\n",[199,3237,3238],{"class":201,"line":255},[199,3239,3240],{},"    WH[\"Page Webhook\u003Cbr>messages · messaging_postbacks\"]\n",[199,3242,3243],{"class":201,"line":261},[199,3244,3220],{},[199,3246,3247],{"class":201,"line":267},[199,3248,3249],{},"  subgraph Core[\"Agent service · Python FastAPI\"]\n",[199,3251,3252],{"class":201,"line":273},[199,3253,3254],{},"    PA[\"Channel auth endpoints\u003Cbr>Session auth · IP rate limit · error mapping\"]\n",[199,3256,3257],{"class":201,"line":279},[199,3258,3259],{},"    PS[\"Auth orchestration service\u003Cbr>Exchange · validate · fetch Pages · subscribe · persist\"]\n",[199,3261,3262],{"class":201,"line":285},[199,3263,3264],{},"    MC[\"Webhook controller\u003Cbr>HMAC verify · ACK first · cross-env forward\"]\n",[199,3266,3267],{"class":201,"line":651},[199,3268,3269],{},"    FM[\"Messenger message service\u003Cbr>Tenant lookup by page_id · AI reply\"]\n",[199,3271,3272],{"class":201,"line":970},[199,3273,3220],{},[199,3275,3276],{"class":201,"line":976},[199,3277,3278],{},"  DB[(\"MySQL merchant table\u003Cbr>five messenger columns\")]\n",[199,3280,3281],{"class":201,"line":982},[199,3282,3283],{},"  RD[(\"Redis\u003Cbr>Selection stash · tenant cache · merchant lock\")]\n",[199,3285,3286],{"class":201,"line":988},[199,3287,3288],{},"  PEER[\"Peer environment\u003Cbr>Webhook controller\"]\n",[199,3290,3291],{"class":201,"line":994},[199,3292,3293],{},"  FC --> HL\n",[199,3295,3296],{"class":201,"line":2371},[199,3297,3298],{},"  HL \u003C--> SDK\n",[199,3300,3301],{"class":201,"line":2377},[199,3302,3303],{},"  HL -->|code| HB\n",[199,3305,3306],{"class":201,"line":2383},[199,3307,3308],{},"  HB -->|session token and code| PA\n",[199,3310,3311],{"class":201,"line":2389},[199,3312,3313],{},"  PA --> PS\n",[199,3315,3316],{"class":201,"line":2395},[199,3317,3318],{},"  PS \u003C--> GRAPH\n",[199,3320,3321],{"class":201,"line":2401},[199,3322,3323],{},"  PS --> DB\n",[199,3325,3326],{"class":201,"line":2407},[199,3327,3328],{},"  PS --> RD\n",[199,3330,3332],{"class":201,"line":3331},29,[199,3333,3334],{},"  WH --> MC\n",[199,3336,3338],{"class":201,"line":3337},30,[199,3339,3340],{},"  MC --> FM\n",[199,3342,3344],{"class":201,"line":3343},31,[199,3345,3346],{},"  FM --> DB\n",[199,3348,3350],{"class":201,"line":3349},32,[199,3351,3352],{},"  FM --> RD\n",[199,3354,3356],{"class":201,"line":3355},33,[199,3357,3358],{},"  MC -.->|forward whole payload for unknown Pages| PEER\n",[199,3360,3362],{"class":201,"line":3361},34,[199,3363,3364],{},"  style FC fill:#dbeafe,stroke:#155dfc\n",[199,3366,3368],{"class":201,"line":3367},35,[199,3369,3370],{},"  style HL fill:#dbeafe,stroke:#155dfc\n",[199,3372,3374],{"class":201,"line":3373},36,[199,3375,3376],{},"  style HB fill:#dbeafe,stroke:#155dfc\n",[199,3378,3380],{"class":201,"line":3379},37,[199,3381,3382],{},"  style PA fill:#dbeafe,stroke:#155dfc\n",[199,3384,3386],{"class":201,"line":3385},38,[199,3387,3388],{},"  style PS fill:#dbeafe,stroke:#155dfc\n",[199,3390,3392],{"class":201,"line":3391},39,[199,3393,3394],{},"  style MC fill:#fef3c7,stroke:#d97706\n",[199,3396,3398],{"class":201,"line":3397},40,[199,3399,3400],{},"  style FM fill:#fef3c7,stroke:#d97706\n",[199,3402,3404],{"class":201,"line":3403},41,[199,3405,3406],{},"  style DB fill:#fef3c7,stroke:#d97706\n",[17,3408,3409],{},"The main authorization sequence (the exactly-one-Page branch and the multi-Page branch):",[191,3411,3413],{"className":193,"code":3412,"language":195,"meta":15,"style":15},"sequenceDiagram\n  autonumber\n  participant M as Merchant\n  participant A as Admin console\n  participant F as Meta auth dialog\n  participant C as Auth orchestration service\n  participant G as Meta Graph API\n  participant D as MySQL merchant table\n  participant R as Redis\n  M->>A: Click Connect Facebook\n  A->>F: FB.login with config_id, response_type code\n  F-->>M: Pick business portfolio and Pages, then authorize\n  F-->>A: authResponse.code\n  A->>C: POST connect with code\n  C->>G: oauth\u002Faccess_token to exchange the token\n  C->>G: debug_token to check app_id and scopes\n  Note over C: Skip long-lived exchange if expires_at is 0 or at least 1 day remains\n  C->>G: Fetch Page name and Page token one by one from granular_scopes\n  alt Exactly 1 Page\n    C->>G: POST subscribed_apps for messages and messaging_postbacks\n    C->>D: Single UPDATE writes five columns, token stored encrypted\n    C->>R: Clear tenant cache for old and new Page\n    C-->>A: connected\n  else Multiple Pages\n    C->>R: Stash encrypted Page list with a short TTL\n    C-->>A: page_select_required with pages and selection_token\n    M->>A: Pick a Page in the card\n    A->>C: POST select\n    C->>G: POST subscribed_apps\n    C->>D: Persist and clear cache\n    C-->>A: connected\n  else 0 Pages\n    C-->>A: 403 no_page\n  end\n  A->>C: GET status\n  C-->>A: connected with page_id and page_name\n",[100,3414,3415,3419,3423,3428,3433,3438,3443,3448,3453,3458,3463,3468,3473,3478,3483,3488,3493,3498,3503,3508,3513,3518,3523,3528,3533,3538,3543,3548,3553,3558,3563,3567,3572,3577,3581,3586],{"__ignoreMap":15},[199,3416,3417],{"class":201,"line":202},[199,3418,892],{},[199,3420,3421],{"class":201,"line":25},[199,3422,897],{},[199,3424,3425],{"class":201,"line":213},[199,3426,3427],{},"  participant M as Merchant\n",[199,3429,3430],{"class":201,"line":219},[199,3431,3432],{},"  participant A as Admin console\n",[199,3434,3435],{"class":201,"line":225},[199,3436,3437],{},"  participant F as Meta auth dialog\n",[199,3439,3440],{"class":201,"line":231},[199,3441,3442],{},"  participant C as Auth orchestration service\n",[199,3444,3445],{"class":201,"line":237},[199,3446,3447],{},"  participant G as Meta Graph API\n",[199,3449,3450],{"class":201,"line":243},[199,3451,3452],{},"  participant D as MySQL merchant table\n",[199,3454,3455],{"class":201,"line":249},[199,3456,3457],{},"  participant R as Redis\n",[199,3459,3460],{"class":201,"line":255},[199,3461,3462],{},"  M->>A: Click Connect Facebook\n",[199,3464,3465],{"class":201,"line":261},[199,3466,3467],{},"  A->>F: FB.login with config_id, response_type code\n",[199,3469,3470],{"class":201,"line":267},[199,3471,3472],{},"  F-->>M: Pick business portfolio and Pages, then authorize\n",[199,3474,3475],{"class":201,"line":273},[199,3476,3477],{},"  F-->>A: authResponse.code\n",[199,3479,3480],{"class":201,"line":279},[199,3481,3482],{},"  A->>C: POST connect with code\n",[199,3484,3485],{"class":201,"line":285},[199,3486,3487],{},"  C->>G: oauth\u002Faccess_token to exchange the token\n",[199,3489,3490],{"class":201,"line":651},[199,3491,3492],{},"  C->>G: debug_token to check app_id and scopes\n",[199,3494,3495],{"class":201,"line":970},[199,3496,3497],{},"  Note over C: Skip long-lived exchange if expires_at is 0 or at least 1 day remains\n",[199,3499,3500],{"class":201,"line":976},[199,3501,3502],{},"  C->>G: Fetch Page name and Page token one by one from granular_scopes\n",[199,3504,3505],{"class":201,"line":982},[199,3506,3507],{},"  alt Exactly 1 Page\n",[199,3509,3510],{"class":201,"line":988},[199,3511,3512],{},"    C->>G: POST subscribed_apps for messages and messaging_postbacks\n",[199,3514,3515],{"class":201,"line":994},[199,3516,3517],{},"    C->>D: Single UPDATE writes five columns, token stored encrypted\n",[199,3519,3520],{"class":201,"line":2371},[199,3521,3522],{},"    C->>R: Clear tenant cache for old and new Page\n",[199,3524,3525],{"class":201,"line":2377},[199,3526,3527],{},"    C-->>A: connected\n",[199,3529,3530],{"class":201,"line":2383},[199,3531,3532],{},"  else Multiple Pages\n",[199,3534,3535],{"class":201,"line":2389},[199,3536,3537],{},"    C->>R: Stash encrypted Page list with a short TTL\n",[199,3539,3540],{"class":201,"line":2395},[199,3541,3542],{},"    C-->>A: page_select_required with pages and selection_token\n",[199,3544,3545],{"class":201,"line":2401},[199,3546,3547],{},"    M->>A: Pick a Page in the card\n",[199,3549,3550],{"class":201,"line":2407},[199,3551,3552],{},"    A->>C: POST select\n",[199,3554,3555],{"class":201,"line":3331},[199,3556,3557],{},"    C->>G: POST subscribed_apps\n",[199,3559,3560],{"class":201,"line":3337},[199,3561,3562],{},"    C->>D: Persist and clear cache\n",[199,3564,3565],{"class":201,"line":3343},[199,3566,3527],{},[199,3568,3569],{"class":201,"line":3349},[199,3570,3571],{},"  else 0 Pages\n",[199,3573,3574],{"class":201,"line":3355},[199,3575,3576],{},"    C-->>A: 403 no_page\n",[199,3578,3579],{"class":201,"line":3361},[199,3580,3220],{},[199,3582,3583],{"class":201,"line":3367},[199,3584,3585],{},"  A->>C: GET status\n",[199,3587,3588],{"class":201,"line":3373},[199,3589,3590],{},"  C-->>A: connected with page_id and page_name\n",[58,3592,3594],{"id":3593},"_3-decision-1-the-authorization-entry-point-where-the-frontend-only-produces-a-code","3. Decision 1: the authorization entry point, where the frontend only produces a code",[17,3596,3597,3600,3601,3604,3605,3608,3609,3612,3613,1312],{},[49,3598,3599],{},"Chosen",": reuse ",[100,3602,3603],{},"FB.login"," from the Meta JS SDK with a Facebook Login for Business configuration (",[100,3606,3607],{},"config_id","), with ",[100,3610,3611],{},"response_type"," set to ",[100,3614,100],{},[17,3616,3617,3620,3621,3623],{},[49,3618,3619],{},"Why",": once Messenger and WhatsApp Embedded Signup share one Meta App, the page needs only one SDK instance. The ",[100,3622,100],{}," comes straight back in the callback, so there is no callback page, no redirect URI allowlist, no state check and no popup lifecycle to manage.",[17,3625,3626,3629],{},[49,3627,3628],{},"Rejected",": building our own OAuth redirect and callback page.",[17,3631,3632],{},"The frontend hook is deliberately small. Its only job is to get hold of the code:",[191,3634,3636],{"className":2427,"code":3635,"language":2429,"meta":15,"style":15},"window.FB.login(\n  response => {\n    if (disposed || settledRound) return;   \u002F\u002F once guard: consume the callback once per round, never after unmount\n    settledRound = true;\n    const code = response.authResponse?.code;\n    if (!code) { options.onCancel?.(); return; }   \u002F\u002F dialog closed or authorization denied: empty authResponse means cancel\n    options.onCode(code).catch(() => options.onError?.(\"submit_failed\"));\n  },\n  { config_id: configId, response_type: \"code\", override_default_response_type: true }\n);\n",[100,3637,3638,3655,3667,3690,3704,3718,3745,3780,3785,3802],{"__ignoreMap":15},[199,3639,3640,3643,3647,3649,3652],{"class":201,"line":202},[199,3641,3642],{"class":1629},"window.",[199,3644,3646],{"class":3645},"suiK_","FB",[199,3648,1312],{"class":1629},[199,3650,3651],{"class":1619},"login",[199,3653,3654],{"class":1629},"(\n",[199,3656,3657,3661,3664],{"class":201,"line":25},[199,3658,3660],{"class":3659},"sQHwn","  response",[199,3662,3663],{"class":2436}," =>",[199,3665,3666],{"class":1629}," {\n",[199,3668,3669,3672,3675,3678,3681,3684,3687],{"class":201,"line":213},[199,3670,3671],{"class":2436},"    if",[199,3673,3674],{"class":1629}," (disposed ",[199,3676,3677],{"class":2436},"||",[199,3679,3680],{"class":1629}," settledRound) ",[199,3682,3683],{"class":2436},"return",[199,3685,3686],{"class":1629},";   ",[199,3688,3689],{"class":2468},"\u002F\u002F once guard: consume the callback once per round, never after unmount\n",[199,3691,3692,3695,3698,3701],{"class":201,"line":219},[199,3693,3694],{"class":1629},"    settledRound ",[199,3696,3697],{"class":2436},"=",[199,3699,3700],{"class":3645}," true",[199,3702,3703],{"class":1629},";\n",[199,3705,3706,3709,3712,3715],{"class":201,"line":225},[199,3707,3708],{"class":2436},"    const",[199,3710,3711],{"class":3645}," code",[199,3713,3714],{"class":2436}," =",[199,3716,3717],{"class":1629}," response.authResponse?.code;\n",[199,3719,3720,3722,3725,3728,3731,3734,3737,3739,3742],{"class":201,"line":231},[199,3721,3671],{"class":2436},[199,3723,3724],{"class":1629}," (",[199,3726,3727],{"class":2436},"!",[199,3729,3730],{"class":1629},"code) { options.",[199,3732,3733],{"class":1619},"onCancel",[199,3735,3736],{"class":1629},"?.(); ",[199,3738,3683],{"class":2436},[199,3740,3741],{"class":1629},"; }   ",[199,3743,3744],{"class":2468},"\u002F\u002F dialog closed or authorization denied: empty authResponse means cancel\n",[199,3746,3747,3750,3753,3756,3759,3762,3765,3768,3771,3774,3777],{"class":201,"line":237},[199,3748,3749],{"class":1629},"    options.",[199,3751,3752],{"class":1619},"onCode",[199,3754,3755],{"class":1629},"(code).",[199,3757,3758],{"class":1619},"catch",[199,3760,3761],{"class":1629},"(() ",[199,3763,3764],{"class":2436},"=>",[199,3766,3767],{"class":1629}," options.",[199,3769,3770],{"class":1619},"onError",[199,3772,3773],{"class":1629},"?.(",[199,3775,3776],{"class":1633},"\"submit_failed\"",[199,3778,3779],{"class":1629},"));\n",[199,3781,3782],{"class":201,"line":243},[199,3783,3784],{"class":1629},"  },\n",[199,3786,3787,3790,3793,3796,3799],{"class":201,"line":249},[199,3788,3789],{"class":1629},"  { config_id: configId, response_type: ",[199,3791,3792],{"class":1633},"\"code\"",[199,3794,3795],{"class":1629},", override_default_response_type: ",[199,3797,3798],{"class":3645},"true",[199,3800,3801],{"class":1629}," }\n",[199,3803,3804],{"class":201,"line":255},[199,3805,2463],{"class":1629},[17,3807,3808,3809,3812,3813,3816,3817,3819,3820,3823],{},"A few edges that are easy to miss. If the SDK has already been loaded by the WhatsApp card, the hook reuses ",[100,3810,3811],{},"window.FB"," and does not set ",[100,3814,3815],{},"fbAsyncInit",", so it cannot overwrite an initialization callback that the other side still has in flight. SDK loading has a timeout. If ",[100,3818,3607],{}," is not configured, the hook says \"not configured in this environment\" and never loads the SDK. When the server exchanges the code for a token it sends no ",[100,3821,3822],{},"redirect_uri",", the same as Embedded Signup.",[58,3825,3827],{"id":3826},"_4-decision-2-token-type-pick-the-system-user-token-but-keep-the-code-indifferent-to-token-type","4. Decision 2: token type. Pick the system user token, but keep the code indifferent to token type",[17,3829,3830],{},"The Facebook Login for Business configuration decides which kind of token you get after authorization, and the two differ quite a bit:",[105,3832,3833,3846],{},[108,3834,3835],{},[111,3836,3837,3840,3843],{},[114,3838,3839],{},"Dimension",[114,3841,3842],{},"User access token",[114,3844,3845],{},"System user access token",[121,3847,3848,3859,3874,3885],{},[111,3849,3850,3853,3856],{},[126,3851,3852],{},"Owner",[126,3854,3855],{},"The personal account of the employee who authorized",[126,3857,3858],{},"The merchant's business; Meta creates a system user under it automatically",[111,3860,3861,3864,3867],{},[126,3862,3863],{},"Lifetime",[126,3865,3866],{},"About 1 hour at first, must be exchanged for a 60-day long-lived token",[126,3868,3869,3870,3873],{},"Can be set to never expire, ",[100,3871,3872],{},"expires_at"," is 0",[111,3875,3876,3879,3882],{},[126,3877,3878],{},"What invalidates it",[126,3880,3881],{},"Password change, the employee leaving, account security checks",[126,3883,3884],{},"Business-level events, unlikely",[111,3886,3887,3890,3893],{},[126,3888,3889],{},"Prerequisite",[126,3891,3892],{},"Low",[126,3894,3895],{},"The merchant needs a business portfolio with the Page added to it",[17,3897,3898,3900],{},[49,3899,3599],{},": a system user token that never expires. The connection belongs to the merchant's business, not to one employee's account. WhatsApp onboarding already requires a business portfolio, so this adds no new prerequisite.",[17,3902,3903,3906],{},[49,3904,3905],{},"The orchestration still works with both token types",", so switching the configuration in the Meta dashboard later needs no code change. The only difference is whether to do the long-lived exchange. Everything else is shared:",[312,3908,3909,3947,3956,3980],{},[315,3910,3911,3914,3915,3918,3919,3922,3923,3926,3927,2625,3930,3933,3934,3937,3938,2625,3940,3933,3943,3946],{},[100,3912,3913],{},"debug_token"," validation: ",[100,3916,3917],{},"is_valid"," is true, ",[100,3920,3921],{},"app_id"," matches our App, and ",[100,3924,3925],{},"scopes"," includes ",[100,3928,3929],{},"pages_show_list",[100,3931,3932],{},"pages_messaging"," and ",[100,3935,3936],{},"pages_manage_metadata",". Any one missing means rejection. The same call also returns the ",[100,3939,3872],{},[100,3941,3942],{},"user_id",[100,3944,3945],{},"granular_scopes"," needed later, so one call serves three purposes.",[315,3948,3949,3950,3952,3953,3955],{},"The long-lived decision looks only at ",[100,3951,3872],{}," from ",[100,3954,3913],{},". It is a pure function, which makes it easy to unit test (code below).",[315,3957,3958,3959,3962,3963,3965,3966,3968,3969,3971,3972,3975,3976,3979],{},"The Page list comes first from the ",[100,3960,3961],{},"target_ids"," that ",[100,3964,3932],{}," was explicitly granted in ",[100,3967,3945],{},". Each Page is fetched with its own GET to get the name and Page token, and one failure is skipped instead of rejecting the whole round. Only when ",[100,3970,3961],{}," is empty (a user token where \"all Pages\" was ticked) does it fall back to ",[100,3973,3974],{},"\u002Fme\u002Faccounts",", with a cap on pagination. Pages whose ",[100,3977,3978],{},"tasks"," exists but contains none of MANAGE, MODERATE or MESSAGING are dropped, because binding them would not let us send messages anyway.",[315,3981,3982,3983,3952,3985,3987],{},"The authorizer identifier is the ",[100,3984,3942],{},[100,3986,3913],{},". With a system user token that is the id of the system user Meta generated.",[17,3989,3990],{},"The long-lived decision function from step 2:",[191,3992,3994],{"className":384,"code":3993,"language":386,"meta":15,"style":15},"def _needs_long_lived_exchange(expires_at) -> bool:\n    \"\"\"0 = never expires (long-term system user token), no exchange; at least 1 day remaining, no exchange;\n    anything else (short-lived user token) must be exchanged, or the derived Page token is short-lived too;\n    a missing or invalid field is treated as short-lived (better one exchange too many)\"\"\"\n    if expires_at is None:\n        return True\n    try:\n        exp = int(expires_at)\n    except (TypeError, ValueError):\n        return True\n    if exp == 0:\n        return False\n    return exp - time.time() \u003C 24 * 3600\n",[100,3995,3996,4001,4006,4011,4016,4021,4026,4031,4036,4041,4045,4050,4054],{"__ignoreMap":15},[199,3997,3998],{"class":201,"line":202},[199,3999,4000],{},"def _needs_long_lived_exchange(expires_at) -> bool:\n",[199,4002,4003],{"class":201,"line":25},[199,4004,4005],{},"    \"\"\"0 = never expires (long-term system user token), no exchange; at least 1 day remaining, no exchange;\n",[199,4007,4008],{"class":201,"line":213},[199,4009,4010],{},"    anything else (short-lived user token) must be exchanged, or the derived Page token is short-lived too;\n",[199,4012,4013],{"class":201,"line":219},[199,4014,4015],{},"    a missing or invalid field is treated as short-lived (better one exchange too many)\"\"\"\n",[199,4017,4018],{"class":201,"line":225},[199,4019,4020],{},"    if expires_at is None:\n",[199,4022,4023],{"class":201,"line":231},[199,4024,4025],{},"        return True\n",[199,4027,4028],{"class":201,"line":237},[199,4029,4030],{},"    try:\n",[199,4032,4033],{"class":201,"line":243},[199,4034,4035],{},"        exp = int(expires_at)\n",[199,4037,4038],{"class":201,"line":249},[199,4039,4040],{},"    except (TypeError, ValueError):\n",[199,4042,4043],{"class":201,"line":255},[199,4044,4025],{},[199,4046,4047],{"class":201,"line":261},[199,4048,4049],{},"    if exp == 0:\n",[199,4051,4052],{"class":201,"line":267},[199,4053,481],{},[199,4055,4056],{"class":201,"line":273},[199,4057,4058],{},"    return exp - time.time() \u003C 24 * 3600\n",[58,4060,4062],{"id":4061},"_5-decision-3-meta-tells-you-which-pages-you-can-access-not-which-one-the-merchant-wants-to-bind","5. Decision 3: Meta tells you which Pages you can access, not which one the merchant wants to bind",[17,4064,4065,4066,3933,4068,4070,4071],{},"This is the least intuitive point in the whole chain. The Page checkboxes in the authorization dialog are multi-select and remembered, and both ",[100,4067,3945],{},[100,4069,3974],{}," return a set. The product rule, however, is one Page per merchant. ",[49,4072,4073],{},"Which one to bind has to be decided on our side.",[348,4075,4076,4079,4086,4109],{},[315,4077,4078],{},"Exactly 1 in the set: bind it directly.",[315,4080,4081,4082,4085],{},"Empty set: 403 ",[100,4083,4084],{},"no_page",". The frontend explains that a business portfolio admin is required and the Page must be in the portfolio.",[315,4087,4088,4089,4092,4093,4096,4097,4100,4101,4104,4105,4108],{},"More than 1 in the set: return ",[100,4090,4091],{},"page_select_required"," with ",[100,4094,4095],{},"pages"," (id and name only, no tokens) and a ",[100,4098,4099],{},"selection_token",". The full list including Page tokens is encrypted and stashed in Redis with a short TTL, under a key built from the merchant id plus a high-entropy random string, so it cannot be used across merchants. After the merchant picks one in the card, the frontend calls ",[100,4102,4103],{},"select",". The server checks that the stash exists, that it decrypts, and that the chosen ",[100,4106,4107],{},"page_id"," is in the list, then deletes the stash once the bind succeeds.",[315,4110,4111,4114],{},[49,4112,4113],{},"Rejected: refusing outright when there are multiple Pages."," Because the authorization is remembered, the checkbox screen does not appear again on retry, and the merchant would be stuck at the authorization step.",[17,4116,4117],{},"So the frontend card has three states, and \"Page select\" is purely local:",[191,4119,4121],{"className":193,"code":4120,"language":195,"meta":15,"style":15},"stateDiagram-v2\n  [*] --> disconnected: Fetch status on mount\n  disconnected --> authorizing: Click Connect Facebook\n  authorizing --> disconnected: Dialog closed or denied, SDK load failed, config_id missing\n  authorizing --> connected: connect returns connected, exactly 1 Page granted\n  authorizing --> pageSelect: connect returns page_select_required, more than 1 Page\n  authorizing --> disconnected: connect returns disconnected, or 403 and 409 rejection\n  pageSelect --> connected: select returns connected\n  pageSelect --> pageSelect: select 409 ownership conflict, keep list and pick again\n  pageSelect --> disconnected: Cancel, stash expired or other failure\n  connected --> disconnected: unbind after Disconnect is confirmed\n  note right of pageSelect\n    Local frontend state, lost on refresh.\n    Meta only returns the set of Pages the App can access,\n    so choosing among several is up to us\n  end note\n",[100,4122,4123,4127,4132,4137,4142,4147,4152,4157,4162,4167,4172,4177,4182,4187,4192,4197],{"__ignoreMap":15},[199,4124,4125],{"class":201,"line":202},[199,4126,730],{},[199,4128,4129],{"class":201,"line":25},[199,4130,4131],{},"  [*] --> disconnected: Fetch status on mount\n",[199,4133,4134],{"class":201,"line":213},[199,4135,4136],{},"  disconnected --> authorizing: Click Connect Facebook\n",[199,4138,4139],{"class":201,"line":219},[199,4140,4141],{},"  authorizing --> disconnected: Dialog closed or denied, SDK load failed, config_id missing\n",[199,4143,4144],{"class":201,"line":225},[199,4145,4146],{},"  authorizing --> connected: connect returns connected, exactly 1 Page granted\n",[199,4148,4149],{"class":201,"line":231},[199,4150,4151],{},"  authorizing --> pageSelect: connect returns page_select_required, more than 1 Page\n",[199,4153,4154],{"class":201,"line":237},[199,4155,4156],{},"  authorizing --> disconnected: connect returns disconnected, or 403 and 409 rejection\n",[199,4158,4159],{"class":201,"line":243},[199,4160,4161],{},"  pageSelect --> connected: select returns connected\n",[199,4163,4164],{"class":201,"line":249},[199,4165,4166],{},"  pageSelect --> pageSelect: select 409 ownership conflict, keep list and pick again\n",[199,4168,4169],{"class":201,"line":255},[199,4170,4171],{},"  pageSelect --> disconnected: Cancel, stash expired or other failure\n",[199,4173,4174],{"class":201,"line":261},[199,4175,4176],{},"  connected --> disconnected: unbind after Disconnect is confirmed\n",[199,4178,4179],{"class":201,"line":267},[199,4180,4181],{},"  note right of pageSelect\n",[199,4183,4184],{"class":201,"line":273},[199,4185,4186],{},"    Local frontend state, lost on refresh.\n",[199,4188,4189],{"class":201,"line":279},[199,4190,4191],{},"    Meta only returns the set of Pages the App can access,\n",[199,4193,4194],{"class":201,"line":285},[199,4195,4196],{},"    so choosing among several is up to us\n",[199,4198,4199],{"class":201,"line":651},[199,4200,800],{},[17,4202,4203,4204,4207,4208,4210],{},"The ",[100,4205,4206],{},"status"," endpoint returns only connected and disconnected. The \"Page select\" state is lost on refresh; once the stash expires, ",[100,4209,4103],{}," is rejected and the card goes back to disconnected, and the merchant simply authorizes again.",[58,4212,4214],{"id":4213},"_6-decision-4-subscribe-to-the-webhook-first-then-persist","6. Decision 4: subscribe to the webhook first, then persist",[17,4216,4217,4218,4221,4222,3933,4225,4228,4229,4232],{},"Binding means POST to that Page's ",[100,4219,4220],{},"subscribed_apps"," (subscribing to ",[100,4223,4224],{},"messages",[100,4226,4227],{},"messaging_postbacks","), then persist, then clear the routing cache. ",[49,4230,4231],{},"The order is subscribe first, persist second."," If the subscription fails, nothing is written, and the merchant clicks Connect again to retry the whole thing (Meta remembers the authorization, so the second time is very fast). The state needs only connected and disconnected, with no partial state and completion flow like WhatsApp has. What I rejected is persisting first and subscribing second.",[17,4234,4235],{},"The part that took real thought is the failure paths:",[191,4237,4239],{"className":193,"code":4238,"language":195,"meta":15,"style":15},"flowchart TD\n  S[\"Start binding the target Page\"] --> O{\"Page already owned by another merchant?\"}\n  O -->|Yes| C1[\"409 ownership conflict\"]\n  O -->|No| SUB[\"POST subscribed_apps to subscribe\"]\n  SUB -->|Failed| D1[\"Return disconnected\u003Cbr>Nothing written, whole flow retryable\"]\n  SUB -->|OK| W[\"Single UPDATE writes all five columns\u003Cbr>token encrypted\"]\n  W -->|Unique key violation| C2[\"409 ownership conflict\u003Cbr>No unsubscribe, the subscription belongs to the other merchant\"]\n  W -->|Other failure| COMP[\"Compensate: unsubscribe the new Page just subscribed\u003Cbr>Old binding left untouched\"]\n  COMP --> D2[\"Return disconnected\"]\n  W -->|OK| OLD{\"Same merchant switched Page?\"}\n  OLD -->|Yes| UNSUB[\"Best-effort unsubscribe of the old Page\"]\n  UNSUB --> OK[\"connected\"]\n  OLD -->|No| OK\n  W -.->|finally: always clear tenant cache for old and new Page| CC[\"Redis tenant cache\"]\n  style C1 fill:#fee2e2,stroke:#dc2626\n  style C2 fill:#fee2e2,stroke:#dc2626\n  style D1 fill:#fef3c7,stroke:#d97706\n  style D2 fill:#fef3c7,stroke:#d97706\n  style OK fill:#dcfce7,stroke:#16a34a\n",[100,4240,4241,4245,4250,4255,4260,4265,4270,4275,4280,4285,4290,4295,4300,4305,4310,4315,4320,4325,4330],{"__ignoreMap":15},[199,4242,4243],{"class":201,"line":202},[199,4244,205],{},[199,4246,4247],{"class":201,"line":25},[199,4248,4249],{},"  S[\"Start binding the target Page\"] --> O{\"Page already owned by another merchant?\"}\n",[199,4251,4252],{"class":201,"line":213},[199,4253,4254],{},"  O -->|Yes| C1[\"409 ownership conflict\"]\n",[199,4256,4257],{"class":201,"line":219},[199,4258,4259],{},"  O -->|No| SUB[\"POST subscribed_apps to subscribe\"]\n",[199,4261,4262],{"class":201,"line":225},[199,4263,4264],{},"  SUB -->|Failed| D1[\"Return disconnected\u003Cbr>Nothing written, whole flow retryable\"]\n",[199,4266,4267],{"class":201,"line":231},[199,4268,4269],{},"  SUB -->|OK| W[\"Single UPDATE writes all five columns\u003Cbr>token encrypted\"]\n",[199,4271,4272],{"class":201,"line":237},[199,4273,4274],{},"  W -->|Unique key violation| C2[\"409 ownership conflict\u003Cbr>No unsubscribe, the subscription belongs to the other merchant\"]\n",[199,4276,4277],{"class":201,"line":243},[199,4278,4279],{},"  W -->|Other failure| COMP[\"Compensate: unsubscribe the new Page just subscribed\u003Cbr>Old binding left untouched\"]\n",[199,4281,4282],{"class":201,"line":249},[199,4283,4284],{},"  COMP --> D2[\"Return disconnected\"]\n",[199,4286,4287],{"class":201,"line":255},[199,4288,4289],{},"  W -->|OK| OLD{\"Same merchant switched Page?\"}\n",[199,4291,4292],{"class":201,"line":261},[199,4293,4294],{},"  OLD -->|Yes| UNSUB[\"Best-effort unsubscribe of the old Page\"]\n",[199,4296,4297],{"class":201,"line":267},[199,4298,4299],{},"  UNSUB --> OK[\"connected\"]\n",[199,4301,4302],{"class":201,"line":273},[199,4303,4304],{},"  OLD -->|No| OK\n",[199,4306,4307],{"class":201,"line":279},[199,4308,4309],{},"  W -.->|finally: always clear tenant cache for old and new Page| CC[\"Redis tenant cache\"]\n",[199,4311,4312],{"class":201,"line":285},[199,4313,4314],{},"  style C1 fill:#fee2e2,stroke:#dc2626\n",[199,4316,4317],{"class":201,"line":651},[199,4318,4319],{},"  style C2 fill:#fee2e2,stroke:#dc2626\n",[199,4321,4322],{"class":201,"line":970},[199,4323,4324],{},"  style D1 fill:#fef3c7,stroke:#d97706\n",[199,4326,4327],{"class":201,"line":976},[199,4328,4329],{},"  style D2 fill:#fef3c7,stroke:#d97706\n",[199,4331,4332],{"class":201,"line":982},[199,4333,4334],{},"  style OK fill:#dcfce7,stroke:#16a34a\n",[348,4336,4337,4343,4353,4359],{},[315,4338,4339,4342],{},[49,4340,4341],{},"Persistence fails",": compensate by unsubscribing the new Page that was just subscribed, so Meta does not keep pushing events nobody owns. The old binding is left as it was and keeps serving. Rebinding the same Page does not unsubscribe, because the subscription still belongs to this merchant's existing binding.",[315,4344,4345,4348,4349,4352],{},[49,4346,4347],{},"Persistence hits the unique key",": treat it as a 409 ownership conflict and do ",[49,4350,4351],{},"not"," compensate with an unsubscribe. That Page's subscription belongs to the other merchant.",[315,4354,4355,4358],{},[49,4356,4357],{},"Same merchant switches Page",": unsubscribe the old Page, best-effort, only after persistence succeeds. The order cannot be reversed. Unsubscribe first, and a failed write leaves the old Page without service while the database still points at it. If the old token fails to decrypt, the unsubscribe is just skipped, and the leftover subscription on Meta's side is covered by the token becoming invalid.",[315,4360,4361,4367,4368,4370],{},[49,4362,4363,4364],{},"Cache clearing runs unconditionally in ",[100,4365,4366],{},"finally",", for both the old and the new ",[100,4369,4107],{},". The new Page may still have a cache entry from before another merchant unbound it, and the old Page's cache no longer matches the database. Without clearing, the old credential keeps routing until the cache entry expires.",[58,4372,4374],{"id":4373},"_7-decision-5-credential-encryption-page-ownership-and-concurrency","7. Decision 5: credential encryption, Page ownership and concurrency",[2031,4376,4378],{"id":4377},"_71-versioned-ciphertext-prefix-older-format-still-readable","7.1 Versioned ciphertext prefix, older format still readable",[17,4380,4381,4382,4385],{},"The Page token is encrypted with Fernet before it is stored, and the ciphertext carries an ",[100,4383,4384],{},"enc:v1:"," prefix. The key falls under the same key management as the other channel credentials. The read side has only two rules:",[191,4387,4389],{"className":384,"code":4388,"language":386,"meta":15,"style":15},"def decrypt_value(stored: str, key: str) -> str:\n    if not stored:\n        return stored or \"\"\n    if not stored.startswith(\"enc:v1:\"):\n        return stored                       # no version prefix: read as the older format for compatibility\n    try:\n        return Fernet(key.encode()).decrypt(stored[len(\"enc:v1:\"):].encode(\"ascii\")).decode(\"utf-8\")\n    except (InvalidToken, ValueError) as e:\n        raise CryptoError(\"凭据解密失败\") from e   # prefixed but undecryptable must raise (fail closed); never send ciphertext out as if it were plaintext\n",[100,4390,4391,4396,4401,4406,4411,4416,4420,4425,4430],{"__ignoreMap":15},[199,4392,4393],{"class":201,"line":202},[199,4394,4395],{},"def decrypt_value(stored: str, key: str) -> str:\n",[199,4397,4398],{"class":201,"line":25},[199,4399,4400],{},"    if not stored:\n",[199,4402,4403],{"class":201,"line":213},[199,4404,4405],{},"        return stored or \"\"\n",[199,4407,4408],{"class":201,"line":219},[199,4409,4410],{},"    if not stored.startswith(\"enc:v1:\"):\n",[199,4412,4413],{"class":201,"line":225},[199,4414,4415],{},"        return stored                       # no version prefix: read as the older format for compatibility\n",[199,4417,4418],{"class":201,"line":231},[199,4419,4030],{},[199,4421,4422],{"class":201,"line":237},[199,4423,4424],{},"        return Fernet(key.encode()).decrypt(stored[len(\"enc:v1:\"):].encode(\"ascii\")).decode(\"utf-8\")\n",[199,4426,4427],{"class":201,"line":243},[199,4428,4429],{},"    except (InvalidToken, ValueError) as e:\n",[199,4431,4432],{"class":201,"line":249},[199,4433,4434],{},"        raise CryptoError(\"凭据解密失败\") from e   # prefixed but undecryptable must raise (fail closed); never send ciphertext out as if it were plaintext\n",[17,4436,4437,4438,4441],{},"A version number in the prefix helps in both directions: data in the older format does not need a one-off migration, and a future algorithm change can move over smoothly with ",[100,4439,4440],{},"enc:v2",". Fernet ciphertext is longer than the plaintext, so the column has to be widened at the same time. When the Messenger message service reads a token that fails to decrypt, it treats the Page as not connected.",[2031,4443,4445],{"id":4444},"_72-page-ownership-check-before-write-with-a-unique-key-as-the-backstop","7.2 Page ownership: check before write, with a unique key as the backstop",[17,4447,4448,4449,4451,4452,4455],{},"A Page belongs to exactly one merchant, guaranteed by a unique key on the Page ID column of the merchant table. Before binding, the service looks up ownership by ",[100,4450,4107],{}," and returns 409 straight away if another merchant has it. If someone else grabs the Page in the window between the check and the write, the ",[100,4453,4454],{},"IntegrityError"," raised by the unique key maps to the same conflict code. In the \"Page select\" state the frontend keeps the list on a 409 so the merchant can pick another; any other error clears it and returns to disconnected.",[2031,4457,4459],{"id":4458},"_73-concurrency-merchant-lock-atomic-write-of-the-whole-group-conditional-unbind","7.3 Concurrency: merchant lock, atomic write of the whole group, conditional unbind",[105,4461,4462,4475],{},[108,4463,4464],{},[111,4465,4466,4469,4472],{},[114,4467,4468],{},"Measure",[114,4470,4471],{},"Problem it solves",[114,4473,4474],{},"Implementation",[121,4476,4477,4488,4512],{},[111,4478,4479,4482,4485],{},[126,4480,4481],{},"Per-merchant serial lock",[126,4483,4484],{},"Two concurrent binds for one merchant can put A's token and B's Page in the same row; an unbind can wipe a new binding that is in progress",[126,4486,4487],{},"Redis SET NX with a short TTL that covers the worst-case duration of one bind. While held, return 409 \"binding in progress\". When the Redis behind the lock is unavailable there is a choice between fail open and fail closed. I chose availability and log an error, so a cache outage does not block merchant onboarding, and the two rows below protect data correctness",[111,4489,4490,4493,4496],{},[126,4491,4492],{},"Single UPDATE writing all five columns",[126,4494,4495],{},"The ORM pattern of loading an object, changing attributes and committing only updates dirty columns, so concurrency can produce a mixed row of \"Page B + token A\". A unique index cannot catch a mismatch inside one row",[126,4497,4498,4499,2625,4501,4504,4505,4508,4509,4511],{},"The repository layer explicitly writes ",[100,4500,4107],{},[100,4502,4503],{},"page_name",", token, owner and ",[100,4506,4507],{},"connected_at"," as one atomic overwrite, with ",[100,4510,4507],{}," taken from the database's current time",[111,4513,4514,4517,4520],{},[126,4515,4516],{},"Conditional update on unbind",[126,4518,4519],{},"A concurrent rebind between the read and the clear means an unconditional clear wipes the binding someone else just wrote",[126,4521,4522,4523,4525],{},"The WHERE clause includes the ",[100,4524,4107],{}," that was read, as a version condition. Zero rows matched returns a failure that is handled as safe to retry. The five columns are set to NULL, not empty strings: a unique index allows many NULL rows, and empty strings would collide",[58,4527,4529],{"id":4528},"_8-decision-6-one-meta-app-has-only-one-page-webhook-callback-url","8. Decision 6: one Meta App has only one Page webhook callback URL",[17,4531,4532,4533,4536,4537,4539,4540,4542,4543,4546],{},"After consolidating into one Meta App, a new problem showed up: ",[49,4534,4535],{},"the Page webhook is a single callback URL at the app level",". WhatsApp lets you override the callback URL per WABA when calling ",[100,4538,4220],{},". Messenger's ",[100,4541,4220],{}," accepts only ",[100,4544,4545],{},"subscribed_fields"," and has no such option. With test and production sharing one App, only one environment can receive messages.",[105,4548,4549,4558],{},[108,4550,4551],{},[111,4552,4553,4555],{},[114,4554,2043],{},[114,4556,4557],{},"Problem",[121,4559,4560,4568,4576],{},[111,4561,4562,4565],{},[126,4563,4564],{},"Switch the callback URL between the two environments by hand",[126,4566,4567],{},"Only one environment works at any given time",[111,4569,4570,4573],{},[126,4571,4572],{},"Keep the old App for the test environment",[126,4574,4575],{},"The frontend has to maintain two App IDs, which brings back the SDK initialization conflict",[111,4577,4578,4583],{},[126,4579,4580],{},[49,4581,4582],{},"Point the callback at production permanently, and have production forward events for Pages it cannot find to test, unchanged",[126,4584,4585],{},"Both environments work at once; with no forward URL configured, behavior is unchanged",[17,4587,4588,4589,4592,4593,4596],{},"The key constraint: ",[100,4590,4591],{},"X-Hub-Signature-256"," covers the entire request body, so the body cannot be split or rewritten. The design is therefore \"",[49,4594,4595],{},"forward the whole payload, and each environment only handles the Pages in its own database","\":",[191,4598,4600],{"className":193,"code":4599,"language":195,"meta":15,"style":15},"flowchart TD\n  W[\"Meta Page webhook\u003Cbr>POST to production\"] --> S{\"X-Hub-Signature-256\u003Cbr>HMAC-SHA256 verification\"}\n  S -->|Fails| X[\"Drop, return 200\"]\n  S -->|Passes| ACK[\"Parse payload, return 200 immediately\u003Cbr>Everything after runs as a background task\"]\n  ACK --> P{\"Forward URL configured\u003Cbr>and no forwarded-marker header?\"}\n  P -->|No| L[\"Handle every entry locally\u003Cbr>Same behavior as before\"]\n  P -->|Yes| T[\"Look up this environment's tenant by entry.id\u003Cbr>Cache first, merchant table on miss\"]\n  T --> K[\"Connected entries\u003Cbr>Deduplicate, then dispatch AI reply\"]\n  T --> U{\"Any entry not connected here?\"}\n  U -->|No| E[\"Done\"]\n  U -->|Yes| FWD[\"Original body, original signature header, plus marker header\u003Cbr>Forward to peer asynchronously with a timeout, failures only logged\"]\n  FWD --> PEER[\"Peer verifies with the same app_secret\u003Cbr>Handles only its own Pages, never forwards again\"]\n  style ACK fill:#dbeafe,stroke:#155dfc\n  style FWD fill:#fef3c7,stroke:#d97706\n  style PEER fill:#fef3c7,stroke:#d97706\n",[100,4601,4602,4606,4611,4616,4621,4626,4631,4636,4641,4646,4651,4656,4661,4666,4671],{"__ignoreMap":15},[199,4603,4604],{"class":201,"line":202},[199,4605,205],{},[199,4607,4608],{"class":201,"line":25},[199,4609,4610],{},"  W[\"Meta Page webhook\u003Cbr>POST to production\"] --> S{\"X-Hub-Signature-256\u003Cbr>HMAC-SHA256 verification\"}\n",[199,4612,4613],{"class":201,"line":213},[199,4614,4615],{},"  S -->|Fails| X[\"Drop, return 200\"]\n",[199,4617,4618],{"class":201,"line":219},[199,4619,4620],{},"  S -->|Passes| ACK[\"Parse payload, return 200 immediately\u003Cbr>Everything after runs as a background task\"]\n",[199,4622,4623],{"class":201,"line":225},[199,4624,4625],{},"  ACK --> P{\"Forward URL configured\u003Cbr>and no forwarded-marker header?\"}\n",[199,4627,4628],{"class":201,"line":231},[199,4629,4630],{},"  P -->|No| L[\"Handle every entry locally\u003Cbr>Same behavior as before\"]\n",[199,4632,4633],{"class":201,"line":237},[199,4634,4635],{},"  P -->|Yes| T[\"Look up this environment's tenant by entry.id\u003Cbr>Cache first, merchant table on miss\"]\n",[199,4637,4638],{"class":201,"line":243},[199,4639,4640],{},"  T --> K[\"Connected entries\u003Cbr>Deduplicate, then dispatch AI reply\"]\n",[199,4642,4643],{"class":201,"line":249},[199,4644,4645],{},"  T --> U{\"Any entry not connected here?\"}\n",[199,4647,4648],{"class":201,"line":255},[199,4649,4650],{},"  U -->|No| E[\"Done\"]\n",[199,4652,4653],{"class":201,"line":261},[199,4654,4655],{},"  U -->|Yes| FWD[\"Original body, original signature header, plus marker header\u003Cbr>Forward to peer asynchronously with a timeout, failures only logged\"]\n",[199,4657,4658],{"class":201,"line":267},[199,4659,4660],{},"  FWD --> PEER[\"Peer verifies with the same app_secret\u003Cbr>Handles only its own Pages, never forwards again\"]\n",[199,4662,4663],{"class":201,"line":273},[199,4664,4665],{},"  style ACK fill:#dbeafe,stroke:#155dfc\n",[199,4667,4668],{"class":201,"line":279},[199,4669,4670],{},"  style FWD fill:#fef3c7,stroke:#d97706\n",[199,4672,4673],{"class":201,"line":285},[199,4674,4675],{},"  style PEER fill:#fef3c7,stroke:#d97706\n",[348,4677,4678,4685,4688,4691],{},[315,4679,4680,4681,4684],{},"The forwarded request carries the original body and the original signature header, plus one marker header. The peer verifies the signature with the same App's ",[100,4682,4683],{},"app_secret"," and handles only the Pages in its own database. A request with the marker header is never forwarded again, which prevents loops.",[315,4686,4687],{},"Forwarding has a timeout, and a failure is only logged. It does not affect this environment returning 200 to Meta.",[315,4689,4690],{},"The tenant pre-check uses the cache and only queries the database on a miss. A Page that is not connected here is not logged as an error, because a Page from the other environment is expected to be missing from this database.",[315,4692,4693,4694,4697],{},"Meta requires the webhook to return 200 quickly and retries on timeout as a failure, so the team designed for a 5-second budget: ACK right after signature verification and parsing, and run tenant splitting, forwarding, message deduplication (",[100,4695,4696],{},"mid"," SET NX with a short TTL) and dispatch as a background task. Neither a cold cache nor a slow query can hold up the response.",[191,4699,4701],{"className":384,"code":4700,"language":386,"meta":15,"style":15},"headers = {\n    \"Content-Type\": \"application\u002Fjson\",\n    \"X-Hub-Signature-256\": signature,   # pass the original signature header through unchanged\n    \"X-Peer-Forwarded\": \"1\",            # marker header (illustrative name): the peer never forwards again when it sees this\n}\nasync with httpx.AsyncClient(timeout=5) as client:\n    resp = await client.post(forward_url, content=body, headers=headers)   # not one byte of the body may change\n",[100,4702,4703,4708,4713,4718,4723,4727,4732],{"__ignoreMap":15},[199,4704,4705],{"class":201,"line":202},[199,4706,4707],{},"headers = {\n",[199,4709,4710],{"class":201,"line":25},[199,4711,4712],{},"    \"Content-Type\": \"application\u002Fjson\",\n",[199,4714,4715],{"class":201,"line":213},[199,4716,4717],{},"    \"X-Hub-Signature-256\": signature,   # pass the original signature header through unchanged\n",[199,4719,4720],{"class":201,"line":219},[199,4721,4722],{},"    \"X-Peer-Forwarded\": \"1\",            # marker header (illustrative name): the peer never forwards again when it sees this\n",[199,4724,4725],{"class":201,"line":225},[199,4726,2502],{},[199,4728,4729],{"class":201,"line":231},[199,4730,4731],{},"async with httpx.AsyncClient(timeout=5) as client:\n",[199,4733,4734],{"class":201,"line":237},[199,4735,4736],{},"    resp = await client.post(forward_url, content=body, headers=headers)   # not one byte of the body may change\n",[58,4738,4740],{"id":4739},"_9-layered-error-semantics-let-the-frontend-act-on-meaning-not-on-status-codes","9. Layered error semantics: let the frontend act on meaning, not on status codes",[17,4742,4743],{},"For the connect, select and unbind endpoints the frontend turns off the global error toast, and the binding hook maps keywords in the response message to localized copy. Only status keeps the global interceptor. The mapping from server exceptions to response codes:",[105,4745,4746,4761],{},[108,4747,4748],{},[111,4749,4750,4752,4755,4758],{},[114,4751,100],{},[114,4753,4754],{},"message",[114,4756,4757],{},"When it happens",[114,4759,4760],{},"Frontend handling",[121,4762,4763,4785,4799,4812,4825,4839,4853,4867],{},[111,4764,4765,4768,4771,4777],{},[126,4766,4767],{},"403",[126,4769,4770],{},"connect rejected: reason",[126,4772,4773,4774,4776],{},"Authorization validation failed or the assets do not qualify: code exchange failed, ",[100,4775,3913],{}," invalid, scopes missing, no Page, stash expired, chosen Page not in the list",[126,4778,4779,3933,4781,4784],{},[100,4780,4084],{},[100,4782,4783],{},"scopes_missing"," have dedicated copy; selection-related reasons return to disconnected; everything else uses the generic failure copy",[111,4786,4787,4790,4793,4796],{},[126,4788,4789],{},"409",[126,4791,4792],{},"page bound to another shop",[126,4794,4795],{},"The Page already belongs to another merchant",[126,4797,4798],{},"Say it is connected to another account; in the Page select state keep the list so another can be picked",[111,4800,4801,4803,4806,4809],{},[126,4802,4789],{},[126,4804,4805],{},"binding in progress, retry later",[126,4807,4808],{},"Another connect or disconnect for the same merchant is in progress",[126,4810,4811],{},"Ask to retry shortly",[111,4813,4814,4816,4819,4822],{},[126,4815,4789],{},[126,4817,4818],{},"unbind rejected: not_bound",[126,4820,4821],{},"Nothing is bound when unbind is called",[126,4823,4824],{},"Treat as already disconnected and refresh status",[111,4826,4827,4830,4833,4836],{},[126,4828,4829],{},"429",[126,4831,4832],{},"too many requests",[126,4834,4835],{},"The per-IP fixed-window rate limit was hit",[126,4837,4838],{},"Generic failure copy",[111,4840,4841,4844,4847,4850],{},[126,4842,4843],{},"502",[126,4845,4846],{},"meta service unavailable, safe to retry",[126,4848,4849],{},"Meta network error, or writing the Redis stash failed",[126,4851,4852],{},"Generic failure copy, retryable",[111,4854,4855,4858,4861,4864],{},[126,4856,4857],{},"503",[126,4859,4860],{},"messenger app not configured",[126,4862,4863],{},"App ID or App Secret is not configured on the server",[126,4865,4866],{},"Say the environment is not configured; retrying is pointless, so it must be distinct from 502",[111,4868,4869,4872,4875,4878],{},[126,4870,4871],{},"500",[126,4873,4874],{},"unbind failed, safe to retry",[126,4876,4877],{},"Clearing the columns locally failed during unbind, including a conditional update that matched nothing",[126,4879,4880],{},"Ask to retry",[17,4882,4883,4884,4887,4888,4891],{},"The 503 was added during development. With the configuration missing, calling Meta with an empty ",[100,4885,4886],{},"client_id"," only gives back a vague ",[100,4889,4890],{},"code_exchange_failed",". The merchant sees \"authorization rejected\", and so does ops. Separating \"needs configuration\" from \"retryable\" and \"rejected\" cuts the debugging cost by an order of magnitude.",[58,4893,4895],{"id":4894},"_10-rollout-order-and-compatibility-with-existing-data","10. Rollout order and compatibility with existing data",[348,4897,4898,4904,4919,4925,4931],{},[315,4899,4900,4903],{},[49,4901,4902],{},"DDL goes out before the service."," The new ORM model includes the two new columns, and if the database lacks them every ORM query on the merchant table fails, which also breaks tenant lookup for WhatsApp and Instagram. The DDL itself is nullable columns and a widened column, has no effect on the old code, and can be run ahead of time. Order: DDL, then the agent service, then the admin console, then point the Page webhook at production in the Meta dashboard.",[315,4905,4906,4909,4910,4912,4913,4915,4916,4918],{},[49,4907,4908],{},"Compatibility for existing bindings",": credentials in the older format stay readable, so no one-off migration is needed. ",[100,4911,4206],{}," reports connected when both ",[100,4914,4107],{}," and the token are non-empty. When ",[100,4917,4503],{}," is empty the frontend falls back to showing the Page ID.",[315,4920,4921,4924],{},[49,4922,4923],{},"The cost of switching Meta Apps",": existing Pages attached to the old App stop receiving messages because the signing secret changes. The merchant has to authorize once more on the settings page, which stores the credential under the new scheme and subscribes the Page to the new App. Existing bindings are inventoried before launch and handled in the same window as the switch.",[315,4926,4927,4930],{},[49,4928,4929],{},"The three permissions on the production App need Advanced Access."," Otherwise only users with a role on the App can authorize successfully. This is the blocker most easily overlooked before launch.",[315,4932,4933,4936],{},[49,4934,4935],{},"Verification",": the test environment ran the full loop of authorize, connected card, visitor message, AI reply. On the server, three new unit test suites (auth orchestration, endpoint layer, webhook forwarding) pass along with the existing WhatsApp tests. The frontend login hook tests cover SDK loading, cancel, the once guard, missing configuration, timeout, and no callback after unmount.",[58,4938,4940],{"id":4939},"_11-lessons-worth-reusing","11. Lessons worth reusing",[348,4942,4943,4949,4955,4961,4967,4973,4979,4985],{},[315,4944,4945,4948],{},[49,4946,4947],{},"In a third-party authorization chain, the frontend only fetches the credential."," Token exchange, validation and persistence all happen on the server. The credential never passes through the frontend, the logic lives in one place, and switching token type needs no frontend change.",[315,4950,4951,4954],{},[49,4952,4953],{},"When the platform returns a set, you need a selection state on your side",", and you have to account for the platform remembering the authorization. Refusing outright leaves the user stuck.",[315,4956,4957,4960],{},[49,4958,4959],{},"For multi-step operations with external side effects, put the step that needs no cleanup on failure first."," Subscribe then persist, and the failure path converges on \"nothing was written\", with compensation needed in only one place.",[315,4962,4963,4966],{},[49,4964,4965],{},"Use a versioned prefix for encrypted storage."," Data in the older format needs no one-off migration, and a future algorithm change is smooth. Prefixed but undecryptable must fail closed.",[315,4968,4969,4972],{},[49,4970,4971],{},"Write a group of fields concurrently with a single UPDATE, and do not trust ORM dirty checking."," Use a conditional update as an optimistic lock for deletes. Set unique-key columns to NULL, not to an empty string.",[315,4974,4975,4978],{},[49,4976,4977],{},"Beyond the status code, keep stable keywords in the message"," so the frontend can map copy by meaning. \"Retryable\", \"rejected\" and \"needs configuration\" must be three separate things.",[315,4980,4981,4984],{},[49,4982,4983],{},"A webhook signature covers the whole body, so forwarding has to be the whole payload."," The response has a deadline, so ACK first and do the work after.",[315,4986,4987,4990],{},[49,4988,4989],{},"Find out the platform's constraints at the design stage."," A limit like \"one App has only one callback URL\" costs a full redesign if you discover it when the test environment stops receiving messages.",[1042,4992,4993],{},"html .light .shiki span {color: var(--shiki-light);background: var(--shiki-light-bg);font-style: var(--shiki-light-font-style);font-weight: var(--shiki-light-font-weight);text-decoration: var(--shiki-light-text-decoration);}html.light .shiki span {color: var(--shiki-light);background: var(--shiki-light-bg);font-style: var(--shiki-light-font-style);font-weight: var(--shiki-light-font-weight);text-decoration: var(--shiki-light-text-decoration);}html .default .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html.dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html pre.shiki code .slsVL, html code.shiki .slsVL{--shiki-light:#24292E;--shiki-default:#E1E4E8;--shiki-dark:#E1E4E8}html pre.shiki code .suiK_, html code.shiki .suiK_{--shiki-light:#005CC5;--shiki-default:#79B8FF;--shiki-dark:#79B8FF}html pre.shiki code .shcOC, html code.shiki .shcOC{--shiki-light:#6F42C1;--shiki-default:#B392F0;--shiki-dark:#B392F0}html pre.shiki code .sQHwn, html code.shiki .sQHwn{--shiki-light:#E36209;--shiki-default:#FFAB70;--shiki-dark:#FFAB70}html pre.shiki code .so5gQ, html code.shiki .so5gQ{--shiki-light:#D73A49;--shiki-default:#F97583;--shiki-dark:#F97583}html pre.shiki code .sCsY4, html code.shiki .sCsY4{--shiki-light:#6A737D;--shiki-default:#6A737D;--shiki-dark:#6A737D}html pre.shiki code .sfrk1, html code.shiki .sfrk1{--shiki-light:#032F62;--shiki-default:#9ECBFF;--shiki-dark:#9ECBFF}",{"title":15,"searchDepth":25,"depth":25,"links":4995},[4996,4997,4998,4999,5000,5001,5002,5007,5008,5009,5010],{"id":3078,"depth":25,"text":3079},{"id":3182,"depth":25,"text":3183},{"id":3593,"depth":25,"text":3594},{"id":3826,"depth":25,"text":3827},{"id":4061,"depth":25,"text":4062},{"id":4213,"depth":25,"text":4214},{"id":4373,"depth":25,"text":4374,"children":5003},[5004,5005,5006],{"id":4377,"depth":213,"text":4378},{"id":4444,"depth":213,"text":4445},{"id":4458,"depth":213,"text":4459},{"id":4528,"depth":25,"text":4529},{"id":4739,"depth":25,"text":4740},{"id":4894,"depth":25,"text":4895},{"id":4939,"depth":25,"text":4940},"2026-09-04","A merchant clicks Connect Facebook once in the admin console and their Page is live on our Messenger AI assistant. The frontend only produces a code; token exchange, validation, Page selection, webhook subscription and encrypted storage all happen on the server, plus a cross-environment fix for an app that has only one webhook callback URL.","\u002Farticles\u002Fmessenger-one-click-auth.svg",{},"\u002Farticles\u002Fmessenger-one-click-auth","17",{"title":3053,"description":5012},{"loc":5015},"articles\u002Fmessenger-one-click-auth",[3048,3049],"cp2eFt0Sfa6kgLB4hLUjWMIMMsIACPK-YAxhN01setg",{"id":5023,"title":5024,"body":5025,"date":7000,"description":7001,"extension":28,"head":27,"image":7002,"meta":7003,"navigation":30,"ogImage":27,"path":7004,"rating":7005,"readingTime":7006,"robots":27,"schemaOrg":27,"seo":7007,"sitemap":7008,"stem":7009,"tags":7010,"__hash__":7013},"articles_en\u002Farticles\u002Foss-filename-url-encoding.md","Special Characters in OSS Filenames: URL-Encoding Pitfalls and the Real Fix",{"type":7,"value":5026,"toc":6970},[5027,5047,5051,5061,5064,5098,5108,5132,5135,5139,5145,5150,5165,5181,5187,5194,5203,5255,5281,5296,5300,5324,5328,5349,5420,5444,5452,5460,5466,5494,5516,5587,5599,5609,5613,5630,6037,6058,6062,6080,6129,6148,6156,6159,6214,6233,6236,6314,6318,6328,6382,6386,6389,6438,6478,6486,6490,6515,6523,6554,6557,6594,6598,6609,6690,6703,6723,6734,6738,6762,6765,6769,6794,6798,6897,6901,6918,6920,6924,6967],[43,5028,5029,5044],{},[17,5030,5031,5032,5035,5036,5039,5040,5043],{},"In production, a user uploaded a file called ",[100,5033,5034],{},"Product Doc_问题+答案.docx",". The upload succeeded and the file showed up in the list, but clicking preview got nowhere: the spinner turned for a long time and then the pane stayed blank. The backend endpoint that reads the file for further processing simply threw back ",[100,5037,5038],{},"500 Parsing failed",". At the end of the investigation, the culprit turned out to be that innocent-looking ",[100,5041,5042],{},"+"," in the filename.",[17,5045,5046],{},"This post is a full post-mortem: from symptom to root cause, from \"treating the symptom\" to \"curing the disease\", plus several deep URL-encoding pits I fell into along the way. All of it is hands-on experience you can carry straight into your own project.",[58,5048,5050],{"id":5049},"_1-background-a-file-upload-system","1. Background: a file upload system",[17,5052,5053,5054,5057,5058,1312],{},"This is a typical ",[49,5055,5056],{},"file management system",": users upload documents (PDF \u002F DOCX \u002F XLSX…) to object storage (OSS), and the file is then registered in the business database. If \"backend processing\" is checked, the server ",[49,5059,5060],{},"fetches the file's URL, then reads and parses its content for further processing",[17,5062,5063],{},"The data flow looks roughly like this:",[191,5065,5067],{"className":193,"code":5066,"language":195,"meta":15,"style":15},"flowchart LR\n    A[\"Pick a file\u003Cbr>in the frontend\"] --> B[\"Upload to OSS\u003Cbr>returns file_url\"]\n    B --> C[\"Register API insert\u003Cbr>writes document_url\"]\n    C --> D[(\"Business DB\")]\n    D --> E[\"Backend fetches content\u003Cbr>by document_url to process it\"]\n    D --> F[\"List \u002F detail page\u003Cbr>preview & download\"]\n",[100,5068,5069,5073,5078,5083,5088,5093],{"__ignoreMap":15},[199,5070,5071],{"class":201,"line":202},[199,5072,1201],{},[199,5074,5075],{"class":201,"line":25},[199,5076,5077],{},"    A[\"Pick a file\u003Cbr>in the frontend\"] --> B[\"Upload to OSS\u003Cbr>returns file_url\"]\n",[199,5079,5080],{"class":201,"line":213},[199,5081,5082],{},"    B --> C[\"Register API insert\u003Cbr>writes document_url\"]\n",[199,5084,5085],{"class":201,"line":219},[199,5086,5087],{},"    C --> D[(\"Business DB\")]\n",[199,5089,5090],{"class":201,"line":225},[199,5091,5092],{},"    D --> E[\"Backend fetches content\u003Cbr>by document_url to process it\"]\n",[199,5094,5095],{"class":201,"line":231},[199,5096,5097],{},"    D --> F[\"List \u002F detail page\u003Cbr>preview & download\"]\n",[17,5099,5100,5101,5107],{},"Note one key fact: ",[49,5102,5103,5106],{},[100,5104,5105],{},"document_url"," is not just for browser preview",". It has at least three consumers:",[312,5109,5110,5117,5126],{},[315,5111,5112,5113,5116],{},"Browser ",[49,5114,5115],{},"preview"," (PDFs go straight into an iframe; Office documents go through an online preview service);",[315,5118,5112,5119,3724,5122,5125],{},[49,5120,5121],{},"download",[100,5123,5124],{},"window.open",");",[315,5127,5128,5131],{},[49,5129,5130],{},"Backend fetch for processing"," (the server sends an HTTP request to pull the file content).",[17,5133,5134],{},"Keep this in mind. The whole \"why fixing only the frontend doesn't work\" part later depends on it.",[58,5136,5138],{"id":5137},"_2-symptom-upload-succeeds-access-returns-404","2. Symptom: upload succeeds, access returns 404",[17,5140,5141,5142,5144],{},"The user uploads ",[100,5143,5034],{},", and OSS returns an access URL that looks like this:",[17,5146,5147],{},[100,5148,5149],{},"https:\u002F\u002Fcdn.example.com\u002Ffiles\u002F2026\u002F06\u002F27\u002FProduct Doc_问题+答案.docx",[17,5151,5152,5153,2625,5156,5159,5160,1312],{},"This filename hits three kinds of \"special characters\" at once: a ",[49,5154,5155],{},"space",[49,5157,5158],{},"Chinese characters",", and a ",[49,5161,5162,5163],{},"plus sign ",[100,5164,5042],{},[17,5166,5167,5168,5174,5175,5177,5178,5180],{},"Testing gave a strange picture: ",[49,5169,5170,5171,5173],{},"the vast majority of files with spaces or Chinese characters worked fine; only the ones with ",[100,5172,5042],{}," wouldn't open."," The backend read-and-process endpoint also returned ",[100,5176,5038],{}," for every one of those files. Spaces and Chinese are fine, but ",[100,5179,5042],{}," is not, and that is exactly the lead to follow.",[58,5182,5184,5185],{"id":5183},"_3-digging-for-the-root-cause-the-dual-identity-of","3. Digging for the root cause: the \"dual identity\" of ",[100,5186,5042],{},[2031,5188,5190,5191,5193],{"id":5189},"_31-what-does-actually-mean-in-a-url","3.1 What does ",[100,5192,5042],{}," actually mean in a URL?",[17,5195,5196,5198,5199,5202],{},[100,5197,5042],{}," has ",[49,5200,5201],{},"two contradictory meanings"," in a URL, depending on where it sits and who parses it:",[105,5204,5205,5220],{},[108,5206,5207],{},[111,5208,5209,5212,5217],{},[114,5210,5211],{},"Context",[114,5213,5214,5215],{},"Meaning of ",[100,5216,5042],{},[114,5218,5219],{},"Source",[121,5221,5222,5235],{},[111,5223,5224,5227,5232],{},[126,5225,5226],{},"application\u002Fx-www-form-urlencoded (forms \u002F query string)",[126,5228,5229],{},[49,5230,5231],{},"A space",[126,5233,5234],{},"The HTML form encoding convention, carried into today's URL standard",[111,5236,5237,5243,5252],{},[126,5238,4203,5239,5242],{},[49,5240,5241],{},"path"," part of the generic URI syntax",[126,5244,5245,5248,5249,5251],{},[49,5246,5247],{},"A literal plus sign"," ",[100,5250,5042],{}," (a reserved character in sub-delims)",[126,5253,5254],{},"RFC 3986 §2.2",[17,5256,5257,5258,5260,5261,5264,5265,5268,5269,5271,5272,5274,5275,1312],{},"According to RFC 3986, a ",[100,5259,5042],{}," in the path should be a ",[49,5262,5263],{},"literal plus",", and a space is what gets encoded as ",[100,5266,5267],{},"%20",". The historical baggage is that form submissions encode spaces as ",[100,5270,5042],{}," (to save bytes and avoid ",[100,5273,5267],{},"), and the habit is so deeply ingrained that ",[49,5276,5277,5278,5280],{},"many servers, gateways and CDNs also treat ",[100,5279,5042],{}," as a space when parsing the path",[424,5282,5283],{},[17,5284,5285,5286,5288,5289,5292,5293,5295],{},"In one sentence: ",[100,5287,5042],{}," in the query = a space; in the path it ",[49,5290,5291],{},"should"," = a literal plus, but many servers don't play by the rules and decode a ",[100,5294,5042],{}," in the path into a space as well.",[2031,5297,5299],{"id":5298},"_32-how-oss-loses-the-file","3.2 How OSS \"loses\" the file",[17,5301,5302,5303,5306,5307,5309,5310,5313,5314,3933,5317,5320,5321,1312],{},"An OSS object key is essentially just a string of bytes. On access, the whole key serves as the path, and the server URL-decodes the path once to restore the real key before looking it up. When the browser requests ",[100,5304,5305],{},"...\u002FProduct Doc_问题+答案.docx",", OSS decodes the ",[100,5308,5042],{}," in the path into a space, so the key it actually looks for becomes ",[100,5311,5312],{},"Product Doc_问题 答案.docx"," (a space, not a plus, between ",[100,5315,5316],{},"问题",[100,5318,5319],{},"答案","). That doesn't match the real key → ",[49,5322,5323],{},"NoSuchKey → 404 → the file won't open",[2031,5325,5327],{"id":5326},"_33-nailing-it-down-with-curl-turning-a-guess-into-proof","3.3 Nailing it down with curl (turning a guess into proof)",[17,5329,5330,5331,5334,5335,5338,5339,5341,5342,5344,5345,5348],{},"Go straight to ",[100,5332,5333],{},"curl -I"," (send only a HEAD request to see the status code, without downloading the body). Change ",[49,5336,5337],{},"only"," the ",[100,5340,5042],{}," in the filename, once as a bare ",[100,5343,5042],{}," and once as ",[100,5346,5347],{},"%2B",", with every other character encoded normally:",[191,5350,5354],{"className":5351,"code":5352,"language":5353,"meta":15,"style":15},"language-bash shiki shiki-themes github-light github-dark github-dark","# Bare + version (everything else encoded, only + left as is)\ncurl -sI -o \u002Fdev\u002Fnull -w \"%{http_code} \" 'https:\u002F\u002Fcdn.example.com\u002Ffiles\u002F2026\u002F06\u002F27\u002FProduct%20Doc_%E9%97%AE%E9%A2%98+%E7%AD%94%E6%A1%88.docx'\n# → 404\n\n# Encoded version (+ → %2B)\ncurl -sI -o \u002Fdev\u002Fnull -w \"%{http_code} \" 'https:\u002F\u002Fcdn.example.com\u002Ffiles\u002F2026\u002F06\u002F27\u002FProduct%20Doc_%E9%97%AE%E9%A2%98%2B%E7%AD%94%E6%A1%88.docx'\n# → 200\n","bash",[100,5355,5356,5361,5384,5389,5393,5398,5415],{"__ignoreMap":15},[199,5357,5358],{"class":201,"line":202},[199,5359,5360],{"class":2468},"# Bare + version (everything else encoded, only + left as is)\n",[199,5362,5363,5366,5369,5372,5375,5378,5381],{"class":201,"line":25},[199,5364,5365],{"class":1619},"curl",[199,5367,5368],{"class":3645}," -sI",[199,5370,5371],{"class":3645}," -o",[199,5373,5374],{"class":1633}," \u002Fdev\u002Fnull",[199,5376,5377],{"class":3645}," -w",[199,5379,5380],{"class":1633}," \"%{http_code} \"",[199,5382,5383],{"class":1633}," 'https:\u002F\u002Fcdn.example.com\u002Ffiles\u002F2026\u002F06\u002F27\u002FProduct%20Doc_%E9%97%AE%E9%A2%98+%E7%AD%94%E6%A1%88.docx'\n",[199,5385,5386],{"class":201,"line":213},[199,5387,5388],{"class":2468},"# → 404\n",[199,5390,5391],{"class":201,"line":219},[199,5392,461],{"emptyLinePlaceholder":30},[199,5394,5395],{"class":201,"line":225},[199,5396,5397],{"class":2468},"# Encoded version (+ → %2B)\n",[199,5399,5400,5402,5404,5406,5408,5410,5412],{"class":201,"line":231},[199,5401,5365],{"class":1619},[199,5403,5368],{"class":3645},[199,5405,5371],{"class":3645},[199,5407,5374],{"class":1633},[199,5409,5377],{"class":3645},[199,5411,5380],{"class":1633},[199,5413,5414],{"class":1633}," 'https:\u002F\u002Fcdn.example.com\u002Ffiles\u002F2026\u002F06\u002F27\u002FProduct%20Doc_%E9%97%AE%E9%A2%98%2B%E7%AD%94%E6%A1%88.docx'\n",[199,5416,5417],{"class":201,"line":237},[199,5418,5419],{"class":2468},"# → 200\n",[17,5421,5422,5431,5432,5434,5435,5437,5438,5440,5441,5443],{},[49,5423,5424,5425,5427,5428,5430],{},"Bare ",[100,5426,5042],{}," → 404, ",[100,5429,5347],{}," → 200."," The ",[100,5433,5042],{}," is the only variable, so the causality is pinned down. It also proves in passing that the key stored in OSS really does contain a literal ",[100,5436,5042],{}," (send ",[100,5439,5347],{}," in the request, OSS decodes it back to ",[100,5442,5042],{},", and the lookup hits).",[1036,5445,5446],{},[17,5447,5448,5449,5451],{},"A debugging method: use ",[100,5450,5333],{}," to decouple \"storage-layer reachability\" from \"upper-layer rendering \u002F preview\". A 200 means file access is fine, so go look at the preview logic; only a 404 \u002F 403 points to a storage or encoding problem. Don't start by staring at the preview component in a debugger.",[58,5453,5455,5456,5459],{"id":5454},"_4-why-does-it-still-slip-through-when-its-clearly-encoded-the-encodeuri-trap","4. Why does it still slip through when \"it's clearly encoded\"? The ",[100,5457,5458],{},"encodeURI"," trap",[17,5461,5462,5463,346],{},"The code actually ",[49,5464,5465],{},"did encode already",[191,5467,5469],{"className":2427,"code":5468,"language":2429,"meta":15,"style":15},"const encodedUrl = computed(() => encodeURI(documentUrl.value));\n",[100,5470,5471],{"__ignoreMap":15},[199,5472,5473,5476,5479,5481,5484,5486,5488,5491],{"class":201,"line":202},[199,5474,5475],{"class":2436},"const",[199,5477,5478],{"class":3645}," encodedUrl",[199,5480,3714],{"class":2436},[199,5482,5483],{"class":1619}," computed",[199,5485,3761],{"class":1629},[199,5487,3764],{"class":2436},[199,5489,5490],{"class":1619}," encodeURI",[199,5492,5493],{"class":1629},"(documentUrl.value));\n",[17,5495,5496,5498,5499,5501,5502,5505,5506,5512,5513,346],{},[100,5497,5458],{}," handles spaces (→ ",[100,5500,5267],{},") and Chinese characters (→ ",[100,5503,5504],{},"%xx","), which is why filenames with spaces or Chinese worked. ",[49,5507,5508,5509,5511],{},"But ",[100,5510,5042],{}," is precisely what it does not encode."," This is the classic difference between it and ",[100,5514,5515],{},"encodeURIComponent",[105,5517,5518,5537],{},[108,5519,5520],{},[111,5521,5522,5525,5528,5534],{},[114,5523,5524],{},"Function",[114,5526,5527],{},"Characters left unencoded",[114,5529,5530,5531,5533],{},"Encodes ",[100,5532,5042],{},"?",[114,5535,5536],{},"Intended use",[121,5538,5539,5566],{},[111,5540,5541,5545,5554,5560],{},[126,5542,5543],{},[100,5544,5458],{},[126,5546,5547,5550,5551],{},[100,5548,5549],{},"A-Za-z0-9 - _ . ! ~ * ' ( )",", plus ",[100,5552,5553],{},"; , \u002F ? : @ & = + $ #",[126,5555,5556,5557],{},"❌ ",[49,5558,5559],{},"No",[126,5561,5562,5563],{},"Encoding a \"whole URL\", preserving structural characters such as ",[100,5564,5565],{},"\u002F : ? #",[111,5567,5568,5572,5576,5584],{},[126,5569,5570],{},[100,5571,5515],{},[126,5573,5574],{},[100,5575,5549],{},[126,5577,5578,5579],{},"✅ ",[49,5580,5581,5582],{},"Encodes it as ",[100,5583,5347],{},[126,5585,5586],{},"Encoding \"one piece of a URL\", escaping structural characters too",[17,5588,5589,5591,5592,5595,5596,5598],{},[100,5590,5458],{}," preserves structurally meaningful characters like ",[100,5593,5594],{},"+ \u002F : ? # & ="," as the \"skeleton of the URL\". That is right for encoding a whole URL, but wrong for encoding a filename: a ",[100,5597,5042],{}," in a filename is data, not structure.",[561,5600,5601],{},[17,5602,5603,5604,848,5606,5608],{},"Conclusion: to encode a filename (one segment of the path), use ",[100,5605,5515],{},[100,5607,5458],{},". This trap is the best hidden of all, because it \"looks fine\" for spaces and Chinese characters and tricks you into believing the encoding is correct.",[58,5610,5612],{"id":5611},"_5-the-first-fix-a-utility-function-replacing-the-read-paths","5. The first fix: a utility function + replacing the \"read\" paths",[17,5614,5615,5616,5622,5623,5626,5627,5629],{},"The idea: ",[49,5617,5618,5619,5621],{},"apply ",[100,5620,5515],{}," to every segment of the path",", segment by segment (",[100,5624,5625],{},"\u002F"," must not be encoded, so split on ",[100,5628,5625],{},", encode each segment, then join them back):",[191,5631,5633],{"className":2427,"code":5632,"language":2429,"meta":15,"style":15},"\u002F\u002F Encode the \"unencoded\" OSS file URL returned by the backend into a form that is safe to access.\nexport const encodeOssUrl = (raw: string): string => {\n  if (!raw) return \"\";\n  const qIdx = raw.indexOf(\"?\");\n  const query = qIdx >= 0 ? raw.slice(qIdx) : \"\";       \u002F\u002F keep the query (signature etc.) as is\n  const noQuery = qIdx >= 0 ? raw.slice(0, qIdx) : raw;\n  const schemeEnd = noQuery.indexOf(\":\u002F\u002F\");\n  const pathStart = schemeEnd >= 0 ? noQuery.indexOf(\"\u002F\", schemeEnd + 3) : -1;\n  if (pathStart \u003C 0) return raw;\n  const origin = noQuery.slice(0, pathStart);\n  const encodedPath = noQuery\n    .slice(pathStart)\n    .split(\"\u002F\")\n    .map(seg => {\n      let s = seg;\n      try { s = decodeURIComponent(seg); } catch { \u002F* illegal escapes such as a bare %: keep as is *\u002F }\n      return encodeURIComponent(s);\n    })\n    .join(\"\u002F\");\n  return origin + encodedPath + query;\n};\n",[100,5634,5635,5640,5674,5693,5716,5755,5788,5809,5856,5874,5894,5906,5916,5930,5946,5959,5985,5996,6001,6014,6032],{"__ignoreMap":15},[199,5636,5637],{"class":201,"line":202},[199,5638,5639],{"class":2468},"\u002F\u002F Encode the \"unencoded\" OSS file URL returned by the backend into a form that is safe to access.\n",[199,5641,5642,5645,5648,5651,5653,5655,5658,5660,5663,5666,5668,5670,5672],{"class":201,"line":25},[199,5643,5644],{"class":2436},"export",[199,5646,5647],{"class":2436}," const",[199,5649,5650],{"class":1619}," encodeOssUrl",[199,5652,3714],{"class":2436},[199,5654,3724],{"class":1629},[199,5656,5657],{"class":3659},"raw",[199,5659,346],{"class":2436},[199,5661,5662],{"class":3645}," string",[199,5664,5665],{"class":1629},")",[199,5667,346],{"class":2436},[199,5669,5662],{"class":3645},[199,5671,3663],{"class":2436},[199,5673,3666],{"class":1629},[199,5675,5676,5679,5681,5683,5686,5688,5691],{"class":201,"line":213},[199,5677,5678],{"class":2436},"  if",[199,5680,3724],{"class":1629},[199,5682,3727],{"class":2436},[199,5684,5685],{"class":1629},"raw) ",[199,5687,3683],{"class":2436},[199,5689,5690],{"class":1633}," \"\"",[199,5692,3703],{"class":1629},[199,5694,5695,5698,5701,5703,5706,5709,5711,5714],{"class":201,"line":219},[199,5696,5697],{"class":2436},"  const",[199,5699,5700],{"class":3645}," qIdx",[199,5702,3714],{"class":2436},[199,5704,5705],{"class":1629}," raw.",[199,5707,5708],{"class":1619},"indexOf",[199,5710,2458],{"class":1629},[199,5712,5713],{"class":1633},"\"?\"",[199,5715,2463],{"class":1629},[199,5717,5718,5720,5723,5725,5728,5731,5734,5737,5739,5742,5745,5747,5749,5752],{"class":201,"line":225},[199,5719,5697],{"class":2436},[199,5721,5722],{"class":3645}," query",[199,5724,3714],{"class":2436},[199,5726,5727],{"class":1629}," qIdx ",[199,5729,5730],{"class":2436},">=",[199,5732,5733],{"class":3645}," 0",[199,5735,5736],{"class":2436}," ?",[199,5738,5705],{"class":1629},[199,5740,5741],{"class":1619},"slice",[199,5743,5744],{"class":1629},"(qIdx) ",[199,5746,346],{"class":2436},[199,5748,5690],{"class":1633},[199,5750,5751],{"class":1629},";       ",[199,5753,5754],{"class":2468},"\u002F\u002F keep the query (signature etc.) as is\n",[199,5756,5757,5759,5762,5764,5766,5768,5770,5772,5774,5776,5778,5780,5783,5785],{"class":201,"line":231},[199,5758,5697],{"class":2436},[199,5760,5761],{"class":3645}," noQuery",[199,5763,3714],{"class":2436},[199,5765,5727],{"class":1629},[199,5767,5730],{"class":2436},[199,5769,5733],{"class":3645},[199,5771,5736],{"class":2436},[199,5773,5705],{"class":1629},[199,5775,5741],{"class":1619},[199,5777,2458],{"class":1629},[199,5779,833],{"class":3645},[199,5781,5782],{"class":1629},", qIdx) ",[199,5784,346],{"class":2436},[199,5786,5787],{"class":1629}," raw;\n",[199,5789,5790,5792,5795,5797,5800,5802,5804,5807],{"class":201,"line":237},[199,5791,5697],{"class":2436},[199,5793,5794],{"class":3645}," schemeEnd",[199,5796,3714],{"class":2436},[199,5798,5799],{"class":1629}," noQuery.",[199,5801,5708],{"class":1619},[199,5803,2458],{"class":1629},[199,5805,5806],{"class":1633},"\":\u002F\u002F\"",[199,5808,2463],{"class":1629},[199,5810,5811,5813,5816,5818,5821,5823,5825,5827,5829,5831,5833,5836,5839,5841,5844,5847,5849,5852,5854],{"class":201,"line":243},[199,5812,5697],{"class":2436},[199,5814,5815],{"class":3645}," pathStart",[199,5817,3714],{"class":2436},[199,5819,5820],{"class":1629}," schemeEnd ",[199,5822,5730],{"class":2436},[199,5824,5733],{"class":3645},[199,5826,5736],{"class":2436},[199,5828,5799],{"class":1629},[199,5830,5708],{"class":1619},[199,5832,2458],{"class":1629},[199,5834,5835],{"class":1633},"\"\u002F\"",[199,5837,5838],{"class":1629},", schemeEnd ",[199,5840,5042],{"class":2436},[199,5842,5843],{"class":3645}," 3",[199,5845,5846],{"class":1629},") ",[199,5848,346],{"class":2436},[199,5850,5851],{"class":2436}," -",[199,5853,1570],{"class":3645},[199,5855,3703],{"class":1629},[199,5857,5858,5860,5863,5866,5868,5870,5872],{"class":201,"line":249},[199,5859,5678],{"class":2436},[199,5861,5862],{"class":1629}," (pathStart ",[199,5864,5865],{"class":2436},"\u003C",[199,5867,5733],{"class":3645},[199,5869,5846],{"class":1629},[199,5871,3683],{"class":2436},[199,5873,5787],{"class":1629},[199,5875,5876,5878,5881,5883,5885,5887,5889,5891],{"class":201,"line":255},[199,5877,5697],{"class":2436},[199,5879,5880],{"class":3645}," origin",[199,5882,3714],{"class":2436},[199,5884,5799],{"class":1629},[199,5886,5741],{"class":1619},[199,5888,2458],{"class":1629},[199,5890,833],{"class":3645},[199,5892,5893],{"class":1629},", pathStart);\n",[199,5895,5896,5898,5901,5903],{"class":201,"line":261},[199,5897,5697],{"class":2436},[199,5899,5900],{"class":3645}," encodedPath",[199,5902,3714],{"class":2436},[199,5904,5905],{"class":1629}," noQuery\n",[199,5907,5908,5911,5913],{"class":201,"line":267},[199,5909,5910],{"class":1629},"    .",[199,5912,5741],{"class":1619},[199,5914,5915],{"class":1629},"(pathStart)\n",[199,5917,5918,5920,5923,5925,5927],{"class":201,"line":273},[199,5919,5910],{"class":1629},[199,5921,5922],{"class":1619},"split",[199,5924,2458],{"class":1629},[199,5926,5835],{"class":1633},[199,5928,5929],{"class":1629},")\n",[199,5931,5932,5934,5937,5939,5942,5944],{"class":201,"line":279},[199,5933,5910],{"class":1629},[199,5935,5936],{"class":1619},"map",[199,5938,2458],{"class":1629},[199,5940,5941],{"class":3659},"seg",[199,5943,3663],{"class":2436},[199,5945,3666],{"class":1629},[199,5947,5948,5951,5954,5956],{"class":201,"line":285},[199,5949,5950],{"class":2436},"      let",[199,5952,5953],{"class":1629}," s ",[199,5955,3697],{"class":2436},[199,5957,5958],{"class":1629}," seg;\n",[199,5960,5961,5964,5967,5969,5972,5975,5977,5980,5983],{"class":201,"line":651},[199,5962,5963],{"class":2436},"      try",[199,5965,5966],{"class":1629}," { s ",[199,5968,3697],{"class":2436},[199,5970,5971],{"class":1619}," decodeURIComponent",[199,5973,5974],{"class":1629},"(seg); } ",[199,5976,3758],{"class":2436},[199,5978,5979],{"class":1629}," { ",[199,5981,5982],{"class":2468},"\u002F* illegal escapes such as a bare %: keep as is *\u002F",[199,5984,3801],{"class":1629},[199,5986,5987,5990,5993],{"class":201,"line":970},[199,5988,5989],{"class":2436},"      return",[199,5991,5992],{"class":1619}," encodeURIComponent",[199,5994,5995],{"class":1629},"(s);\n",[199,5997,5998],{"class":201,"line":976},[199,5999,6000],{"class":1629},"    })\n",[199,6002,6003,6005,6008,6010,6012],{"class":201,"line":982},[199,6004,5910],{"class":1629},[199,6006,6007],{"class":1619},"join",[199,6009,2458],{"class":1629},[199,6011,5835],{"class":1633},[199,6013,2463],{"class":1629},[199,6015,6016,6019,6022,6024,6027,6029],{"class":201,"line":988},[199,6017,6018],{"class":2436},"  return",[199,6020,6021],{"class":1629}," origin ",[199,6023,5042],{"class":2436},[199,6025,6026],{"class":1629}," encodedPath ",[199,6028,5042],{"class":2436},[199,6030,6031],{"class":1629}," query;\n",[199,6033,6034],{"class":201,"line":994},[199,6035,6036],{"class":1629},"};\n",[17,6038,6039,6040,4092,6043,6046,6047,6052,6053,1312],{},"I replaced ",[100,6041,6042],{},"encodeURI(...)",[100,6044,6045],{},"encodeOssUrl(...)"," in the preview and download call sites. ",[49,6048,6049,6050,3727],{},"Self-test: preview and download both worked for files with ",[100,6051,5042],{}," …and I thought I was done. But the backend read-and-process endpoint was ",[49,6054,6055,6056],{},"still returning ",[100,6057,5038],{},[58,6059,6061],{"id":6060},"_6-the-real-root-the-read-side-and-the-write-side-must-agree","6. The real root: the read side and the write side must agree",[17,6063,6064,6065,6068,6069,6071,6072,6075,6076,6079],{},"The first version only fixed the ",[49,6066,6067],{},"\"read\" paths",", but ",[100,6070,5105],{}," has one more consumer the frontend can't reach: ",[49,6073,6074],{},"the backend fetch",". What decides whether the backend can fetch the file is ",[49,6077,6078],{},"the value written into the database",". The register API had been receiving the bare URL all along:",[191,6081,6083],{"className":2427,"code":6082,"language":2429,"meta":15,"style":15},"insertDocument({\n  document_url: f.fileUrl,   \u002F\u002F ❌ bare URL, contains a literal +\n  file_name: f.name,\n  enable_status: withProcess ? 1 : 0,\n});\n",[100,6084,6085,6093,6101,6106,6124],{"__ignoreMap":15},[199,6086,6087,6090],{"class":201,"line":202},[199,6088,6089],{"class":1619},"insertDocument",[199,6091,6092],{"class":1629},"({\n",[199,6094,6095,6098],{"class":201,"line":25},[199,6096,6097],{"class":1629},"  document_url: f.fileUrl,   ",[199,6099,6100],{"class":2468},"\u002F\u002F ❌ bare URL, contains a literal +\n",[199,6102,6103],{"class":201,"line":213},[199,6104,6105],{"class":1629},"  file_name: f.name,\n",[199,6107,6108,6111,6113,6116,6119,6121],{"class":201,"line":219},[199,6109,6110],{"class":1629},"  enable_status: withProcess ",[199,6112,5533],{"class":2436},[199,6114,6115],{"class":3645}," 1",[199,6117,6118],{"class":2436}," :",[199,6120,5733],{"class":3645},[199,6122,6123],{"class":1629},",\n",[199,6125,6126],{"class":201,"line":225},[199,6127,6128],{"class":1629},"});\n",[17,6130,6131,6132,6134,6135,6137,6138,6140,6141,6144,6145,1312],{},"The chain: the bare URL (with ",[100,6133,5042],{},") is written to the DB → the backend reads it and sends an HTTP request → ",[100,6136,5042],{}," is treated as a space → the content can't be fetched → ",[100,6139,5038],{},". Meanwhile the frontend's preview and download have ",[100,6142,6143],{},"encodeOssUrl"," as a safety net, so \"reading\" looks fine, and ",[49,6146,6147],{},"that is exactly what masked the problem at the write entry point",[424,6149,6150],{},[17,6151,6152,6155],{},[49,6153,6154],{},"Key insight",": an encoding safety net on the frontend's \"read\" side cannot rescue dirty data that was \"written\" in. The true source is the value that goes into the database.",[17,6157,6158],{},"Fixing the write entry point:",[191,6160,6162],{"className":2427,"code":6161,"language":2429,"meta":15,"style":15},"insertDocument({\n  \u002F\u002F Encode before storing: the backend fetches by this URL, and a bare + \u002F space \u002F Chinese character makes the fetch fail\n  document_url: encodeOssUrl(f.fileUrl),   \u002F\u002F ✅\n  file_name: f.name,                        \u002F\u002F display name stays as is, not encoded\n  enable_status: withProcess ? 1 : 0,\n});\n",[100,6163,6164,6170,6175,6188,6196,6210],{"__ignoreMap":15},[199,6165,6166,6168],{"class":201,"line":202},[199,6167,6089],{"class":1619},[199,6169,6092],{"class":1629},[199,6171,6172],{"class":201,"line":25},[199,6173,6174],{"class":2468},"  \u002F\u002F Encode before storing: the backend fetches by this URL, and a bare + \u002F space \u002F Chinese character makes the fetch fail\n",[199,6176,6177,6180,6182,6185],{"class":201,"line":213},[199,6178,6179],{"class":1629},"  document_url: ",[199,6181,6143],{"class":1619},[199,6183,6184],{"class":1629},"(f.fileUrl),   ",[199,6186,6187],{"class":2468},"\u002F\u002F ✅\n",[199,6189,6190,6193],{"class":201,"line":219},[199,6191,6192],{"class":1629},"  file_name: f.name,                        ",[199,6194,6195],{"class":2468},"\u002F\u002F display name stays as is, not encoded\n",[199,6197,6198,6200,6202,6204,6206,6208],{"class":201,"line":225},[199,6199,6110],{"class":1629},[199,6201,5533],{"class":2436},[199,6203,6115],{"class":3645},[199,6205,6118],{"class":2436},[199,6207,5733],{"class":3645},[199,6209,6123],{"class":1629},[199,6211,6212],{"class":201,"line":231},[199,6213,6128],{"class":1629},[424,6215,6216],{},[17,6217,6218,6219,6221,6222,6225,6226,6228,6229,6232],{},"Do ",[49,6220,4351],{}," encode ",[100,6223,6224],{},"file_name",". It is the display name meant for humans, and encoding it would show ",[100,6227,5347],{}," in the list. ",[49,6230,6231],{},"Encode the URL field, keep the display field verbatim",", and keep the two responsibilities separate.",[17,6234,6235],{},"After this change, the whole chain is self-consistent:",[105,6237,6238,6251],{},[108,6239,6240],{},[111,6241,6242,6245,6248],{},[114,6243,6244],{},"Stage",[114,6246,6247],{},"URL form",[114,6249,6250],{},"Result",[121,6252,6253,6266,6282,6297],{},[111,6254,6255,6258,6263],{},[126,6256,6257],{},"Returned by the OSS upload",[126,6259,5424,6260],{},[100,6261,6262],{},"…+…",[126,6264,6265],{},"—",[111,6267,6268,6271,6279],{},[126,6269,6270],{},"Registered in the DB",[126,6272,6273,6275,6276],{},[100,6274,6143],{}," → ",[100,6277,6278],{},"…%2B…",[126,6280,6281],{},"The DB stores the encoded form",[111,6283,6284,6286,6294],{},[126,6285,5130],{},[126,6287,6288,6289,6291,6292],{},"Requests ",[100,6290,5347],{}," → OSS decodes it back to ",[100,6293,5042],{},[126,6295,6296],{},"✅ Hit, fetch succeeds",[111,6298,6299,6302,6311],{},[126,6300,6301],{},"List response → preview \u002F download",[126,6303,6304,6305,6307,6308,6310],{},"The DB's ",[100,6306,6278],{}," goes through ",[100,6309,6143],{}," again (idempotent)",[126,6312,6313],{},"✅ Hit",[58,6315,6317],{"id":6316},"_7-four-hidden-pits-the-best-part","7. Four hidden pits (the best part)",[2031,6319,6321,6322,6324,6325],{"id":6320},"pit-1-idempotency-dont-double-encode-2b-into-252b","Pit 1: Idempotency — don't double-encode ",[100,6323,5347],{}," into ",[100,6326,6327],{},"%252B",[17,6329,6330,6331,6333,6334,6336,6337,6340,6341,6343,6344,6347,6348,6350,6351,6360,6361,1630,6364,6367,6368,6370,6371,6373,6374,6377,6378,6381],{},"Once the write entry point encodes, the DB already stores ",[100,6332,6278],{},", and the frontend calls ",[100,6335,6143],{}," once more when \"reading\". If the implementation \"blindly encodes again\", the ",[100,6338,6339],{},"%"," in ",[100,6342,5347],{}," gets encoded again into ",[100,6345,6346],{},"%25"," → it becomes the double-encoded ",[100,6349,6327],{},", and OSS can't find that either. The solution: ",[49,6352,6353,6354,6357,6358],{},"first restore with ",[100,6355,6356],{},"decodeURIComponent",", then ",[100,6359,5515],{},", so the output is the same whether the input is a bare URL or an already-encoded one. That is ",[49,6362,6363],{},"idempotency",[100,6365,6366],{},"f(f(x)) === f(x)",". It is the precondition for \"the read side and the write side share one function\" to hold. (",[100,6369,6356],{}," throws on a bare ",[100,6372,6339],{},", as in ",[100,6375,6376],{},"50%off.xlsx",", so a ",[100,6379,6380],{},"try\u002Fcatch"," fallback is needed.)",[2031,6383,6385],{"id":6384},"pit-2-the-second-encoding-for-third-party-online-preview","Pit 2: The \"second encoding\" for third-party online preview",[17,6387,6388],{},"Browsers can't render Office documents directly, so Microsoft's online viewer is commonly used:",[191,6390,6392],{"className":2427,"code":6391,"language":2429,"meta":15,"style":15},"const officeUrl = computed(\n  () => `https:\u002F\u002Fview.officeapps.live.com\u002Fop\u002Fembed.aspx?src=${encodeURIComponent(encodedUrl.value)}`\n);\n",[100,6393,6394,6407,6434],{"__ignoreMap":15},[199,6395,6396,6398,6401,6403,6405],{"class":201,"line":202},[199,6397,5475],{"class":2436},[199,6399,6400],{"class":3645}," officeUrl",[199,6402,3714],{"class":2436},[199,6404,5483],{"class":1619},[199,6406,3654],{"class":1629},[199,6408,6409,6412,6414,6417,6419,6421,6424,6426,6429,6431],{"class":201,"line":25},[199,6410,6411],{"class":1629},"  () ",[199,6413,3764],{"class":2436},[199,6415,6416],{"class":1633}," `https:\u002F\u002Fview.officeapps.live.com\u002Fop\u002Fembed.aspx?src=${",[199,6418,5515],{"class":1619},[199,6420,2458],{"class":1633},[199,6422,6423],{"class":1629},"encodedUrl",[199,6425,1312],{"class":1633},[199,6427,6428],{"class":1629},"value",[199,6430,5665],{"class":1633},[199,6432,6433],{"class":1633},"}`\n",[199,6435,6436],{"class":201,"line":213},[199,6437,2463],{"class":1629},[17,6439,6440,6441,6444,6445,6447,6448,6275,6450,6452,6453,6456,6457,6459,6460,6462,6463,6466,6467,5248,6470,5248,6472,6474,6475,6477],{},"There are ",[49,6442,6443],{},"two layers of encoding"," here, and neither can be skipped: ① ",[100,6446,6423],{}," is already a path-safe URL (",[100,6449,5042],{},[100,6451,5347],{},"); ② it is stuffed into the Office URL as the ",[100,6454,6455],{},"src"," query parameter, so the whole thing gets ",[100,6458,5515],{}," once more. The Office server decodes one layer off ",[100,6461,6455],{},", gets a clean URL back, and then fetches from OSS. ",[49,6464,6465],{},"Leave out the second layer",", and the ",[100,6468,6469],{},"&",[100,6471,346],{},[100,6473,5625],{}," inside ",[100,6476,6455],{}," break the structure of Office's own URL, and the preview fails outright.",[424,6479,6480],{},[17,6481,6482,6483,6485],{},"Whenever you \"use one URL as a parameter of another URL\", the parameter layer always needs ",[100,6484,5515],{},", and it must be applied on top of \"a safe URL that has already been processed\".",[2031,6487,6489],{"id":6488},"pit-3-dont-damage-the-query-signed-urls","Pit 3: Don't damage the query (signed URLs)",[17,6491,6492,6493,6496,6497,6499,6500,6502,6503,6506,6507,6509,6510,2625,6512,1312],{},"Accessing a private bucket requires a signature, ",[100,6494,6495],{},"?Expires=...&Signature=...",", and the signature may itself contain ",[100,6498,5042],{}," \u002F ",[100,6501,5347],{},". But the query is computed by the backend according to an algorithm, and ",[49,6504,6505],{},"the frontend must never touch it"," (change one character and the signature is invalid). So ",[100,6508,6143],{}," splits at ",[100,6511,5533],{},[49,6513,6514],{},"encodes only the path part, and appends the query back untouched",[2031,6516,6518,6519,6522],{"id":6517},"pit-4-is-part-of-the-filename-not-a-fragment","Pit 4: ",[100,6520,6521],{},"#"," is part of the filename, not a fragment",[17,6524,6525,6527,6528,6531,6532,6535,6536,6539,6540,6543,6544,6546,6547,6550,6551,1312],{},[100,6526,6521],{}," is perfectly legal in Windows \u002F macOS filenames (",[100,6529,6530],{},"会议纪要#3.docx",", \"meeting notes #3\"), but in a URL it marks the fragment anchor. In the first version I casually wrote ",[100,6533,6534],{},"split(\"#\")[0]"," to strip the fragment, which chopped off the whole ",[100,6537,6538],{},"#3.docx"," and produced ",[100,6541,6542],{},"…\u002F会议纪要",", creating yet another file that wouldn't open. OSS direct links have no fragment; a ",[100,6545,6521],{}," in a filename should be encoded as ",[100,6548,6549],{},"%23"," and treated as data, ",[49,6552,6553],{},"not cut off as a separator",[17,6555,6556],{},"The following cases can be used directly as regression tests (actual output):",[191,6558,6562],{"className":6559,"code":6560,"language":6561,"meta":15,"style":15},"language-txt shiki shiki-themes github-light github-dark github-dark","Product Doc_问题+答案.docx  →  Product%20Doc_%E9%97%AE%E9%A2%98%2B%E7%AD%94%E6%A1%88.docx\nreport&final.pdf           →  report%26final.pdf\n50%off.xlsx                →  50%25off.xlsx          ← a bare % is handled correctly too\n会议纪要#3.docx             →  %E4%BC%9A%E8%AE%AE%E7%BA%AA%E8%A6%81%233.docx   ← # → %23, not truncated\na b  c.txt                 →  a%20b%20%20c.txt       ← consecutive spaces\nx.docx?Expires=1&Sig=a+b   →  ...x.docx?Expires=1&Sig=a+b   ← query kept as is\n","txt",[100,6563,6564,6569,6574,6579,6584,6589],{"__ignoreMap":15},[199,6565,6566],{"class":201,"line":202},[199,6567,6568],{},"Product Doc_问题+答案.docx  →  Product%20Doc_%E9%97%AE%E9%A2%98%2B%E7%AD%94%E6%A1%88.docx\n",[199,6570,6571],{"class":201,"line":25},[199,6572,6573],{},"report&final.pdf           →  report%26final.pdf\n",[199,6575,6576],{"class":201,"line":213},[199,6577,6578],{},"50%off.xlsx                →  50%25off.xlsx          ← a bare % is handled correctly too\n",[199,6580,6581],{"class":201,"line":219},[199,6582,6583],{},"会议纪要#3.docx             →  %E4%BC%9A%E8%AE%AE%E7%BA%AA%E8%A6%81%233.docx   ← # → %23, not truncated\n",[199,6585,6586],{"class":201,"line":225},[199,6587,6588],{},"a b  c.txt                 →  a%20b%20%20c.txt       ← consecutive spaces\n",[199,6590,6591],{"class":201,"line":231},[199,6592,6593],{},"x.docx?Expires=1&Sig=a+b   →  ...x.docx?Expires=1&Sig=a+b   ← query kept as is\n",[58,6595,6597],{"id":6596},"_8-treating-the-symptom-vs-curing-the-disease","8. Treating the symptom vs. curing the disease",[17,6599,6600,6601,6604,6605,6608],{},"The \"encode uniformly at the access layer\" approach above ",[49,6602,6603],{},"treats the symptom",". It works, but it requires every single place that consumes the URL to remember to encode, and missing one spot means a failure (I missed the write entry point). ",[49,6606,6607],{},"The cure",": make the object key URL-safe from the very beginning, so special characters never get a chance to enter the URL at all.",[105,6610,6611,6623],{},[108,6612,6613],{},[111,6614,6615,6617,6620],{},[114,6616],{},[114,6618,6619],{},"Symptom: encode at the access layer",[114,6621,6622],{},"Cure: safe keys",[121,6624,6625,6642,6656,6666,6676],{},[111,6626,6627,6630,6635],{},[126,6628,6629],{},"Approach",[126,6631,6632,6633],{},"Every consumer uses ",[100,6634,6143],{},[126,6636,6637,6638,6641],{},"At upload, the key is ",[100,6639,6640],{},"{date}\u002F{uuid}.{ext}","; the original name is stored in a DB field",[111,6643,6644,6647,6650],{},[126,6645,6646],{},"Who changes",[126,6648,6649],{},"Frontend (or each consumer)",[126,6651,6652,6653,6655],{},"Backend upload logic + a ",[100,6654,6224],{}," field in the DB",[111,6657,6658,6660,6663],{},[126,6659,2049],{},[126,6661,6662],{},"Small change, rescues existing data",[126,6664,6665],{},"URLs are always safe; all edge cases disappear at once",[111,6667,6668,6670,6673],{},[126,6669,2208],{},[126,6671,6672],{},"Relies on no spot being missed; has edge cases",[126,6674,6675],{},"Needs backend changes; you lose \"reading the filename off the URL\"",[111,6677,6678,6681,6684],{},[126,6679,6680],{},"Original name on download",[126,6682,6683],{},"Use the encoded URL directly",[126,6685,6686,6687],{},"Filled back in via ",[100,6688,6689],{},"Content-Disposition",[17,6691,6692,6695,6696,6698,6699,6702],{},[49,6693,6694],{},"With the cure in place, how do you keep \"the download still has the original Chinese filename\"?"," Through the ",[100,6697,6689],{}," response header, using RFC 5987's ",[100,6700,6701],{},"filename*"," for non-ASCII names:",[191,6704,6706],{"className":6559,"code":6705,"language":6561,"meta":15,"style":15},"Content-Disposition: attachment;\n  filename=\"fallback.docx\";\n  filename*=UTF-8''Product%20Doc_%E9%97%AE%E9%A2%98%2B%E7%AD%94%E6%A1%88.docx\n",[100,6707,6708,6713,6718],{"__ignoreMap":15},[199,6709,6710],{"class":201,"line":202},[199,6711,6712],{},"Content-Disposition: attachment;\n",[199,6714,6715],{"class":201,"line":25},[199,6716,6717],{},"  filename=\"fallback.docx\";\n",[199,6719,6720],{"class":201,"line":213},[199,6721,6722],{},"  filename*=UTF-8''Product%20Doc_%E9%97%AE%E9%A2%98%2B%E7%AD%94%E6%A1%88.docx\n",[17,6724,6725,6728,6729,6731,6732,1312],{},[100,6726,6727],{},"filename"," (the ASCII fallback) is for old browsers and ",[100,6730,6701],{}," (UTF-8 percent-encoded) is for modern ones; the downloaded file is still named ",[100,6733,5034],{},[2031,6735,6737],{"id":6736},"one-more-class-of-edge-cases-that-encoding-cant-save","One more class of edge cases that encoding can't save",[312,6739,6740,6752],{},[315,6741,6742,6748,6749,6751],{},[49,6743,6744,6745,6747],{},"A bare ",[100,6746,5533],{}," in the filename",": syntactically it cannot be told apart from the query delimiter (fortunately Windows forbids ",[100,6750,5533],{}," in filenames anyway, so it is rare in practice);",[315,6753,6754,6757,6758,6761],{},[49,6755,6756],{},"Unicode normalization differences",": filenames uploaded from macOS are in NFD (the decomposed form), while OSS \u002F Windows store them in NFC. ",[49,6759,6760],{},"They look identical to the eye but the bytes differ",", so the key simply doesn't match. Percent-encoding escapes byte by byte and can't help when the bytes themselves are inconsistent.",[17,6763,6764],{},"These two points are the hard reasons that push the \"safe key\" approach to the top.",[58,6766,6768],{"id":6767},"_9-what-about-existing-data","9. What about existing data?",[17,6770,6771,6772,6775,6776,6779,6780,6783,6784,6786,6787,6790,6791,6793],{},"After the fix shipped, ",[49,6773,6774],{},"new files"," were fine, but the ",[49,6777,6778],{},"historical records"," in the DB still held bare URLs: preview and download ",[49,6781,6782],{},"still work"," thanks to the ",[100,6785,6143],{}," safety net on the read path, but a backend re-fetch using the bare URL ",[49,6788,6789],{},"will still fail",". So existing data has to be handled separately: have the backend run a one-off script that batch-encodes ",[100,6792,5105],{}," in the DB (the script must be idempotent too), or re-trigger registration \u002F processing for the affected files.",[58,6795,6797],{"id":6796},"_10-pitfall-checklist-take-it-as-is","10. Pitfall checklist (take it as is)",[348,6799,6802,6815,6827,6837,6846,6852,6864,6873,6882,6891],{"className":6800},[6801],"contains-task-list",[315,6803,6806,6810,6811,848,6813],{"className":6804},[6805],"task-list-item",[6807,6808],"input",{"disabled":30,"type":6809},"checkbox"," Encode filenames \u002F path segments with ",[100,6812,5515],{},[100,6814,5458],{},[315,6816,6818,6820,6821,6823,6824,6826],{"className":6817},[6805],[6807,6819],{"disabled":30,"type":6809}," Encode segment by segment (split on ",[100,6822,5625],{},"); don't encode the path separator ",[100,6825,5625],{}," itself",[315,6828,6830,6832,6833,6836],{"className":6829},[6805],[6807,6831],{"disabled":30,"type":6809}," Share one ",[49,6834,6835],{},"idempotent"," encoding function between the read side and the write side (decode-then-encode)",[315,6838,6840,6842,6843,6845],{"className":6839},[6805],[6807,6841],{"disabled":30,"type":6809}," Encode the URL field; keep the display field (",[100,6844,6224],{},") verbatim",[315,6847,6849,6851],{"className":6848},[6805],[6807,6850],{"disabled":30,"type":6809}," Encode only the path, leave the query alone (a signed URL dies with a single change)",[315,6853,6855,6857,6858,6860,6861,6863],{"className":6854},[6805],[6807,6856],{"disabled":30,"type":6809}," Encode ",[100,6859,6521],{}," as ",[100,6862,6549],{},"; don't cut it off as a fragment",[315,6865,6867,6869,6870,6872],{"className":6866},[6805],[6807,6868],{"disabled":30,"type":6809}," For \"a URL as a parameter\", wrap one more layer of ",[100,6871,5515],{}," (Office \u002F any online preview)",[315,6874,6876,6878,6879,6881],{"className":6875},[6805],[6807,6877],{"disabled":30,"type":6809}," When debugging, check the status code with ",[100,6880,5333],{}," first, decoupling storage reachability from upper-layer rendering",[315,6883,6885,6887,6888,6890],{"className":6884},[6805],[6807,6886],{"disabled":30,"type":6809}," Cure it properly if you can: safe uuid keys + original name in the DB + ",[100,6889,6689],{}," on download",[315,6892,6894,6896],{"className":6893},[6805],[6807,6895],{"disabled":30,"type":6809}," Don't forget to migrate existing data",[58,6898,6900],{"id":6899},"_11-summary-in-one-sentence","11. Summary in one sentence",[424,6902,6903],{},[17,6904,6905,6906,6908,6909,1630,6912,6914,6915,6917],{},"The disaster caused by a single ",[100,6907,5042],{}," is, at its core, a ",[49,6910,6911],{},"\"read\u002Fwrite consistency\" problem in URL encoding",[100,6913,5042],{}," has two identities, \"space\" and \"literal plus\", and ",[100,6916,5458],{}," happens not to encode it. The real fix is not on the \"read\" side (preview \u002F download) but on the \"write\" side (the value that goes into the database). The most robust approach is to make object keys URL-safe from birth.",[1940,6919],{},[58,6921,6923],{"id":6922},"references","References",[348,6925,6926,6939,6946,6953,6960],{},[315,6927,6928,6935,6936,6938],{},[6929,6930,6934],"a",{"href":6931,"rel":6932},"https:\u002F\u002Fdatatracker.ietf.org\u002Fdoc\u002Fhtml\u002Frfc3986",[6933],"nofollow","RFC 3986 — URI Generic Syntax"," (§2.2 sub-delims, where ",[100,6937,5042],{}," belongs)",[315,6940,6941],{},[6929,6942,6945],{"href":6943,"rel":6944},"https:\u002F\u002Fdeveloper.mozilla.org\u002Fzh-CN\u002Fdocs\u002FWeb\u002FJavaScript\u002FReference\u002FGlobal_Objects\u002FencodeURIComponent",[6933],"MDN — encodeURIComponent()",[315,6947,6948],{},[6929,6949,6952],{"href":6950,"rel":6951},"https:\u002F\u002Fhelp.aliyun.com\u002Fzh\u002Foss\u002Fwhat-can-i-do-if-i-cannot-access-an-object-by-using-the-object-url",[6933],"Alibaba Cloud OSS — Troubleshooting an object URL that cannot be accessed (in Chinese)",[315,6954,6955],{},[6929,6956,6959],{"href":6957,"rel":6958},"https:\u002F\u002Fhelp.aliyun.com\u002Fzh\u002Foss\u002Fuser-guide\u002Fset-the-file-name-for-downloading-an-oss-file",[6933],"Alibaba Cloud OSS — Setting a custom filename for downloads via Content-Disposition (in Chinese)",[315,6961,6962],{},[6929,6963,6966],{"href":6964,"rel":6965},"https:\u002F\u002Fwww.codestudy.net\u002Fblog\u002Furl-encoding-the-space-character-or-20\u002F",[6933],"URL Encoding Spaces: + vs %20",[1042,6968,6969],{},"html .light .shiki span {color: var(--shiki-light);background: var(--shiki-light-bg);font-style: var(--shiki-light-font-style);font-weight: var(--shiki-light-font-weight);text-decoration: var(--shiki-light-text-decoration);}html.light .shiki span {color: var(--shiki-light);background: var(--shiki-light-bg);font-style: var(--shiki-light-font-style);font-weight: var(--shiki-light-font-weight);text-decoration: var(--shiki-light-text-decoration);}html .default .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html.dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html pre.shiki code .sCsY4, html code.shiki .sCsY4{--shiki-light:#6A737D;--shiki-default:#6A737D;--shiki-dark:#6A737D}html pre.shiki code .shcOC, html code.shiki .shcOC{--shiki-light:#6F42C1;--shiki-default:#B392F0;--shiki-dark:#B392F0}html pre.shiki code .suiK_, html code.shiki .suiK_{--shiki-light:#005CC5;--shiki-default:#79B8FF;--shiki-dark:#79B8FF}html pre.shiki code .sfrk1, html code.shiki .sfrk1{--shiki-light:#032F62;--shiki-default:#9ECBFF;--shiki-dark:#9ECBFF}html pre.shiki code .so5gQ, html code.shiki .so5gQ{--shiki-light:#D73A49;--shiki-default:#F97583;--shiki-dark:#F97583}html pre.shiki code .slsVL, html code.shiki .slsVL{--shiki-light:#24292E;--shiki-default:#E1E4E8;--shiki-dark:#E1E4E8}html pre.shiki code .sQHwn, html code.shiki .sQHwn{--shiki-light:#E36209;--shiki-default:#FFAB70;--shiki-dark:#FFAB70}",{"title":15,"searchDepth":25,"depth":25,"links":6971},[6972,6973,6974,6981,6983,6984,6985,6993,6996,6997,6998,6999],{"id":5049,"depth":25,"text":5050},{"id":5137,"depth":25,"text":5138},{"id":5183,"depth":25,"text":6975,"children":6976},"3. Digging for the root cause: the \"dual identity\" of +",[6977,6979,6980],{"id":5189,"depth":213,"text":6978},"3.1 What does + actually mean in a URL?",{"id":5298,"depth":213,"text":5299},{"id":5326,"depth":213,"text":5327},{"id":5454,"depth":25,"text":6982},"4. Why does it still slip through when \"it's clearly encoded\"? The encodeURI trap",{"id":5611,"depth":25,"text":5612},{"id":6060,"depth":25,"text":6061},{"id":6316,"depth":25,"text":6317,"children":6986},[6987,6989,6990,6991],{"id":6320,"depth":213,"text":6988},"Pit 1: Idempotency — don't double-encode %2B into %252B",{"id":6384,"depth":213,"text":6385},{"id":6488,"depth":213,"text":6489},{"id":6517,"depth":213,"text":6992},"Pit 4: # is part of the filename, not a fragment",{"id":6596,"depth":25,"text":6597,"children":6994},[6995],{"id":6736,"depth":213,"text":6737},{"id":6767,"depth":25,"text":6768},{"id":6796,"depth":25,"text":6797},{"id":6899,"depth":25,"text":6900},{"id":6922,"depth":25,"text":6923},"2026-06-27","One innocent plus sign in a filename made a successfully uploaded file impossible to preview and turned the backend parser into a 500. A full post-mortem, from symptom to root cause and from patch to cure, with the URL-encoding traps I hit along the way.","\u002Farticles\u002Foss-filename-url-encoding.svg",{},"\u002Farticles\u002Foss-filename-url-encoding",4.5,"13",{"title":5024,"description":7001},{"loc":7004},"articles\u002Foss-filename-url-encoding",[7011,7012],"Frontend","Debugging","KTJ7fqfVCj_KTGFzqyQ0GmrekYKQwGQD7Jk0eO1iEAE",{"id":7015,"title":7016,"body":7017,"date":1056,"description":7873,"extension":28,"head":27,"image":7874,"meta":7875,"navigation":30,"ogImage":27,"path":7876,"rating":7005,"readingTime":3043,"robots":27,"schemaOrg":27,"seo":7877,"sitemap":7878,"stem":7879,"tags":7880,"__hash__":7882},"articles_en\u002Farticles\u002Fpython-312-uv-glibc.md","The Wheel Exists, So Why Won't It Install? A glibc\u002Fmanylinux Lesson and uv Dependency Management in a Python 3.12 Upgrade",{"type":7,"value":7018,"toc":7863},[7019,7038,7042,7057,7072,7075,7156,7162,7166,7173,7188,7191,7238,7252,7255,7266,7280,7284,7290,7303,7312,7322,7330,7334,7351,7358,7471,7478,7516,7525,7560,7564,7570,7617,7628,7632,7635,7659,7687,7699,7723,7738,7761,7765,7776,7795,7799,7802,7828,7839,7861],[43,7020,7021],{},[17,7022,7023,7025,7026,7029,7030,7033,7034,7037],{},[49,7024,3068],{},": a Python 3.12 upgrade plus a ",[100,7027,7028],{},"pip → uv"," migration that \"should have taken 10 minutes\" turned, on an end-of-life CentOS 7 (glibc 2.17) server, into a deep investigation of ",[49,7031,7032],{},"wheel \u002F manylinux \u002F glibc ABI compatibility",". This article explains why a wheel can clearly exist and still refuse to install, and how ",[49,7035,7036],{},"uv"," turns dependency management into a reproducible, self-healing engineering capability.",[58,7039,7041],{"id":7040},"_1-a-task-that-should-take-10-minutes","1. A task that \"should take 10 minutes\"",[17,7043,7044,7045,7048,7049,7052,7053,7056],{},"I maintain an AI agent service running in production: ",[100,7046,7047],{},"FastAPI"," + ",[100,7050,7051],{},"LangGraph",", wired up to several LLM providers, with a Milvus vector store behind it. Its dependencies had always lived in a hand-maintained ",[100,7054,7055],{},"requirements.txt",". This time I had two seemingly routine things to do:",[312,7058,7059,7066],{},[315,7060,7061,7062,7065],{},"Upgrade the runtime from Python ",[49,7063,7064],{},"3.11 to 3.12",";",[315,7067,7068,7069,1312],{},"Migrate dependency management from ",[49,7070,7071],{},"pip to uv",[17,7073,7074],{},"If you come from the frontend world, this mapping gives you the intuition:",[105,7076,7077,7090],{},[108,7078,7079],{},[111,7080,7081,7084,7087],{},[114,7082,7083],{},"Python \u002F uv",[114,7085,7086],{},"Frontend \u002F npm",[114,7088,7089],{},"Purpose",[121,7091,7092,7107,7126,7141],{},[111,7093,7094,7099,7104],{},[126,7095,7096],{},[100,7097,7098],{},"pyproject.toml",[126,7100,7101],{},[100,7102,7103],{},"package.json",[126,7105,7106],{},"Declares dependencies, version constraints, and the package index",[111,7108,7109,7114,7119],{},[126,7110,7111],{},[100,7112,7113],{},"uv.lock",[126,7115,7116],{},[100,7117,7118],{},"package-lock.json",[126,7120,7121,7122,7125],{},"Locks the ",[49,7123,7124],{},"full transitive dependency tree"," to exact versions",[111,7127,7128,7133,7138],{},[126,7129,7130],{},[100,7131,7132],{},"uv sync --frozen",[126,7134,7135],{},[100,7136,7137],{},"npm ci",[126,7139,7140],{},"Restores the environment strictly from the lockfile, without re-resolving",[111,7142,7143,7148,7153],{},[126,7144,7145],{},[100,7146,7147],{},"uv add xxx",[126,7149,7150],{},[100,7151,7152],{},"npm install xxx",[126,7154,7155],{},"Adds a dependency and updates the lockfile",[17,7157,7158,7159,7161],{},"Why migrate at all? A hand-maintained ",[100,7160,7055],{}," has no lockfile. The resulting dependency tree depends on install order and on the environment, so environments drift apart — the classic \"works on my machine, breaks in production\".",[58,7163,7165],{"id":7164},"_2-the-first-wall-the-wheel-exists-yet-it-cant-be-installed","2. The first wall: the wheel exists, yet it \"can't be installed\"",[17,7167,7168,7169,7172],{},"With the uv migration done, the very first ",[100,7170,7171],{},"uv sync"," on the server got stuck:",[191,7174,7176],{"className":6559,"code":7175,"language":6561,"meta":15,"style":15},"error: Distribution `onnxruntime==1.26.0` can't be installed because it doesn't have a source distribution or wheel for the current platform\nhint: You're on Linux (`manylinux_2_17_x86_64`), but `onnxruntime` only has wheels for: manylinux_2_27 \u002F manylinux_2_28 ...\n",[100,7177,7178,7183],{"__ignoreMap":15},[199,7179,7180],{"class":201,"line":202},[199,7181,7182],{},"error: Distribution `onnxruntime==1.26.0` can't be installed because it doesn't have a source distribution or wheel for the current platform\n",[199,7184,7185],{"class":201,"line":25},[199,7186,7187],{},"hint: You're on Linux (`manylinux_2_17_x86_64`), but `onnxruntime` only has wheels for: manylinux_2_27 \u002F manylinux_2_28 ...\n",[17,7189,7190],{},"To make sense of this error, you need three concepts first:",[348,7192,7193,7214,7232],{},[315,7194,7195,7196,7199,7200,1630,7203,7206,7207,7210,7211,1312],{},"A ",[49,7197,7198],{},"wheel"," is Python's precompiled binary package, and its filename carries its own \"birth certificate\". Take ",[100,7201,7202],{},"onnxruntime-1.17.0-cp312-cp312-manylinux_2_27_x86_64.whl",[100,7204,7205],{},"cp312"," means it was built for Python 3.12, and ",[100,7208,7209],{},"manylinux_2_27"," means it requires ",[49,7212,7213],{},"glibc ≥ 2.27",[315,7215,7216,7219,7220,7223,7224,7227,7228,7231],{},[49,7217,7218],{},"manylinux"," is a family of compatibility tags meant to make wheels \"run on old Linux too\" (PEP 600). ",[100,7221,7222],{},"manylinux_2_X"," is a ",[49,7225,7226],{},"hard requirement"," of glibc ≥ 2.X, not a suggestion. ",[100,7229,7230],{},"manylinux2014"," = glibc 2.17.",[315,7233,7234,7237],{},[49,7235,7236],{},"glibc is only backward compatible",": a machine with a newer glibc can install wheels built for an older glibc, but not the other way around.",[17,7239,7240,7241,7244,7245,7248,7249,7251],{},"My server was ",[49,7242,7243],{},"CentOS 7 = glibc 2.17"," (confirmed with ",[100,7246,7247],{},"ldd --version","). And every onnxruntime release that ships a cp312 build has only ",[100,7250,7209],{}," wheels for Linux x86_64 — hence the failure.",[17,7253,7254],{},"It gets worse:",[561,7256,7257],{},[17,7258,7259,7262,7263],{},[49,7260,7261],{},"The combination \"cp312 + glibc 2.17\" simply does not exist."," The onnxruntime version that installs on CentOS 7 (1.16.3) has no cp312 build; the versions that do have cp312 (1.17.0 onward) require glibc ≥ 2.27. ",[49,7264,7265],{},"Downgrading can't save you either.",[17,7267,7268,7269,7272,7273,7276,7277],{},"What about building from source? I checked the toolchain: ",[100,7270,7271],{},"gcc 4.8.5"," (from 2015), an empty ",[100,7274,7275],{},"\u002Fopt\u002Frh",", no devtoolset. pandas needs Cython + meson, and rapidfuzz needs C++17 — that old gcc can't build any of it. ",[49,7278,7279],{},"The source route was a dead end too.",[58,7281,7283],{"id":7282},"_3-the-turning-point-this-isnt-a-technical-problem-its-a-product-problem","3. The turning point: this isn't a technical problem, it's a product problem",[17,7285,7286,7287],{},"The technical layer was a dead end. At that moment, the most important call was: ",[49,7288,7289],{},"stop hammering on the dead end, step back one layer, and ask whether the constraint itself can be relaxed.",[17,7291,7292,7293,3724,7296,6499,7299,7302],{},"I went to find out who was pulling onnxruntime in. It turned out to be the project's image\u002Fdocument ",[49,7294,7295],{},"OCR feature",[100,7297,7298],{},"rapidocr-onnxruntime",[100,7300,7301],{},"rapidocr-paddle",", both of which sit on top of Microsoft's inference engine, onnxruntime).",[17,7304,7305,7306,1630,7309],{},"So the question changed from \"how do I install onnxruntime on glibc 2.17\" into a ",[49,7307,7308],{},"product go\u002Fno-go decision",[49,7310,7311],{},"is this OCR feature still in use?",[17,7313,7314,7315,7318,7319,7321],{},"Once I confirmed it had been ",[49,7316,7317],{},"deprecated",", I commented out those two OCR packages in ",[100,7320,7098],{},", and onnxruntime dropped out of the entire dependency tree along with them. As far as onnxruntime was concerned, Python 3.12 was unblocked.",[1036,7323,7324],{},[17,7325,7326,7329],{},[49,7327,7328],{},"This step was the most important engineering judgment in the whole story",": when a constraint has no solution at the current technical layer, the right move is often not to work harder at the technical puzzle, but to step back and ask \"could we simply not need this requirement at all?\" Recognizing a go\u002Fno-go is worth more than grinding through a dead end.",[58,7331,7333],{"id":7332},"_4-the-second-wall-onnxruntime-wasnt-the-only-landmine","4. The second wall: onnxruntime wasn't the only landmine",[17,7335,7336,7337,7339,7340,7343,7344,7346,7347,7350],{},"After removing OCR, I ran ",[100,7338,7171],{}," again and hit ",[49,7341,7342],{},"faiss-cpu"," (it doesn't even publish an sdist, so it fails hard right away). I then scanned the whole ",[100,7345,7113],{}," against the target platform (cp312 \u002F glibc 2.17 \u002F x86_64) and found that recent versions of ",[49,7348,7349],{},"pandas \u002F greenlet \u002F rapidfuzz \u002F ujson"," were also missing glibc 2.17 wheels.",[17,7352,7353,7354,7357],{},"This time I didn't SSH in and firefight them one by one. Instead I ",[49,7355,7356],{},"encoded the platform constraint into the dependency declarations",", using two different kinds of tools:",[105,7359,7360,7372],{},[108,7361,7362],{},[111,7363,7364,7367,7370],{},[114,7365,7366],{},"Package",[114,7368,7369],{},"Treatment",[114,7371,3619],{},[121,7373,7374,7406,7423,7439,7455],{},[111,7375,7376,7384,7391],{},[126,7377,7378,7380,7381,5665],{},[100,7379,7342],{}," (pulled in via ",[100,7382,7383],{},"milvus-lite",[126,7385,7386,7387,7390],{},"Removed from the tree entirely via ",[100,7388,7389],{},"override-dependencies"," with an always-false marker",[126,7392,7393,7394,7397,7398,7401,7402,7405],{},"The chain is ",[100,7395,7396],{},"pymilvus → milvus-lite (local embedded mode) → faiss-cpu","; this project only connects to a ",[49,7399,7400],{},"remote"," Milvus and there is no ",[100,7403,7404],{},"import faiss"," anywhere in the repo, so this chain was never used",[111,7407,7408,7413,7420],{},[126,7409,7410],{},[100,7411,7412],{},"pandas",[126,7414,7415,7416,7419],{},"Pinned ",[100,7417,7418],{},"\u003C2.3"," → 2.2.3",[126,7421,7422],{},"2.2.x is the last line that publishes manylinux2014 wheels",[111,7424,7425,7430,7436],{},[126,7426,7427],{},[100,7428,7429],{},"greenlet",[126,7431,7415,7432,7435],{},[100,7433,7434],{},"\u003C3.2"," → 3.1.1",[126,7437,7438],{},"Required by SQLAlchemy; from 3.2 on, wheels are raised to glibc 2.24",[111,7440,7441,7446,7452],{},[126,7442,7443],{},[100,7444,7445],{},"rapidfuzz",[126,7447,7415,7448,7451],{},[100,7449,7450],{},"\u003C3.13"," → 3.12.2",[126,7453,7454],{},"Required by unstructured; from 3.13 on, raised to glibc 2.27",[111,7456,7457,7462,7468],{},[126,7458,7459],{},[100,7460,7461],{},"ujson",[126,7463,7415,7464,7467],{},[100,7465,7466],{},"\u003C5.11"," → 5.10.0",[126,7469,7470],{},"Required by pymilvus; newer versions are raised to glibc 2.24",[17,7472,7473,7474,7477],{},"The last four are pinned with ",[100,7475,7476],{},"constraint-dependencies",". There's a distinction here that often gets blurred:",[43,7479,7480],{},[348,7481,7482,7501],{},[315,7483,7484,7489,7490,7493,7494,7496,7497,7500],{},[49,7485,7486,7488],{},[100,7487,7476],{}," (constraints)",": \"",[49,7491,7492],{},"if"," this package is used, its version must satisfy the constraint\". It will ",[49,7495,4351],{}," pull in any package on its own; it only narrows the version range when an existing dependency is being resolved. ≈ using npm's ",[100,7498,7499],{},"overrides"," to \"narrow a version\".",[315,7502,7503,7508,7509,7512,7513,1312],{},[49,7504,7505,7507],{},[100,7506,7389],{}," (overrides)",": forcibly rewrites what someone else in the dependency tree declares about a package. Combined with an always-false marker (",[100,7510,7511],{},"sys_platform == 'never'",", which is true on no platform), it lets you ",[49,7514,7515],{},"cut out an entire unused chain",[17,7517,7518,7519,5248,7521,7524],{},"The result: ",[100,7520,7132],{},[49,7522,7523],{},"finishes in seconds with zero C compilation"," — no Docker, no OS upgrade.",[43,7526,7527],{},[17,7528,7529,7532,7533,3724,7536,6499,7539,6499,7542,6499,7545,6499,7548,7551,7552,7555,7556,7559],{},[49,7530,7531],{},"A precision correction (and a matter of honesty)",": strictly speaking, it isn't \"pure wheels all the way\". Of the 161 installed packages, 156 are precompiled wheels and the other 5 are ",[49,7534,7535],{},"pure-Python sdists",[100,7537,7538],{},"oss2",[100,7540,7541],{},"aliyun-python-sdk-core",[100,7543,7544],{},"crcmod",[100,7546,7547],{},"memoization",[100,7549,7550],{},"langdetect","), which get a lightweight build on the spot but ",[49,7553,7554],{},"need no compiler",". The accurate claim is \"",[49,7557,7558],{},"zero C compilation","\", not \"pure wheels\". In technical writing, that kind of precision matters more than a pretty conclusion.",[58,7561,7563],{"id":7562},"_5-why-uv-instead-of-sticking-with-pip","5. Why uv instead of sticking with pip",[17,7565,7566,7567,346],{},"Getting the dependencies installed was just the outcome. I chose uv because it turns \"reproducible\" into an ",[49,7568,7569],{},"engineering capability you can put in a pipeline",[348,7571,7572,7581,7605],{},[315,7573,7574,7577,7578,7580],{},[49,7575,7576],{},"Reproducible via lockfile",": any environment built from ",[100,7579,7113],{}," gets exactly the same dependency tree, which eliminates drift.",[315,7582,7583,7588,7589,4092,7592,7594,7595,7598,7599,2797,7601,7604],{},[49,7584,7585,7587],{},[100,7586,7132],{}," is idempotent",": it compares ",[100,7590,7591],{},".venv",[100,7593,7113],{},"; if they match, it's a no-op that returns in seconds, and only when they differ does it install the delta — so you can ",[49,7596,7597],{},"run it on every deploy",". You wouldn't dare use pip that way, because it runs through everything even when nothing changed, and it's slow. (It's the same relationship as ",[100,7600,7137],{},[100,7602,7603],{},"npm install",".)",[315,7606,7607,7610,7611,7614,7615,1312],{},[49,7608,7609],{},"Configuration in one place",": the Python version constraint (",[100,7612,7613],{},"requires-python = \">=3.12,\u003C3.13\"","), the package index, and the platform constraints are all declared in a single ",[100,7616,7098],{},[17,7618,7619,7620,7623,7624,7627],{},"That last point leads directly to \"self-healing dependencies\": add ",[100,7621,7622],{},"uv sync --frozen --no-dev"," to the deployment pipeline, and from then on, when I change dependencies locally with ",[100,7625,7626],{},"uv add"," and commit the lockfile, the server catches up automatically at deploy time. No more SSHing in to install things by hand.",[58,7629,7631],{"id":7630},"_6-going-live-a-gradual-cutover-a-classic-process-management-pitfall","6. Going live: a gradual cutover + a classic process-management pitfall",[17,7633,7634],{},"This service is deployed in a very \"traditional\" way: Jenkins only rsyncs the source code, supervisor manages the process, and dependencies live in a venv local to the server (not in git).",[191,7636,7638],{"className":193,"code":7637,"language":195,"meta":15,"style":15},"flowchart LR\n    J[\"Jenkins: rsync source\"] --> S[\"uv sync --frozen (self-healing deps)\"]\n    S --> R[\"restart script: supervisorctl restart\"]\n    R --> P[\".venv\u002Fbin\u002Fpython entrypoint (uvicorn, multiple workers)\"]\n",[100,7639,7640,7644,7649,7654],{"__ignoreMap":15},[199,7641,7642],{"class":201,"line":202},[199,7643,1201],{},[199,7645,7646],{"class":201,"line":25},[199,7647,7648],{},"    J[\"Jenkins: rsync source\"] --> S[\"uv sync --frozen (self-healing deps)\"]\n",[199,7650,7651],{"class":201,"line":213},[199,7652,7653],{},"    S --> R[\"restart script: supervisorctl restart\"]\n",[199,7655,7656],{"class":201,"line":219},[199,7657,7658],{},"    R --> P[\".venv\u002Fbin\u002Fpython entrypoint (uvicorn, multiple workers)\"]\n",[17,7660,7661,7664,7665,5248,7667,7670,7671,7674,7675,6499,7678,7681,7682,2797,7684,7686],{},[49,7662,7663],{},"Gradual cutover",": uv installs a standalone Python 3.12 in user space (without touching the system python), and the new ",[100,7666,7591],{},[49,7668,7669],{},"coexists"," with the old ",[100,7672,7673],{},"venv",". Switching over only requires pointing ",[100,7676,7677],{},"command",[100,7679,7680],{},"PATH"," in the supervisor config from ",[100,7683,7673],{},[100,7685,7591],{}," — an atomic, reversible action. Rollback = restoring the backed-up conf. It's close to a blue-green deployment.",[17,7688,7689,7692,7693,7695,7696,7698],{},[49,7690,7691],{},"Then I walked into a classic pitfall",": after switching to ",[100,7694,7591],{}," and restarting, the service started flapping — ",[100,7697,4206],{}," showed RUNNING for a moment, the pid kept changing, and it finally ended up FATAL. The investigation:",[348,7700,7701,7707],{},[315,7702,7703,7706],{},[100,7704,7705],{},"ss -ltnp"," filtered on the service port → a batch of old python processes were still holding that port;",[315,7708,7709,7712,7713,7716,7717,6275,7720,1312],{},[100,7710,7711],{},"ps"," showed them with ",[100,7714,7715],{},"PPID=1"," and a cmdline of ",[100,7718,7719],{},"multiprocessing-fork",[49,7721,7722],{},"orphaned workers",[17,7724,7725,7726,7729,7730,7733,7734,7737],{},"Root cause: in uvicorn's multi-worker mode, the master spawns several workers, but ",[49,7727,7728],{},"by default supervisor only sends the stop signal to the master and doesn't reap the workers",". On restart, the old workers became orphans and kept holding the service port → the new master failed to bind and exited → ",[100,7731,7732],{},"autorestart"," retried over and over until FATAL. (The old single-process code never exposed this; it only became real with multiple workers. On top of that, the process's stderr wasn't being written anywhere at the time, which swallowed the ",[100,7735,7736],{},"address already in use"," error, so for a while I couldn't even see it.)",[17,7739,7740,7741,7749,7750,7753,7754,7757,7758,7760],{},"The fix: add ",[49,7742,7743,7048,7746],{},[100,7744,7745],{},"stopasgroup=true",[100,7747,7748],{},"killasgroup=true"," to the supervisor conf so that it reaps the master and workers together as a ",[49,7751,7752],{},"process group",". For the one-off orphan cleanup, I used ",[100,7755,7756],{},"pkill -f"," with a pattern that matches exactly this app's ",[100,7759,7591],{}," path (to avoid hitting any other process).",[58,7762,7764],{"id":7763},"_7-the-last-mile-the-test-and-production-machines-differ-too","7. The last mile: the test and production machines differ too",[17,7766,7767,7768,7771,7772,7775],{},"The test machine is CentOS 7 (glibc 2.17), but the production machine is ",[49,7769,7770],{},"Ubuntu 24.04 (glibc 2.39)",". glibc 2.39 is backward compatible with the manylinux2014 wheels pinned for 2.17, so production is actually ",[49,7773,7774],{},"easier to install on",". But the key discipline is this:",[699,7777,7778],{},[17,7779,7780,7781,7784,7785,7787,7788,7791,7792],{},"Production ",[49,7782,7783],{},"must"," use ",[100,7786,7132],{},"; ",[49,7789,7790],{},"re-resolving is forbidden",". Otherwise, on Ubuntu with its newer glibc, the resolver would pick newer wheels and install a dependency set that differs from the test machine — and \"it passed testing\" would stop meaning anything. ",[49,7793,7794],{},"The value of a lockfile only truly shows when the two machines' environments differ like this.",[58,7796,7798],{"id":7797},"_8-takeaways-and-honest-technical-debt","8. Takeaways and honest technical debt",[17,7800,7801],{},"A few reusable principles:",[312,7803,7804,7810,7816,7822],{},[315,7805,7806,7809],{},[49,7807,7808],{},"When a constraint has no solution at one layer, step back a layer"," (from technical to a product go\u002Fno-go).",[315,7811,7812,7815],{},[49,7813,7814],{},"Encode platform constraints into the lockfile",", rather than relying on someone SSHing in to firefight by hand.",[315,7817,7818,7821],{},[49,7819,7820],{},"Gradual rollout + atomic switch + easy rollback"," keep the blast radius of a release as small as possible.",[315,7823,7824,7827],{},[49,7825,7826],{},"Lockfile-driven deployment = self-healing dependencies",": it removes the human-factor risk of \"don't forget to install the dependencies manually\" from the process.",[17,7829,7830,7831,7834,7835,7838],{},"The technical debt left behind deserves an honest record too: pinning 4 packages to old versions is ",[49,7832,7833],{},"accommodating an end-of-life CentOS 7 box",". The clean long-term answer is containerization (the ",[100,7836,7837],{},"python:3.12"," image ships with glibc 2.36) or an OS upgrade. Those are tracked as separate follow-ups and were deliberately kept out of this migration.",[43,7840,7841],{},[17,7842,7843,7846,7847,6499,7850,6499,7853,7856,7857,7860],{},[49,7844,7845],{},"A closing note (from an AI engineering perspective)",": AI projects are inherently heavier on dependencies — ML-native packages like ",[100,7848,7849],{},"torch",[100,7851,7852],{},"onnxruntime",[100,7854,7855],{},"faiss"," are extremely sensitive to glibc, CUDA, and the build toolchain. So in AI engineering, \"",[49,7858,7859],{},"reproducible dependency management","\" isn't a nice-to-have; it's the foundation. Whether a model runs consistently on the target machine often depends not on the model itself, but on whether you've locked the environment down. That's my biggest takeaway from this whole exercise.",[1042,7862,1044],{},{"title":15,"searchDepth":25,"depth":25,"links":7864},[7865,7866,7867,7868,7869,7870,7871,7872],{"id":7040,"depth":25,"text":7041},{"id":7164,"depth":25,"text":7165},{"id":7282,"depth":25,"text":7283},{"id":7332,"depth":25,"text":7333},{"id":7562,"depth":25,"text":7563},{"id":7630,"depth":25,"text":7631},{"id":7763,"depth":25,"text":7764},{"id":7797,"depth":25,"text":7798},"A Python 3.12 upgrade plus a pip-to-uv migration that should have taken ten minutes turned into a deep dive on wheel, manylinux and glibc ABI compatibility on an end-of-life CentOS 7 (glibc 2.17) server, and showed how uv makes dependency management reproducible and self-healing.","\u002Farticles\u002Fpython-312-uv-glibc.svg",{},"\u002Farticles\u002Fpython-312-uv-glibc",{"title":7016,"description":7873},{"loc":7876},"articles\u002Fpython-312-uv-glibc",[3049,7881,7012],"DevOps","fVXu98lxcAHScmMAHW6pQEre5He0trca3JumIei-Kio",{"id":7884,"title":7885,"body":7886,"date":8410,"description":8411,"extension":28,"head":27,"image":8412,"meta":8413,"navigation":30,"ogImage":27,"path":8414,"rating":219,"readingTime":3043,"robots":27,"schemaOrg":27,"seo":8415,"sitemap":8416,"stem":8417,"tags":8418,"__hash__":8420},"articles_en\u002Farticles\u002Frag-media-as-text.md","Teaching an AI Support Agent to Send Photos: Index Media as Text, Skip Multimodal Embeddings",{"type":7,"value":7887,"toc":8402},[7888,7891,7894,7897,7903,7907,7910,7913,7916,7919,7969,7972,7977,7981,7984,8013,8016,8022,8028,8034,8037,8101,8104,8107,8111,8114,8117,8120,8202,8205,8212,8261,8264,8267,8272,8276,8281,8284,8287,8292,8295,8298,8301,8305,8308,8311,8314,8344,8347,8351,8357,8363,8369,8372,8374,8377,8397,8400],[17,7889,7890],{},"A customer types into the chat window: \"What does your venue look like?\"",[17,7892,7893],{},"The AI support agent answers with a paragraph. The space is bright and roomy, there is a separate lounge, and there is a lawn outside. Nothing wrong with it, but it is plainly not what the customer wanted. A human agent would have sent a photo.",[17,7895,7896],{},"The merchant has photos, and videos too. The AI simply cannot reach them. The knowledge base only accepts documents, so everything the AI can retrieve is text.",[17,7898,7899,7900],{},"This project fills that gap: ",[49,7901,7902],{},"merchants upload images and videos to the knowledge base, the AI decides when one is worth sending, and then it gets sent.",[58,7904,7906],{"id":7905},"two-routes-multimodal-embeddings-or-translate-to-text-first","Two routes: multimodal embeddings, or translate to text first",[17,7908,7909],{},"There are two ways to make an image retrievable.",[17,7911,7912],{},"The first is multimodal embeddings. Use an embedding model that understands both images and text, place the image and the question in the same vector space, and search for images with the question directly. This is the textbook answer.",[17,7914,7915],{},"The second is to translate first and retrieve second. A vision model looks at the file and writes a text description. That description is embedded like any other text. Retrieval finds the description, and what gets sent is the file behind it.",[17,7917,7918],{},"I chose the second, for three reasons.",[105,7920,7921,7934],{},[108,7922,7923],{},[111,7924,7925,7928,7931],{},[114,7926,7927],{},"Consideration",[114,7929,7930],{},"Multimodal embeddings",[114,7932,7933],{},"Translate to text first",[121,7935,7936,7947,7958],{},[111,7937,7938,7941,7944],{},[126,7939,7940],{},"Changes to the existing system",[126,7942,7943],{},"New embedding model, and every existing document must be re-embedded",[126,7945,7946],{},"Vector store schema untouched, retrieval logic reused as is",[111,7948,7949,7952,7955],{},[126,7950,7951],{},"What you do when retrieval misses",[126,7953,7954],{},"Hard to explain why it missed; you can only tune the model",[126,7956,7957],{},"The description is readable text; edit a sentence and it is fixed",[111,7959,7960,7963,7966],{},[126,7961,7962],{},"Text inside the image",[126,7964,7965],{},"Price lists and timetables contain numbers that a vector represents poorly",[126,7967,7968],{},"The vision model transcribes the text, so it can be matched exactly",[17,7970,7971],{},"The second row decided it. When a merchant uploads a photo and it cannot be found, the multimodal route leaves me saying \"that is how the model sees it\". With text, the merchant opens the description, notices the lawn is not mentioned, and adds the word.",[17,7973,7974],{},[49,7975,7976],{},"Replace an unexplainable step with an intermediate product people can read and edit, and the system becomes something you can operate.",[58,7978,7980],{"id":7979},"indexing-one-file-one-chunk","Indexing: one file, one chunk",[17,7982,7983],{},"The flow is short:",[191,7985,7987],{"className":193,"code":7986,"language":195,"meta":15,"style":15},"flowchart LR\n    A[\"Merchant picks an image \u002F video\"] --> B[\"Upload to object storage\u003Cbr>get a file link\"]\n    B --> C[\"Vision model reads the file by link\u003Cbr>writes a draft description\"]\n    C --> D[\"Merchant confirms or edits it\"]\n    D --> E[\"Embed the description\u003Cbr>store it with the file link\"]\n",[100,7988,7989,7993,7998,8003,8008],{"__ignoreMap":15},[199,7990,7991],{"class":201,"line":202},[199,7992,1201],{},[199,7994,7995],{"class":201,"line":25},[199,7996,7997],{},"    A[\"Merchant picks an image \u002F video\"] --> B[\"Upload to object storage\u003Cbr>get a file link\"]\n",[199,7999,8000],{"class":201,"line":213},[199,8001,8002],{},"    B --> C[\"Vision model reads the file by link\u003Cbr>writes a draft description\"]\n",[199,8004,8005],{"class":201,"line":219},[199,8006,8007],{},"    C --> D[\"Merchant confirms or edits it\"]\n",[199,8009,8010],{"class":201,"line":225},[199,8011,8012],{},"    D --> E[\"Embed the description\u003Cbr>store it with the file link\"]\n",[17,8014,8015],{},"A few details are worth pointing out.",[17,8017,8018,8021],{},[49,8019,8020],{},"The file never passes through our service."," To generate a description, the file link goes straight to the vision model, which fetches it on its own. The server does no downloading and no transcoding, and videos need no frame extraction.",[17,8023,8024,8027],{},[49,8025,8026],{},"The merchant sees the description first."," Generating a description and indexing are two separate endpoints. The first only returns a draft. After the merchant confirms or edits it, the draft is submitted with the indexing request. That extra step means a person has read every description.",[17,8029,8030,8033],{},[49,8031,8032],{},"One file is always one chunk."," Documents get split into chunks; media does not. The full description is the only retrieval text, and the media id maps to exactly one chunk. This convention simplifies a lot downstream: editing a description means updating one record and recomputing one vector, and a media id is enough to locate a file when sending.",[17,8035,8036],{},"Indexing gains a single branch:",[191,8038,8040],{"className":384,"code":8039,"language":386,"meta":15,"style":15},"MEDIA_KINDS = {\"jpg\": \"image\", \"jpeg\": \"image\", \"png\": \"image\", \"mp4\": \"video\"}\n\ndef insert(req):\n    kind = MEDIA_KINDS.get(req.file_type)\n    if kind:\n        # Media: no file parsing, the description is the retrieval text\n        text = req.description.strip() or describe_media(req.url, kind)\n        chunks = [text]\n    else:\n        # Documents: the existing parse + split path\n        chunks = split(parse(req.url))\n    save(chunks, embed(chunks), url=req.url, file_type=req.file_type)\n",[100,8041,8042,8047,8051,8056,8061,8066,8071,8076,8081,8086,8091,8096],{"__ignoreMap":15},[199,8043,8044],{"class":201,"line":202},[199,8045,8046],{},"MEDIA_KINDS = {\"jpg\": \"image\", \"jpeg\": \"image\", \"png\": \"image\", \"mp4\": \"video\"}\n",[199,8048,8049],{"class":201,"line":25},[199,8050,461],{"emptyLinePlaceholder":30},[199,8052,8053],{"class":201,"line":213},[199,8054,8055],{},"def insert(req):\n",[199,8057,8058],{"class":201,"line":219},[199,8059,8060],{},"    kind = MEDIA_KINDS.get(req.file_type)\n",[199,8062,8063],{"class":201,"line":225},[199,8064,8065],{},"    if kind:\n",[199,8067,8068],{"class":201,"line":231},[199,8069,8070],{},"        # Media: no file parsing, the description is the retrieval text\n",[199,8072,8073],{"class":201,"line":237},[199,8074,8075],{},"        text = req.description.strip() or describe_media(req.url, kind)\n",[199,8077,8078],{"class":201,"line":243},[199,8079,8080],{},"        chunks = [text]\n",[199,8082,8083],{"class":201,"line":249},[199,8084,8085],{},"    else:\n",[199,8087,8088],{"class":201,"line":255},[199,8089,8090],{},"        # Documents: the existing parse + split path\n",[199,8092,8093],{"class":201,"line":261},[199,8094,8095],{},"        chunks = split(parse(req.url))\n",[199,8097,8098],{"class":201,"line":267},[199,8099,8100],{},"    save(chunks, embed(chunks), url=req.url, file_type=req.file_type)\n",[17,8102,8103],{},"The instructions for the vision model differ by type. For an image: say what it shows in a sentence or two, and if it contains text (a price list, a timetable, a poster), transcribe all of it faithfully. For a video: describe it in two to four sentences and include any on-screen text that carries information.",[17,8105,8106],{},"On cost, the vision model is called once at upload. A single call costs well under a cent, and an image takes a few seconds. It is never called during a conversation.",[58,8108,8110],{"id":8109},"choosing-the-model-says-which-one-and-never-touches-the-link","Choosing: the model says which one, and never touches the link",[17,8112,8113],{},"Indexing makes media findable. The next question is how the AI sends what it found.",[17,8115,8116],{},"The obvious approach is to put the file link in the retrieval result and let the model write it into the reply. I did not do that. Once a link is in the model's context, two things can go wrong. The model may paste a long raw link to the customer, or it may assemble a link from memory that does not exist.",[17,8118,8119],{},"The actual design separates choosing from sending:",[191,8121,8123],{"className":193,"code":8122,"language":195,"meta":15,"style":15},"sequenceDiagram\n    autonumber\n    participant V as Customer\n    participant M as Main agent\n    participant K as Knowledge retrieval\n    participant C as Code (end of turn)\n    participant I as Messaging channel\n\n    V->>M: Do you have photos of the venue?\n    M->>K: Retrieve \"venue photo\"\n    K-->>M: Text content + media list (id \u002F type \u002F short description)\n    Note over K,C: Full media records (with links)\u003Cbr>are kept in this turn's media pool\n    M-->>C: Reply text + [media:812]\n    C->>C: Strip the tag, check 812 is in the pool\n    C->>I: Send the photo by its pooled link, then the text\n    I-->>V: Photo + \"Here is our venue...\"\n",[100,8124,8125,8129,8133,8138,8143,8148,8153,8158,8162,8167,8172,8177,8182,8187,8192,8197],{"__ignoreMap":15},[199,8126,8127],{"class":201,"line":202},[199,8128,892],{},[199,8130,8131],{"class":201,"line":25},[199,8132,2276],{},[199,8134,8135],{"class":201,"line":213},[199,8136,8137],{},"    participant V as Customer\n",[199,8139,8140],{"class":201,"line":219},[199,8141,8142],{},"    participant M as Main agent\n",[199,8144,8145],{"class":201,"line":225},[199,8146,8147],{},"    participant K as Knowledge retrieval\n",[199,8149,8150],{"class":201,"line":231},[199,8151,8152],{},"    participant C as Code (end of turn)\n",[199,8154,8155],{"class":201,"line":237},[199,8156,8157],{},"    participant I as Messaging channel\n",[199,8159,8160],{"class":201,"line":243},[199,8161,461],{"emptyLinePlaceholder":30},[199,8163,8164],{"class":201,"line":249},[199,8165,8166],{},"    V->>M: Do you have photos of the venue?\n",[199,8168,8169],{"class":201,"line":255},[199,8170,8171],{},"    M->>K: Retrieve \"venue photo\"\n",[199,8173,8174],{"class":201,"line":261},[199,8175,8176],{},"    K-->>M: Text content + media list (id \u002F type \u002F short description)\n",[199,8178,8179],{"class":201,"line":267},[199,8180,8181],{},"    Note over K,C: Full media records (with links)\u003Cbr>are kept in this turn's media pool\n",[199,8183,8184],{"class":201,"line":273},[199,8185,8186],{},"    M-->>C: Reply text + [media:812]\n",[199,8188,8189],{"class":201,"line":279},[199,8190,8191],{},"    C->>C: Strip the tag, check 812 is in the pool\n",[199,8193,8194],{"class":201,"line":285},[199,8195,8196],{},"    C->>I: Send the photo by its pooled link, then the text\n",[199,8198,8199],{"class":201,"line":651},[199,8200,8201],{},"    I-->>V: Photo + \"Here is our venue...\"\n",[17,8203,8204],{},"The media information returned by the retrieval tool is split in two. The copy the model sees has only an id, a type and a short excerpt of the description. The full copy, with the link, stays in a per-turn media pool that the model cannot see.",[17,8206,8207,8208,8211],{},"To send something, the model writes a tag line in its reply, such as ",[100,8209,8210],{},"[media:812]",". At the end of the turn, code does three things:",[191,8213,8215],{"className":384,"code":8214,"language":386,"meta":15,"style":15},"_TAG = re.compile(r\"\\[\\s*media\\s*[:=]\\s*([^\\]]*)\\]\", re.IGNORECASE)\n_MAX_PER_TURN = 2\n\ndef attach_media(answer: str, pool: dict) -> tuple[str, list]:\n    ids = [int(x) for m in _TAG.finditer(answer) for x in re.findall(r\"\\d+\", m.group(1))]\n    answer = _TAG.sub(\"\", answer).strip()          # 1. strip the tag wherever it appears\n    picked = [pool[i] for i in dict.fromkeys(ids)  # 2. the id must be in this turn's pool\n              if i in pool][:_MAX_PER_TURN]        # 3. at most 2 per turn\n    return answer, picked\n",[100,8216,8217,8222,8227,8231,8236,8241,8246,8251,8256],{"__ignoreMap":15},[199,8218,8219],{"class":201,"line":202},[199,8220,8221],{},"_TAG = re.compile(r\"\\[\\s*media\\s*[:=]\\s*([^\\]]*)\\]\", re.IGNORECASE)\n",[199,8223,8224],{"class":201,"line":25},[199,8225,8226],{},"_MAX_PER_TURN = 2\n",[199,8228,8229],{"class":201,"line":213},[199,8230,461],{"emptyLinePlaceholder":30},[199,8232,8233],{"class":201,"line":219},[199,8234,8235],{},"def attach_media(answer: str, pool: dict) -> tuple[str, list]:\n",[199,8237,8238],{"class":201,"line":225},[199,8239,8240],{},"    ids = [int(x) for m in _TAG.finditer(answer) for x in re.findall(r\"\\d+\", m.group(1))]\n",[199,8242,8243],{"class":201,"line":231},[199,8244,8245],{},"    answer = _TAG.sub(\"\", answer).strip()          # 1. strip the tag wherever it appears\n",[199,8247,8248],{"class":201,"line":237},[199,8249,8250],{},"    picked = [pool[i] for i in dict.fromkeys(ids)  # 2. the id must be in this turn's pool\n",[199,8252,8253],{"class":201,"line":243},[199,8254,8255],{},"              if i in pool][:_MAX_PER_TURN]        # 3. at most 2 per turn\n",[199,8257,8258],{"class":201,"line":249},[199,8259,8260],{},"    return answer, picked\n",[17,8262,8263],{},"If the model invents an id, it is not in the pool, so it is dropped and logged. If the model puts the tag mid-sentence, the regex still removes it and the customer never sees it.",[17,8265,8266],{},"The idea is to treat model output as untrusted input. The model has the right to decide which file to send, but all it hands over is a number. What is actually sent, and whether it can be sent, is decided by code.",[1036,8268,8269],{},[17,8270,8271],{},"The prompt has to spell out when to attach: only when the media directly shows what the customer asked about. For something loosely related, the agent can offer (\"want to see it?\") and wait for a yes. Also state it outright: never say \"here's a photo\" without the tag.",[58,8273,8275],{"id":8274},"two-details-that-are-easy-to-miss","Two details that are easy to miss",[17,8277,8278],{},[49,8279,8280],{},"Media that was sent has to be written back into the conversation history.",[17,8282,8283],{},"History stores text. The AI sends a photo this turn, and on the next turn all it sees in history is that it said \"here is our venue\". It does not see the photo. If the customer follows up with \"where's the photo?\", the model assumes it failed to send, and either apologises or sends it again.",[17,8285,8286],{},"The fix is to attach an internal note to the reply at the moment the media goes out, recording which media the customer was shown and what each one is. The note is not shown to the customer, but it travels with the history into the next turn.",[17,8288,8289],{},[49,8290,8291],{},"Media can only be chosen from this turn's retrieval results.",[17,8293,8294],{},"The pool is rebuilt every turn. Media retrieved last turn is no longer in the pool.",[17,8296,8297],{},"This matters for a common two-turn exchange. The customer asks \"do you have a photo of the lawn?\", the AI says \"yes, want to see it?\", and the customer says \"sure\". On the second turn the AI must retrieve again to get the media. It cannot write last turn's id from memory. This rule also goes into the prompt. I ran this exact two-turn exchange repeatedly to confirm the model does not change its answer on the second turn and claim there is no photo.",[17,8299,8300],{},"Why not keep the pool across turns? Because a merchant may delete or disable a file between two turns. Retrieving every turn guarantees that what comes back is valid right now.",[58,8302,8304],{"id":8303},"sending-video-is-slower-than-text","Sending: video is slower than text",[17,8306,8307],{},"The reply finally goes out on whatever chat channel the customer is using. We support several IM channels, plus the web. Web is the easy one: the media information goes in the response and the frontend renders it. Each IM channel needs its ordering handled.",[17,8309,8310],{},"Video is where it goes wrong. When an IM platform receives a video message, it fetches the file and validates it before delivering it to the customer, which is far slower than a text message. If the code sends the video and then immediately sends the text, the customer sees them reversed: first \"here is our training video\", then, seconds later, the video.",[17,8312,8313],{},"There are two ways to handle it, depending on what the channel supports:",[105,8315,8316,8326],{},[108,8317,8318],{},[111,8319,8320,8323],{},[114,8321,8322],{},"Situation",[114,8324,8325],{},"What we do",[121,8327,8328,8336],{},[111,8329,8330,8333],{},[126,8331,8332],{},"The channel can combine media and text, there is one file, and the text is short",[126,8334,8335],{},"Send the text as the caption, as a single message",[111,8337,8338,8341],{},[126,8339,8340],{},"Several files, or the text exceeds the caption limit",[126,8342,8343],{},"Send the media first, wait for the platform's delivery receipt on the video, then send the text",[17,8345,8346],{},"Format and size limits also differ between channels. Rather than handle each one at send time, I constrain uploads to the strictest channel: images must be jpg or png, videos must be mp4, and size is capped at the smallest limit. Anything that passes upload can be sent by link on every channel, so the sending code needs no compatibility checks.",[58,8348,8350],{"id":8349},"where-this-approach-stops-working","Where this approach stops working",[17,8352,8353,8356],{},[49,8354,8355],{},"Quality is capped by the description."," Anything the description leaves out cannot be found. If the photo shows a lawn and the description does not say so, the photo will not appear when a customer asks about the lawn. The upside is that the merchant can fix this without us.",[17,8358,8359,8362],{},[49,8360,8361],{},"Whether to send is governed by the prompt, not a hard rule."," Sometimes it will not send when it should, or will send something only loosely relevant. The cap of two per turn is insurance against the worst case.",[17,8364,8365,8368],{},[49,8366,8367],{},"It searches what the image says, not what the image looks like."," If a customer sends a picture and asks \"do you have something similar?\", this design cannot answer. Search by image and visual similarity is where multimodal embeddings belong.",[17,8370,8371],{},"So the test is simple. If you have tens to hundreds of files, maintained by people, and customers ask in text, translating to text is enough. If you have thousands of product images that nobody can describe one by one, and customers ask with pictures, look at multimodal embeddings.",[1940,8373],{},[17,8375,8376],{},"Looking back, this feature uses no new technology and not much code. It works because of three choices:",[312,8378,8379,8385,8391],{},[315,8380,8381,8384],{},[49,8382,8383],{},"Reuse the existing pipeline before adding a new one."," Media disguised as a piece of text gets retrieval, permissions, enable\u002Fdisable and deletion for free.",[315,8386,8387,8390],{},[49,8388,8389],{},"Make the intermediate product readable and editable."," The description is there for the model to retrieve, and for the merchant to correct.",[315,8392,8393,8396],{},[49,8394,8395],{},"The model chooses; code executes and validates."," The model hands over a number. The link, the cap and validity are all enforced by code.",[17,8398,8399],{},"The third one keeps coming up elsewhere. Wherever a model's output turns into a real action, it is worth asking which part of that action does not need to be left to the model.",[1042,8401,1044],{},{"title":15,"searchDepth":25,"depth":25,"links":8403},[8404,8405,8406,8407,8408,8409],{"id":7905,"depth":25,"text":7906},{"id":7979,"depth":25,"text":7980},{"id":8109,"depth":25,"text":8110},{"id":8274,"depth":25,"text":8275},{"id":8303,"depth":25,"text":8304},{"id":8349,"depth":25,"text":8350},"2026-11-20","Merchants wanted their AI support agent to send photos and videos during a chat. Instead of multimodal embeddings, I had a vision model write a text description of each file and reused the existing text retrieval. This post walks through the approach, and the design that lets the model choose while code does the sending.","\u002Farticles\u002Frag-media-as-text.svg",{},"\u002Farticles\u002Frag-media-as-text",{"title":7885,"description":8411},{"loc":8414},"articles\u002Frag-media-as-text",[1066,8419],"RAG","YH7YcLTHWwETWrCI2vHHxVmO2Aw7DG4t3tuyu-SAZKM",{"id":8422,"title":8423,"body":8424,"date":8410,"description":9618,"extension":28,"head":27,"image":9619,"meta":9620,"navigation":30,"ogImage":27,"path":9621,"rating":7005,"readingTime":1965,"robots":27,"schemaOrg":27,"seo":9622,"sitemap":9623,"stem":9624,"tags":9625,"__hash__":9626},"articles_en\u002Farticles\u002Freviewing-ai-code-concurrency.md","Every Line the AI Wrote Was Correct. It Still Failed Review: Transactions Don't Queue, and Where the Lock Goes",{"type":7,"value":8425,"toc":9608},[8426,8434,8438,8441,8485,8488,8495,8499,8502,8586,8597,8604,8624,8627,8634,8638,8645,8704,8707,8812,8815,8851,8854,8862,8867,8871,8874,8926,9003,9006,9012,9085,9088,9092,9095,9133,9140,9214,9217,9224,9269,9272,9282,9289,9338,9341,9345,9352,9355,9375,9378,9382,9388,9477,9483,9543,9550,9559,9563,9601,9606],[43,8427,8428],{},[17,8429,47,8430,8433],{},[49,8431,8432],{},"AI-written code usually survives a line-by-line read and fails the question \"what if two requests arrive at once?\""," Using a batch of AI-generated admin write endpoints as the example, this post covers three things from the reviewer's seat: why a transaction does not stop concurrent requests from breaking a limit, why adding a lock can still leave you reading stale data, and why saving a whole list can delete something a colleague just added. Business names and code have been neutralized; only the pseudocode needed to make the point remains.",[58,8435,8437],{"id":8436},"_1-would-this-pass-your-review","1. Would this pass your review?",[17,8439,8440],{},"The requirement is simple: a merchant maintains a set of quick replies, capped at 80. The AI's endpoint for adding one looks like this:",[191,8442,8444],{"className":2483,"code":8443,"language":2485,"meta":15,"style":15},"@Transactional\npublic void addQuickReply(long shopId, String content) {\n    int count = replyMapper.countByShop(shopId);   \u002F\u002F count first\n    if (count >= 80) {\n        throw new BusinessException(\"Limit reached\");\n    }\n    replyMapper.insert(shopId, content);           \u002F\u002F then insert\n}\n",[100,8445,8446,8451,8456,8461,8466,8471,8476,8481],{"__ignoreMap":15},[199,8447,8448],{"class":201,"line":202},[199,8449,8450],{},"@Transactional\n",[199,8452,8453],{"class":201,"line":25},[199,8454,8455],{},"public void addQuickReply(long shopId, String content) {\n",[199,8457,8458],{"class":201,"line":213},[199,8459,8460],{},"    int count = replyMapper.countByShop(shopId);   \u002F\u002F count first\n",[199,8462,8463],{"class":201,"line":219},[199,8464,8465],{},"    if (count >= 80) {\n",[199,8467,8468],{"class":201,"line":225},[199,8469,8470],{},"        throw new BusinessException(\"Limit reached\");\n",[199,8472,8473],{"class":201,"line":231},[199,8474,8475],{},"    }\n",[199,8477,8478],{"class":201,"line":237},[199,8479,8480],{},"    replyMapper.insert(shopId, content);           \u002F\u002F then insert\n",[199,8482,8483],{"class":201,"line":243},[199,8484,2502],{},[17,8486,8487],{},"It has a transaction, a limit check, a clear error message and comments. Read line by line, there is nothing to object to, and it will pass self-testing every time: click 81 times and the 81st is rejected.",[17,8489,8490,8491,8494],{},"But I don't review line by line. I ask one question: ",[49,8492,8493],{},"if two requests arrive together, what is the other one doing while each of them sits on a given line?"," You cannot see the answer in the code. You have to draw it.",[58,8496,8498],{"id":8497},"_2-problem-one-a-transaction-is-not-a-queue","2. Problem one: a transaction is not a queue",[17,8500,8501],{},"Put the two requests on one timeline, with 79 rows in the table:",[191,8503,8505],{"className":193,"code":8504,"language":195,"meta":15,"style":15},"sequenceDiagram\n    participant A as Request A\n    participant DB as Database\n    participant B as Request B\n    A->>DB: BEGIN\n    B->>DB: BEGIN\n    A->>DB: SELECT COUNT\n    DB-->>A: 79\n    B->>DB: SELECT COUNT\n    DB-->>B: 79\n    Note over A,B: Both pass the \"fewer than 80\" check\n    A->>DB: INSERT\n    B->>DB: INSERT\n    A->>DB: COMMIT\n    B->>DB: COMMIT\n    Note over DB: 81 rows in the end, the limit is broken\n",[100,8506,8507,8511,8516,8521,8526,8531,8536,8541,8546,8551,8556,8561,8566,8571,8576,8581],{"__ignoreMap":15},[199,8508,8509],{"class":201,"line":202},[199,8510,892],{},[199,8512,8513],{"class":201,"line":25},[199,8514,8515],{},"    participant A as Request A\n",[199,8517,8518],{"class":201,"line":213},[199,8519,8520],{},"    participant DB as Database\n",[199,8522,8523],{"class":201,"line":219},[199,8524,8525],{},"    participant B as Request B\n",[199,8527,8528],{"class":201,"line":225},[199,8529,8530],{},"    A->>DB: BEGIN\n",[199,8532,8533],{"class":201,"line":231},[199,8534,8535],{},"    B->>DB: BEGIN\n",[199,8537,8538],{"class":201,"line":237},[199,8539,8540],{},"    A->>DB: SELECT COUNT\n",[199,8542,8543],{"class":201,"line":243},[199,8544,8545],{},"    DB-->>A: 79\n",[199,8547,8548],{"class":201,"line":249},[199,8549,8550],{},"    B->>DB: SELECT COUNT\n",[199,8552,8553],{"class":201,"line":255},[199,8554,8555],{},"    DB-->>B: 79\n",[199,8557,8558],{"class":201,"line":261},[199,8559,8560],{},"    Note over A,B: Both pass the \"fewer than 80\" check\n",[199,8562,8563],{"class":201,"line":267},[199,8564,8565],{},"    A->>DB: INSERT\n",[199,8567,8568],{"class":201,"line":273},[199,8569,8570],{},"    B->>DB: INSERT\n",[199,8572,8573],{"class":201,"line":279},[199,8574,8575],{},"    A->>DB: COMMIT\n",[199,8577,8578],{"class":201,"line":285},[199,8579,8580],{},"    B->>DB: COMMIT\n",[199,8582,8583],{"class":201,"line":651},[199,8584,8585],{},"    Note over DB: 81 rows in the end, the limit is broken\n",[17,8587,8588,8589,8592,8593,8596],{},"The misunderstanding is about what ",[100,8590,8591],{},"@Transactional"," gives you. A transaction guarantees that ",[49,8594,8595],{},"a group of operations either all take effect or all roll back",". It does not make transactions take turns. Two transactions can both be in the state \"counted, not yet inserted\", and both counted 79.",[17,8598,8599,8600,8603],{},"This pattern has a name: ",[49,8601,8602],{},"check-then-act",". Whenever the decision to write depends on something you just read, and nothing prevents another request from slipping in between the read and the write, the check can be bypassed. Count limits, name uniqueness and \"the set must still match what I saw\" all belong here.",[1036,8605,8606],{},[17,8607,8608,8611,8612,8615,8616,8619,8620,8623],{},[49,8609,8610],{},"Review signal",": when you see ",[100,8613,8614],{},"if (what I read satisfies the condition) { write }",", stop and ask what guarantees nobody gets in between the read and the write. The answer can only be a ",[49,8617,8618],{},"unique key"," or a ",[49,8621,8622],{},"lock",". If the answer is \"there's a transaction\", there is no guarantee.",[17,8625,8626],{},"Name uniqueness can fall back on a unique key: of two concurrent inserts, the later one gets a duplicate-key error, which you catch and turn into a business message. A count limit has no unique key to lean on, so it needs a lock.",[17,8628,8629,8630,8633],{},"Lock what, though? This is easy to get wrong: the row you need to guard against ",[49,8631,8632],{},"does not exist yet",", so there is no \"80th row\" to lock. What you can lock is the parent row they all share, the merchant. Every add request for the same merchant first competes for the row lock on that merchant. The winner proceeds and the rest wait.",[58,8635,8637],{"id":8636},"_3-why-a-lock-is-still-not-enough-which-line-does-it-go-on","3. Why a lock is still not enough: which line does it go on?",[17,8639,8640,8641,8644],{},"\"Add a row lock\" is advice you can find anywhere. In review I also check ",[49,8642,8643],{},"where the lock sits inside the transaction",", because this version is wrong too:",[191,8646,8648],{"className":2483,"code":8647,"language":2485,"meta":15,"style":15},"@Transactional\npublic void addQuickReply(long shopId, long operatorId, String content) {\n    Operator op = operatorMapper.selectById(operatorId); \u002F\u002F plain read\n    checkPermission(op, shopId);\n\n    shopMapper.lockById(shopId);                         \u002F\u002F SELECT ... FOR UPDATE\n    int count = replyMapper.countByShop(shopId);         \u002F\u002F plain read\n    if (count >= 80) {\n        throw new BusinessException(\"Limit reached\");\n    }\n    replyMapper.insert(shopId, content);\n}\n",[100,8649,8650,8654,8659,8664,8669,8673,8678,8683,8687,8691,8695,8700],{"__ignoreMap":15},[199,8651,8652],{"class":201,"line":202},[199,8653,8450],{},[199,8655,8656],{"class":201,"line":25},[199,8657,8658],{},"public void addQuickReply(long shopId, long operatorId, String content) {\n",[199,8660,8661],{"class":201,"line":213},[199,8662,8663],{},"    Operator op = operatorMapper.selectById(operatorId); \u002F\u002F plain read\n",[199,8665,8666],{"class":201,"line":219},[199,8667,8668],{},"    checkPermission(op, shopId);\n",[199,8670,8671],{"class":201,"line":225},[199,8672,461],{"emptyLinePlaceholder":30},[199,8674,8675],{"class":201,"line":231},[199,8676,8677],{},"    shopMapper.lockById(shopId);                         \u002F\u002F SELECT ... FOR UPDATE\n",[199,8679,8680],{"class":201,"line":237},[199,8681,8682],{},"    int count = replyMapper.countByShop(shopId);         \u002F\u002F plain read\n",[199,8684,8685],{"class":201,"line":243},[199,8686,8465],{},[199,8688,8689],{"class":201,"line":249},[199,8690,8470],{},[199,8692,8693],{"class":201,"line":255},[199,8694,8475],{},[199,8696,8697],{"class":201,"line":261},[199,8698,8699],{},"    replyMapper.insert(shopId, content);\n",[199,8701,8702],{"class":201,"line":267},[199,8703,2502],{},[17,8705,8706],{},"It locks before it counts, so what is wrong? Draw it:",[191,8708,8710],{"className":193,"code":8709,"language":195,"meta":15,"style":15},"sequenceDiagram\n    participant A as Request A\n    participant DB as Database\n    participant B as Request B\n    A->>DB: BEGIN\n    B->>DB: BEGIN\n    B->>DB: Plain read: check the operator\n    Note over B: B's snapshot is fixed here\u003Cbr>the table has 79 rows\n    A->>DB: Plain read: check the operator\n    A->>DB: Lock the merchant row\n    B->>DB: Lock the merchant row\n    Note over B: Waits in line\n    A->>DB: SELECT COUNT\n    DB-->>A: 79\n    A->>DB: INSERT, then COMMIT\n    Note over DB: 80 rows committed\n    DB-->>B: Lock acquired\n    B->>DB: SELECT COUNT\n    DB-->>B: 79\n    Note over B: Reads the old snapshot, cannot see A's row\n    B->>DB: INSERT, then COMMIT\n    Note over DB: 81 rows in the end\n",[100,8711,8712,8716,8720,8724,8728,8732,8736,8741,8746,8751,8756,8761,8766,8770,8774,8779,8784,8789,8793,8797,8802,8807],{"__ignoreMap":15},[199,8713,8714],{"class":201,"line":202},[199,8715,892],{},[199,8717,8718],{"class":201,"line":25},[199,8719,8515],{},[199,8721,8722],{"class":201,"line":213},[199,8723,8520],{},[199,8725,8726],{"class":201,"line":219},[199,8727,8525],{},[199,8729,8730],{"class":201,"line":225},[199,8731,8530],{},[199,8733,8734],{"class":201,"line":231},[199,8735,8535],{},[199,8737,8738],{"class":201,"line":237},[199,8739,8740],{},"    B->>DB: Plain read: check the operator\n",[199,8742,8743],{"class":201,"line":243},[199,8744,8745],{},"    Note over B: B's snapshot is fixed here\u003Cbr>the table has 79 rows\n",[199,8747,8748],{"class":201,"line":249},[199,8749,8750],{},"    A->>DB: Plain read: check the operator\n",[199,8752,8753],{"class":201,"line":255},[199,8754,8755],{},"    A->>DB: Lock the merchant row\n",[199,8757,8758],{"class":201,"line":261},[199,8759,8760],{},"    B->>DB: Lock the merchant row\n",[199,8762,8763],{"class":201,"line":267},[199,8764,8765],{},"    Note over B: Waits in line\n",[199,8767,8768],{"class":201,"line":273},[199,8769,8540],{},[199,8771,8772],{"class":201,"line":279},[199,8773,8545],{},[199,8775,8776],{"class":201,"line":285},[199,8777,8778],{},"    A->>DB: INSERT, then COMMIT\n",[199,8780,8781],{"class":201,"line":651},[199,8782,8783],{},"    Note over DB: 80 rows committed\n",[199,8785,8786],{"class":201,"line":970},[199,8787,8788],{},"    DB-->>B: Lock acquired\n",[199,8790,8791],{"class":201,"line":976},[199,8792,8550],{},[199,8794,8795],{"class":201,"line":982},[199,8796,8555],{},[199,8798,8799],{"class":201,"line":988},[199,8800,8801],{},"    Note over B: Reads the old snapshot, cannot see A's row\n",[199,8803,8804],{"class":201,"line":994},[199,8805,8806],{},"    B->>DB: INSERT, then COMMIT\n",[199,8808,8809],{"class":201,"line":2371},[199,8810,8811],{},"    Note over DB: 81 rows in the end\n",[17,8813,8814],{},"B did wait, and it did resume only after A committed, yet it still counted 79. The reason lies in two rules of MySQL's default isolation level, REPEATABLE READ:",[312,8816,8817,8837],{},[315,8818,8819,8826,8827,8830,8831,8836],{},[49,8820,8821,8822,8825],{},"A plain ",[100,8823,8824],{},"SELECT"," reads a snapshot",", and that snapshot is fixed by the ",[49,8828,8829],{},"first plain read"," in the transaction. The whole transaction sees that one view from then on (",[6929,8832,8835],{"href":8833,"rel":8834},"https:\u002F\u002Fdev.mysql.com\u002Fdoc\u002Frefman\u002F8.0\u002Fen\u002Finnodb-consistent-read.html",[6933],"consistent reads",").",[315,8838,8839,8845,8846,8836],{},[49,8840,8841,8844],{},[100,8842,8843],{},"SELECT ... FOR UPDATE"," reads the latest committed data",", and takes a lock that others queue on (",[6929,8847,8850],{"href":8848,"rel":8849},"https:\u002F\u002Fdev.mysql.com\u002Fdoc\u002Frefman\u002F8.0\u002Fen\u002Finnodb-locking-reads.html",[6933],"locking reads",[17,8852,8853],{},"So the lock in this code works fine. The problem is the plain read at the top, the operator check, which pinned the snapshot to a moment before A committed. Counting after the lock is acquired still counts the old world.",[561,8855,8856],{},[17,8857,8858,8861],{},[49,8859,8860],{},"The lock must be the first statement in the transaction",", or at least come before any plain read. A single plain read ahead of the lock reduces the queue to a formality: the request waits, and then sees the data from before it waited.",[43,8863,8864],{},[17,8865,8866],{},"Two caveats. First, this section assumes REPEATABLE READ. Under READ COMMITTED every statement gets a fresh snapshot, so this particular problem does not appear, though the one in section 2 still does. Second, the diagrams here are derived from the documented InnoDB semantics, not from a load test.",[58,8868,8870],{"id":8869},"_4-the-correct-version","4. The correct version",[17,8872,8873],{},"Move the lock to the top:",[191,8875,8877],{"className":2483,"code":8876,"language":2485,"meta":15,"style":15},"@Transactional\npublic void addQuickReply(long shopId, long operatorId, String content) {\n    shopMapper.lockById(shopId);                         \u002F\u002F first statement in the transaction\n    Operator op = operatorMapper.selectById(operatorId);\n    checkPermission(op, shopId);\n    int count = replyMapper.countByShop(shopId);\n    if (count >= 80) {\n        throw new BusinessException(\"Limit reached\");\n    }\n    replyMapper.insert(shopId, content);\n}\n",[100,8878,8879,8883,8887,8892,8897,8901,8906,8910,8914,8918,8922],{"__ignoreMap":15},[199,8880,8881],{"class":201,"line":202},[199,8882,8450],{},[199,8884,8885],{"class":201,"line":25},[199,8886,8658],{},[199,8888,8889],{"class":201,"line":213},[199,8890,8891],{},"    shopMapper.lockById(shopId);                         \u002F\u002F first statement in the transaction\n",[199,8893,8894],{"class":201,"line":219},[199,8895,8896],{},"    Operator op = operatorMapper.selectById(operatorId);\n",[199,8898,8899],{"class":201,"line":225},[199,8900,8668],{},[199,8902,8903],{"class":201,"line":231},[199,8904,8905],{},"    int count = replyMapper.countByShop(shopId);\n",[199,8907,8908],{"class":201,"line":237},[199,8909,8465],{},[199,8911,8912],{"class":201,"line":243},[199,8913,8470],{},[199,8915,8916],{"class":201,"line":249},[199,8917,8475],{},[199,8919,8920],{"class":201,"line":255},[199,8921,8699],{},[199,8923,8924],{"class":201,"line":261},[199,8925,2502],{},[191,8927,8929],{"className":193,"code":8928,"language":195,"meta":15,"style":15},"sequenceDiagram\n    participant A as Request A\n    participant DB as Database\n    participant B as Request B\n    A->>DB: BEGIN\n    B->>DB: BEGIN\n    A->>DB: Lock the merchant row\n    B->>DB: Lock the merchant row\n    Note over B: Waits in line, no snapshot yet\n    A->>DB: SELECT COUNT\n    DB-->>A: 79\n    A->>DB: INSERT, then COMMIT\n    DB-->>B: Lock acquired\n    B->>DB: SELECT COUNT\n    Note over B: First plain read, the snapshot is fixed only now\n    DB-->>B: 80\n    B-->>B: Rejected: limit reached\n",[100,8930,8931,8935,8939,8943,8947,8951,8955,8959,8963,8968,8972,8976,8980,8984,8988,8993,8998],{"__ignoreMap":15},[199,8932,8933],{"class":201,"line":202},[199,8934,892],{},[199,8936,8937],{"class":201,"line":25},[199,8938,8515],{},[199,8940,8941],{"class":201,"line":213},[199,8942,8520],{},[199,8944,8945],{"class":201,"line":219},[199,8946,8525],{},[199,8948,8949],{"class":201,"line":225},[199,8950,8530],{},[199,8952,8953],{"class":201,"line":231},[199,8954,8535],{},[199,8956,8957],{"class":201,"line":237},[199,8958,8755],{},[199,8960,8961],{"class":201,"line":243},[199,8962,8760],{},[199,8964,8965],{"class":201,"line":249},[199,8966,8967],{},"    Note over B: Waits in line, no snapshot yet\n",[199,8969,8970],{"class":201,"line":255},[199,8971,8540],{},[199,8973,8974],{"class":201,"line":261},[199,8975,8545],{},[199,8977,8978],{"class":201,"line":267},[199,8979,8778],{},[199,8981,8982],{"class":201,"line":273},[199,8983,8788],{},[199,8985,8986],{"class":201,"line":279},[199,8987,8550],{},[199,8989,8990],{"class":201,"line":285},[199,8991,8992],{},"    Note over B: First plain read, the snapshot is fixed only now\n",[199,8994,8995],{"class":201,"line":651},[199,8996,8997],{},"    DB-->>B: 80\n",[199,8999,9000],{"class":201,"line":970},[199,9001,9002],{},"    B-->>B: Rejected: limit reached\n",[17,9004,9005],{},"Only one thing differs from the previous diagram: B did no plain read before it queued, so its snapshot is created after it gets the lock and naturally includes the row A committed.",[17,9007,9008,9011],{},[49,9009,9010],{},"What if you have to query first to know what to lock?"," One place in this batch was exactly that case: adding a tag to a customer, capped at 100 per customer. The input is a conversation ID, so you must look up the conversation to learn which customer it is, and that lookup is itself a plain read. Declarative transactions are not enough here. The transaction boundary has to shrink to just \"lock, read, write\":",[191,9013,9015],{"className":2483,"code":9014,"language":2485,"meta":15,"style":15},"public void addTag(long conversationId, String name) {\n    \u002F\u002F Outside the transaction: look up the conversation and check ownership,\n    \u002F\u002F only to learn which row to lock\n    Customer customer = resolveCustomer(conversationId);\n\n    transactionTemplate.execute(status -> {\n        customerMapper.lockById(customer.getId());   \u002F\u002F first statement in the transaction\n        List\u003CTag> tags = tagMapper.listByCustomer(customer.getId());\n        if (containsName(tags, name)) return null;   \u002F\u002F same name counts as success\n        if (tags.size() >= 100) throw new BusinessException(\"Limit reached\");\n        tagMapper.insert(customer.getId(), name);\n        return null;\n    });\n}\n",[100,9016,9017,9022,9027,9032,9037,9041,9046,9051,9056,9061,9066,9071,9076,9081],{"__ignoreMap":15},[199,9018,9019],{"class":201,"line":202},[199,9020,9021],{},"public void addTag(long conversationId, String name) {\n",[199,9023,9024],{"class":201,"line":25},[199,9025,9026],{},"    \u002F\u002F Outside the transaction: look up the conversation and check ownership,\n",[199,9028,9029],{"class":201,"line":213},[199,9030,9031],{},"    \u002F\u002F only to learn which row to lock\n",[199,9033,9034],{"class":201,"line":219},[199,9035,9036],{},"    Customer customer = resolveCustomer(conversationId);\n",[199,9038,9039],{"class":201,"line":225},[199,9040,461],{"emptyLinePlaceholder":30},[199,9042,9043],{"class":201,"line":231},[199,9044,9045],{},"    transactionTemplate.execute(status -> {\n",[199,9047,9048],{"class":201,"line":237},[199,9049,9050],{},"        customerMapper.lockById(customer.getId());   \u002F\u002F first statement in the transaction\n",[199,9052,9053],{"class":201,"line":243},[199,9054,9055],{},"        List\u003CTag> tags = tagMapper.listByCustomer(customer.getId());\n",[199,9057,9058],{"class":201,"line":249},[199,9059,9060],{},"        if (containsName(tags, name)) return null;   \u002F\u002F same name counts as success\n",[199,9062,9063],{"class":201,"line":255},[199,9064,9065],{},"        if (tags.size() >= 100) throw new BusinessException(\"Limit reached\");\n",[199,9067,9068],{"class":201,"line":261},[199,9069,9070],{},"        tagMapper.insert(customer.getId(), name);\n",[199,9072,9073],{"class":201,"line":267},[199,9074,9075],{},"        return null;\n",[199,9077,9078],{"class":201,"line":273},[199,9079,9080],{},"    });\n",[199,9082,9083],{"class":201,"line":279},[199,9084,2502],{},[17,9086,9087],{},"Keeping the ownership check outside the transaction is acceptable: it verifies \"is this conversation yours\", a fact that does not change within milliseconds. The limit and the duplicate check, on the other hand, must happen inside the lock.",[58,9089,9091],{"id":9090},"_5-problem-two-a-whole-list-overwrite-with-no-version","5. Problem two: a whole-list overwrite with no version",[17,9093,9094],{},"The second kind of problem has nothing to do with locks. The requirement is a \"job title dictionary\" dialog: an admin adds, deletes, renames and reorders titles in the dialog, then submits the whole list on save. The AI implemented it like this:",[191,9096,9098],{"className":2483,"code":9097,"language":2485,"meta":15,"style":15},"@Transactional\npublic void saveAll(long shopId, List\u003CItem> items) {\n    List\u003CTitle> current = titleMapper.listByShop(shopId);\n    \u002F\u002F Items with an id are renames, items without one are new,\n    \u002F\u002F and anything in the table but missing from the submission is a delete\n    ...\n}\n",[100,9099,9100,9104,9109,9114,9119,9124,9129],{"__ignoreMap":15},[199,9101,9102],{"class":201,"line":202},[199,9103,8450],{},[199,9105,9106],{"class":201,"line":25},[199,9107,9108],{},"public void saveAll(long shopId, List\u003CItem> items) {\n",[199,9110,9111],{"class":201,"line":213},[199,9112,9113],{},"    List\u003CTitle> current = titleMapper.listByShop(shopId);\n",[199,9115,9116],{"class":201,"line":219},[199,9117,9118],{},"    \u002F\u002F Items with an id are renames, items without one are new,\n",[199,9120,9121],{"class":201,"line":225},[199,9122,9123],{},"    \u002F\u002F and anything in the table but missing from the submission is a delete\n",[199,9125,9126],{"class":201,"line":231},[199,9127,9128],{},"    ...\n",[199,9130,9131],{"class":201,"line":237},[199,9132,2502],{},[17,9134,9135,9136,9139],{},"\"Anything in the table but missing from the submission is a delete\" holds under one assumption: ",[49,9137,9138],{},"the submitted draft was edited from the list that is in the table right now",". Once two admins have the dialog open at the same time, the assumption fails:",[191,9141,9143],{"className":193,"code":9142,"language":195,"meta":15,"style":15},"sequenceDiagram\n    participant X as Admin X\n    participant S as Service\n    participant Y as Admin Y\n    X->>S: Open the dialog\n    S-->>X: Manager, Clerk\n    Y->>S: Open the dialog\n    S-->>Y: Manager, Clerk\n    Y->>S: Add \"Supervisor\" and save\n    Note over S: Table: Manager, Clerk, Supervisor\n    X->>S: Rename \"Clerk\" and save\u003Cbr>Submits: Manager, Store Lead\n    Note over S: \"Supervisor\" is not in the submission\u003Cbr>so it is treated as a delete\n    S-->>X: Saved\n    Note over Y: Y's new \"Supervisor\" is gone, with no warning\n",[100,9144,9145,9149,9154,9159,9164,9169,9174,9179,9184,9189,9194,9199,9204,9209],{"__ignoreMap":15},[199,9146,9147],{"class":201,"line":202},[199,9148,892],{},[199,9150,9151],{"class":201,"line":25},[199,9152,9153],{},"    participant X as Admin X\n",[199,9155,9156],{"class":201,"line":213},[199,9157,9158],{},"    participant S as Service\n",[199,9160,9161],{"class":201,"line":219},[199,9162,9163],{},"    participant Y as Admin Y\n",[199,9165,9166],{"class":201,"line":225},[199,9167,9168],{},"    X->>S: Open the dialog\n",[199,9170,9171],{"class":201,"line":231},[199,9172,9173],{},"    S-->>X: Manager, Clerk\n",[199,9175,9176],{"class":201,"line":237},[199,9177,9178],{},"    Y->>S: Open the dialog\n",[199,9180,9181],{"class":201,"line":243},[199,9182,9183],{},"    S-->>Y: Manager, Clerk\n",[199,9185,9186],{"class":201,"line":249},[199,9187,9188],{},"    Y->>S: Add \"Supervisor\" and save\n",[199,9190,9191],{"class":201,"line":255},[199,9192,9193],{},"    Note over S: Table: Manager, Clerk, Supervisor\n",[199,9195,9196],{"class":201,"line":261},[199,9197,9198],{},"    X->>S: Rename \"Clerk\" and save\u003Cbr>Submits: Manager, Store Lead\n",[199,9200,9201],{"class":201,"line":267},[199,9202,9203],{},"    Note over S: \"Supervisor\" is not in the submission\u003Cbr>so it is treated as a delete\n",[199,9205,9206],{"class":201,"line":273},[199,9207,9208],{},"    S-->>X: Saved\n",[199,9210,9211],{"class":201,"line":279},[199,9212,9213],{},"    Note over Y: Y's new \"Supervisor\" is gone, with no warning\n",[17,9215,9216],{},"X did nothing wrong, and the service followed its rule exactly. The result is that Y's data was silently deleted. This is harder to spot than a broken limit: no error, nothing over quota, and the log shows one ordinary save.",[17,9218,9219,9220,9223],{},"The fix is to give the list a ",[49,9221,9222],{},"version",". The list endpoint returns a version value (a digest of the list contents is enough), the save request sends it back unchanged, and the server compares first:",[191,9225,9227],{"className":2483,"code":9226,"language":2485,"meta":15,"style":15},"@Transactional\npublic Result saveAll(long shopId, String version, List\u003CItem> items) {\n    shopMapper.lockById(shopId);                       \u002F\u002F still the first statement\n    List\u003CTitle> current = titleMapper.listByShop(shopId);\n    if (!versionOf(current).equals(version)) {\n        return Result.stale(current);                  \u002F\u002F stale draft: reject and return the latest list\n    }\n    ...\n}\n",[100,9228,9229,9233,9238,9243,9247,9252,9257,9261,9265],{"__ignoreMap":15},[199,9230,9231],{"class":201,"line":202},[199,9232,8450],{},[199,9234,9235],{"class":201,"line":25},[199,9236,9237],{},"public Result saveAll(long shopId, String version, List\u003CItem> items) {\n",[199,9239,9240],{"class":201,"line":213},[199,9241,9242],{},"    shopMapper.lockById(shopId);                       \u002F\u002F still the first statement\n",[199,9244,9245],{"class":201,"line":219},[199,9246,9113],{},[199,9248,9249],{"class":201,"line":225},[199,9250,9251],{},"    if (!versionOf(current).equals(version)) {\n",[199,9253,9254],{"class":201,"line":231},[199,9255,9256],{},"        return Result.stale(current);                  \u002F\u002F stale draft: reject and return the latest list\n",[199,9258,9259],{"class":201,"line":237},[199,9260,8475],{},[199,9262,9263],{"class":201,"line":243},[199,9264,9128],{},[199,9266,9267],{"class":201,"line":249},[199,9268,2502],{},[17,9270,9271],{},"If the version does not match, the whole save is rejected. The frontend says \"the list was changed by someone else\" and resets the draft from the latest list that came back. X has to redo the rename on the new list, and that cost is deliberate: redoing one edit is better than quietly deleting someone else's data.",[1036,9273,9274],{},[17,9275,9276,9278,9279,1312],{},[49,9277,8610],{},": when you see \"the client's full submission is the truth, anything missing gets deleted\", ask how the server knows the submission was edited from the latest state. The answer can only be a ",[49,9280,9281],{},"version check",[17,9283,9284,9285,9288],{},"Both tools solve the same thing, ",[49,9286,9287],{},"what you read may be out of date by the time you write",", but they fit different situations:",[105,9290,9291,9303],{},[108,9292,9293],{},[111,9294,9295,9297,9300],{},[114,9296],{},[114,9298,9299],{},"Row lock (pessimistic)",[114,9301,9302],{},"Version check (optimistic)",[121,9304,9305,9316,9327],{},[111,9306,9307,9310,9313],{},[126,9308,9309],{},"Gap between read and write",[126,9311,9312],{},"Within one request, milliseconds",[126,9314,9315],{},"Across requests, the user may edit for minutes",[111,9317,9318,9321,9324],{},[126,9319,9320],{},"On conflict",[126,9322,9323],{},"The later one waits, then continues on fresh data",[126,9325,9326],{},"The later one is rejected and must redo on fresh data",[111,9328,9329,9332,9335],{},[126,9330,9331],{},"Fits",[126,9333,9334],{},"Limits, uniqueness, decrements",[126,9336,9337],{},"Whole-list saves, long forms, draft-style editing",[17,9339,9340],{},"You cannot hold a database lock for the minutes a dialog stays open, so a version is the only option there. Both appear in the code above because \"compare the version, then write\" is itself check-then-act and still needs the lock to hold.",[58,9342,9344],{"id":9343},"_6-why-ai-tends-to-write-code-like-this","6. Why AI tends to write code like this",[17,9346,9347,9348,9351],{},"Looking back at what was sent back, the pieces share one trait: ",[49,9349,9350],{},"treated as a single request running top to bottom, all of them are correct",". My observation is that an AI generating code works from that viewpoint by default. It implements \"what happens after one request comes in\", while concurrency problems live \"between two requests\", in something the code text never spells out.",[17,9353,9354],{},"That also explains why these problems are especially hard to notice in AI-written code:",[348,9356,9357,9363,9369],{},[315,9358,9359,9362],{},[49,9360,9361],{},"The code looks complete."," Transactions, validation, error codes and comments are all there, and a reviewer is easily persuaded by the polish.",[315,9364,9365,9368],{},[49,9366,9367],{},"Self-testing always passes."," One person on one thread can never trigger the interleaving.",[315,9370,9371,9374],{},[49,9372,9373],{},"The AI is not ignorant of it."," In the same batch, a reorder endpoint did carry a staleness check, and another uniqueness rule was backed by a unique key. The knowledge was there. It just was not applied systematically to every write endpoint.",[17,9376,9377],{},"That last point sets the direction for improvement: what is missing is not knowledge but a checklist that gets run every time.",[58,9379,9381],{"id":9380},"_7-where-to-improve","7. Where to improve",[17,9383,9384,9387],{},[49,9385,9386],{},"For the reviewer: turn the questions above into a decision tree."," Walk through it for any write endpoint:",[191,9389,9391],{"className":193,"code":9390,"language":195,"meta":15,"style":15},"flowchart TD\n    S([\"A write endpoint\"]) --> Q1{\"Does whether or how it writes\u003Cbr>depend on something read first?\"}\n    Q1 -->|No| OK[\"Pass\"]\n    Q1 -->|Yes| Q2{\"What does it read?\"}\n    Q2 -->|Whether one row already exists| U{\"Is there a unique key?\"}\n    U -->|Yes| U1[\"Catch the duplicate-key error\u003Cbr>return a business message\"]\n    U -->|No| U2[\"Add a unique key\"]\n    Q2 -->|The size or contents of a set| L{\"Is the parent row locked\u003Cbr>inside the transaction?\"}\n    L -->|No| L1[\"Add a parent-row lock\"]\n    L -->|Yes| L2{\"Is the lock the first statement?\"}\n    L2 -->|Yes| OK\n    L2 -->|No| L3[\"Move the lock up\u003Cbr>use a programmatic transaction if needed\"]\n    Q2 -->|A full copy sent back by the client| V{\"Is there a version check?\"}\n    V -->|Yes| OK\n    V -->|No| V1[\"Add a version, reject stale drafts\"]\n    style OK fill:#DCFCE7,stroke:#16A34A,color:#14532D\n    style L3 fill:#FEF3C7,stroke:#D97706,color:#78350F\n",[100,9392,9393,9397,9402,9407,9412,9417,9422,9427,9432,9437,9442,9447,9452,9457,9462,9467,9472],{"__ignoreMap":15},[199,9394,9395],{"class":201,"line":202},[199,9396,205],{},[199,9398,9399],{"class":201,"line":25},[199,9400,9401],{},"    S([\"A write endpoint\"]) --> Q1{\"Does whether or how it writes\u003Cbr>depend on something read first?\"}\n",[199,9403,9404],{"class":201,"line":213},[199,9405,9406],{},"    Q1 -->|No| OK[\"Pass\"]\n",[199,9408,9409],{"class":201,"line":219},[199,9410,9411],{},"    Q1 -->|Yes| Q2{\"What does it read?\"}\n",[199,9413,9414],{"class":201,"line":225},[199,9415,9416],{},"    Q2 -->|Whether one row already exists| U{\"Is there a unique key?\"}\n",[199,9418,9419],{"class":201,"line":231},[199,9420,9421],{},"    U -->|Yes| U1[\"Catch the duplicate-key error\u003Cbr>return a business message\"]\n",[199,9423,9424],{"class":201,"line":237},[199,9425,9426],{},"    U -->|No| U2[\"Add a unique key\"]\n",[199,9428,9429],{"class":201,"line":243},[199,9430,9431],{},"    Q2 -->|The size or contents of a set| L{\"Is the parent row locked\u003Cbr>inside the transaction?\"}\n",[199,9433,9434],{"class":201,"line":249},[199,9435,9436],{},"    L -->|No| L1[\"Add a parent-row lock\"]\n",[199,9438,9439],{"class":201,"line":255},[199,9440,9441],{},"    L -->|Yes| L2{\"Is the lock the first statement?\"}\n",[199,9443,9444],{"class":201,"line":261},[199,9445,9446],{},"    L2 -->|Yes| OK\n",[199,9448,9449],{"class":201,"line":267},[199,9450,9451],{},"    L2 -->|No| L3[\"Move the lock up\u003Cbr>use a programmatic transaction if needed\"]\n",[199,9453,9454],{"class":201,"line":273},[199,9455,9456],{},"    Q2 -->|A full copy sent back by the client| V{\"Is there a version check?\"}\n",[199,9458,9459],{"class":201,"line":279},[199,9460,9461],{},"    V -->|Yes| OK\n",[199,9463,9464],{"class":201,"line":285},[199,9465,9466],{},"    V -->|No| V1[\"Add a version, reject stale drafts\"]\n",[199,9468,9469],{"class":201,"line":651},[199,9470,9471],{},"    style OK fill:#DCFCE7,stroke:#16A34A,color:#14532D\n",[199,9473,9474],{"class":201,"line":970},[199,9475,9476],{},"    style L3 fill:#FEF3C7,stroke:#D97706,color:#78350F\n",[17,9478,9479,9482],{},[49,9480,9481],{},"For the AI: write the review conclusions into rules it reads every time."," A verbal correction only lasts for the current conversation. Next time it starts from the single-request viewpoint again. What I did was put the conclusions into the project's instruction file, so it goes through them while drafting a plan and while self-testing:",[191,9484,9486],{"className":6559,"code":9485,"language":6561,"meta":15,"style":15},"Self-check for every create, update and delete endpoint:\n1. Check-then-act must be serialized: count limits, name uniqueness and\n   set-consistency checks need either a unique key behind them or a lock on\n   the parent row inside the transaction. A transaction alone is not mutual exclusion.\n2. The lock must come before any plain read in the transaction. If you must\n   query first to know what to lock, do that query outside the transaction and\n   wrap \"lock, read, write\" in a programmatic transaction.\n3. Whole-list or whole-object overwrites must carry a version: for semantics\n   like \"anything missing from the submission is deleted\", verify the version\n   the draft was based on, and reject stale drafts with the latest data.\nIn every plan, state for each write endpoint: what serializes it.\n",[100,9487,9488,9493,9498,9503,9508,9513,9518,9523,9528,9533,9538],{"__ignoreMap":15},[199,9489,9490],{"class":201,"line":202},[199,9491,9492],{},"Self-check for every create, update and delete endpoint:\n",[199,9494,9495],{"class":201,"line":25},[199,9496,9497],{},"1. Check-then-act must be serialized: count limits, name uniqueness and\n",[199,9499,9500],{"class":201,"line":213},[199,9501,9502],{},"   set-consistency checks need either a unique key behind them or a lock on\n",[199,9504,9505],{"class":201,"line":219},[199,9506,9507],{},"   the parent row inside the transaction. A transaction alone is not mutual exclusion.\n",[199,9509,9510],{"class":201,"line":225},[199,9511,9512],{},"2. The lock must come before any plain read in the transaction. If you must\n",[199,9514,9515],{"class":201,"line":231},[199,9516,9517],{},"   query first to know what to lock, do that query outside the transaction and\n",[199,9519,9520],{"class":201,"line":237},[199,9521,9522],{},"   wrap \"lock, read, write\" in a programmatic transaction.\n",[199,9524,9525],{"class":201,"line":243},[199,9526,9527],{},"3. Whole-list or whole-object overwrites must carry a version: for semantics\n",[199,9529,9530],{"class":201,"line":249},[199,9531,9532],{},"   like \"anything missing from the submission is deleted\", verify the version\n",[199,9534,9535],{"class":201,"line":255},[199,9536,9537],{},"   the draft was based on, and reject stale drafts with the latest data.\n",[199,9539,9540],{"class":201,"line":261},[199,9541,9542],{},"In every plan, state for each write endpoint: what serializes it.\n",[17,9544,9545,9546,9549],{},"The last line is the key one. Requiring the plan to ",[49,9547,9548],{},"state explicitly what serializes each endpoint"," turns the question it would not ask by default into a blank it must fill in. Wherever it cannot fill the blank is where the review needs to look.",[17,9551,9552,9555,9556],{},[49,9553,9554],{},"For the fix itself: it needs review too."," Having the rules written down does not mean you can relax. In the second review round of this batch, the AI added an early return while fixing a scope check. The issue that had been raised was fixed correctly, but the early return also skipped an existing check further down, the one verifying that the resource still exists, and that kind of problem was not on the checklist. A checklist guards against the kinds of problems you have already seen, not new ones, and every round of changes can bring something from outside it. So a re-review cannot stop at \"were last round's comments addressed\". It also has to ask ",[49,9557,9558],{},"\"what does this change bypass?\"",[58,9560,9562],{"id":9561},"_8-principles-that-transfer","8. Principles that transfer",[312,9564,9565,9571,9577,9583,9589,9595],{},[315,9566,9567,9570],{},[49,9568,9569],{},"Reading AI code line by line is not enough. Ask what happens when two requests arrive together."," Polish does not mean concurrency safety, and a sequence diagram exposes problems more readily than the code does.",[315,9572,9573,9576],{},[49,9574,9575],{},"A transaction handles \"all or nothing\". It does not handle queuing."," Queuing comes only from a unique key or a lock.",[315,9578,9579,9582],{},[49,9580,9581],{},"A lock has a position requirement."," Under REPEATABLE READ, one plain read ahead of the lock means everything read afterwards is old.",[315,9584,9585,9588],{},[49,9586,9587],{},"Use a version for read-then-write across requests, and a lock within a request."," Both solve the same problem: what you read is out of date by the time you write.",[315,9590,9591,9594],{},[49,9592,9593],{},"What the AI lacks is often not knowledge but a checklist that runs every time."," Writing review conclusions into its standing rules works better than correcting it again each time.",[315,9596,9597,9600],{},[49,9598,9599],{},"The fix needs review too."," A checklist only guards against problems you have seen. When re-reviewing, check last round's comments, then check which existing validations the new change bypasses.",[1036,9602,9603],{},[17,9604,9605],{},"In one sentence: the AI gets a single request right, and the human asks what happens between requests. Then hand that question to the AI as well, so it asks itself first every time.",[1042,9607,1044],{},{"title":15,"searchDepth":25,"depth":25,"links":9609},[9610,9611,9612,9613,9614,9615,9616,9617],{"id":8436,"depth":25,"text":8437},{"id":8497,"depth":25,"text":8498},{"id":8636,"depth":25,"text":8637},{"id":8869,"depth":25,"text":8870},{"id":9090,"depth":25,"text":9091},{"id":9343,"depth":25,"text":9344},{"id":9380,"depth":25,"text":9381},{"id":9561,"depth":25,"text":9562},"An AI delivered a batch of write endpoints with transactions, validation and comments. Each line holds up on its own, yet none of it survives concurrency. From the reviewer's seat, four sequence diagrams cover check-then-act, lock placement and whole-list overwrites, plus how to stop the AI from repeating them.","\u002Farticles\u002Freviewing-ai-code-concurrency.svg",{},"\u002Farticles\u002Freviewing-ai-code-concurrency",{"title":8423,"description":9618},{"loc":9621},"articles\u002Freviewing-ai-code-concurrency",[1066,3049],"jFfgSJZhVLsU3RqwC_IoG7mWUDXU57UDnaPUuWu60pU",{"id":9628,"title":9629,"body":9630,"date":12637,"description":12638,"extension":28,"head":27,"image":12639,"meta":12640,"navigation":30,"ogImage":27,"path":12641,"rating":7005,"readingTime":5016,"robots":27,"schemaOrg":27,"seo":12642,"sitemap":12643,"stem":12644,"tags":12645,"__hash__":12647},"articles_en\u002Farticles\u002Fspa-hash-seo-prerender.md","One HTML File, Two Apps: Making a Hash-Routed SPA's Home Page Crawlable Without Touching the Router",{"type":7,"value":9631,"toc":12616},[9632,9649,9687,9694,9701,9816,9833,9846,9887,9890,9932,9942,9946,9949,9980,9986,10004,10010,10016,10102,10105,10109,10117,10166,10169,10199,10208,10251,10258,10262,10266,10273,10616,10619,10668,10671,10728,10735,10739,10752,11135,11138,11222,11225,11281,11285,11490,11509,11528,11532,11536,11539,11545,11609,11616,11620,11630,11675,11689,11699,11746,11749,11753,11764,11767,11782,11785,11789,11811,11824,11830,11935,11941,11951,11958,11962,11975,11992,11998,12089,12099,12188,12191,12202,12206,12209,12224,12385,12392,12395,12481,12488,12492,12495,12500,12524,12529,12574,12578,12613],[17,9633,9634,9635,9637,9638,9640,9641,9644,9645,9648],{},"\"Just get rid of the ",[100,9636,6521],{}," in the URL\" sounds like a one-line router change. It isn't, and the ",[100,9639,6521],{}," turned out not to be the real problem anyway. ",[49,9642,9643],{},"Crawlers couldn't read our content because the HTML didn't contain any."," On top of that, giving the home page a clean URL runs into a constraint that's easy to miss: ",[49,9646,9647],{},"a domain's root path can only serve one file",". This post is about how I got a marketing home page, full text and all, in front of search engines without changing how the admin app routes.",[43,9650,9651,9656],{},[17,9652,9653],{},[49,9654,9655],{},"The problem at a glance",[348,9657,9658,9667,9677],{},[315,9659,9660,9662,9663,9666],{},[49,9661,2523],{},": A Vue 3 + Vite admin app with hash routing. The marketing home page is just another route in that app, at ",[100,9664,9665],{},"https:\u002F\u002Fwww.example.com\u002F#\u002Flanding\u002Fhome",". We wanted it to show up in search, but a crawler hitting the domain root got a 4 kB shell with a loading spinner and nothing else.",[315,9668,9669,9672,9673,9676],{},[49,9670,9671],{},"Constraints",": No admin URL could change. That includes ",[100,9674,9675],{},"\u002F#\u002Flogin",", short links already sent out by SMS, and third-party login callbacks. The test environment also lives in a subdirectory of a shared domain, where a server-side fallback isn't available.",[315,9678,9679,9682,9683,9686],{},[49,9680,9681],{},"What you'll take away",": How I chose between three options, a reusable way to serve two apps from one ",[100,9684,9685],{},"index.html",", the skeleton of a build-time prerender plugin, and four problems that only show up once you actually ship this.",[58,9688,9690,9691,9693],{"id":9689},"_1-where-it-started-is-really-the-problem","1. Where It Started: Is ",[100,9692,6521],{}," Really the Problem?",[17,9695,9696,9697,9700],{},"Let's look at what a crawler actually gets. A request to ",[100,9698,9699],{},"https:\u002F\u002Fwww.example.com\u002F"," came back with roughly this:",[191,9702,9706],{"className":9703,"code":9704,"language":9705,"meta":15,"style":15},"language-html shiki shiki-themes github-light github-dark github-dark","\u003Chead>\n  \u003Ctitle>Admin\u003C\u002Ftitle>\n\u003C\u002Fhead>\n\u003Cbody>\n  \u003Cdiv id=\"app\">\u003C!-- just a loading spinner -->\u003C\u002Fdiv>\n  \u003Cscript type=\"module\" src=\".\u002Fassets\u002Fjs\u002Findex-xxxx.js\">\u003C\u002Fscript>\n\u003C\u002Fbody>\n","html",[100,9707,9708,9718,9733,9742,9751,9778,9808],{"__ignoreMap":15},[199,9709,9710,9712,9715],{"class":201,"line":202},[199,9711,5865],{"class":1629},[199,9713,9714],{"class":1625},"head",[199,9716,9717],{"class":1629},">\n",[199,9719,9720,9723,9726,9729,9731],{"class":201,"line":25},[199,9721,9722],{"class":1629},"  \u003C",[199,9724,9725],{"class":1625},"title",[199,9727,9728],{"class":1629},">Admin\u003C\u002F",[199,9730,9725],{"class":1625},[199,9732,9717],{"class":1629},[199,9734,9735,9738,9740],{"class":201,"line":213},[199,9736,9737],{"class":1629},"\u003C\u002F",[199,9739,9714],{"class":1625},[199,9741,9717],{"class":1629},[199,9743,9744,9746,9749],{"class":201,"line":219},[199,9745,5865],{"class":1629},[199,9747,9748],{"class":1625},"body",[199,9750,9717],{"class":1629},[199,9752,9753,9755,9758,9761,9763,9766,9769,9772,9774,9776],{"class":201,"line":225},[199,9754,9722],{"class":1629},[199,9756,9757],{"class":1625},"div",[199,9759,9760],{"class":1619}," id",[199,9762,3697],{"class":1629},[199,9764,9765],{"class":1633},"\"app\"",[199,9767,9768],{"class":1629},">",[199,9770,9771],{"class":2468},"\u003C!-- just a loading spinner -->",[199,9773,9737],{"class":1629},[199,9775,9757],{"class":1625},[199,9777,9717],{"class":1629},[199,9779,9780,9782,9785,9788,9790,9793,9796,9798,9801,9804,9806],{"class":201,"line":231},[199,9781,9722],{"class":1629},[199,9783,9784],{"class":1625},"script",[199,9786,9787],{"class":1619}," type",[199,9789,3697],{"class":1629},[199,9791,9792],{"class":1633},"\"module\"",[199,9794,9795],{"class":1619}," src",[199,9797,3697],{"class":1629},[199,9799,9800],{"class":1633},"\".\u002Fassets\u002Fjs\u002Findex-xxxx.js\"",[199,9802,9803],{"class":1629},">\u003C\u002F",[199,9805,9784],{"class":1625},[199,9807,9717],{"class":1629},[199,9809,9810,9812,9814],{"class":201,"line":237},[199,9811,9737],{"class":1629},[199,9813,9748],{"class":1625},[199,9815,9717],{"class":1629},[17,9817,9818,9819,9821,9822,9825,9826,3933,9829,9832],{},"No body text, no ",[100,9820,1639],{},", no ",[100,9823,9824],{},"og:"," tags for link previews. ",[100,9827,9828],{},"robots.txt",[100,9830,9831],{},"sitemap.xml"," returned the very same HTML, because the static host serves the home page for any path that doesn't exist.",[17,9834,9835,9836,9838,9839,9845],{},"Now for the ",[100,9837,6521],{},". ",[49,9840,9841,9842,9844],{},"Everything after the ",[100,9843,6521],{}," in a URL (the fragment) never leaves the browser."," It isn't sent to the server at all. That has two consequences:",[312,9847,9848,9864],{},[315,9849,9850,9851,2625,9854,9856,9857,9860,9861,9863],{},"As far as a crawler is concerned, ",[100,9852,9853],{},"\u002F#\u002Flanding\u002Fhome",[100,9855,9675],{},", and ",[100,9858,9859],{},"\u002F#\u002Fanything"," are all the same URL: ",[100,9862,5625],{},". Pages behind hash routing can't be indexed individually.",[315,9865,9866,9871,9872,2797,9875,9877,9878,9880,9881,9883,9884,9886],{},[49,9867,9868,9869,1312],{},"The server can't do anything about the ",[100,9870,6521],{}," The first thing I asked was whether ops could just add a rule. They can't. All ops can control is what a given path returns, say a 302 from ",[100,9873,9874],{},"\u002Flanding\u002Fhome",[100,9876,9853],{},". The link you share looks clean, but the ",[100,9879,6521],{}," is back in the address bar the moment it loads, and a crawler following the redirect drops the fragment and indexes ",[100,9882,5625],{}," anyway. The front-end router puts the ",[100,9885,6521],{}," there, so the front end has to take it away.",[17,9888,9889],{},"So this is really two separate problems tangled together:",[105,9891,9892,9907],{},[108,9893,9894],{},[111,9895,9896,9898,9901],{},[114,9897,4557],{},[114,9899,9900],{},"What causes it",[114,9902,9903,9904,9906],{},"Does dropping the ",[100,9905,6521],{}," fix it?",[121,9908,9909,9920],{},[111,9910,9911,9914,9917],{},[126,9912,9913],{},"The home page has no clean URL of its own",[126,9915,9916],{},"How hash-routed URLs are shaped",[126,9918,9919],{},"Yes",[111,9921,9922,9925,9928],{},[126,9923,9924],{},"Crawlers can't read the body text",[126,9926,9927],{},"Everything is rendered client-side",[126,9929,9930],{},[49,9931,5559],{},[17,9933,9934,9935,9938,9939,9941],{},"Googlebot does run JavaScript, but rendering happens in a deferred second pass that's slow and not guaranteed. Link-preview scrapers, and most crawlers that only read raw HTML, don't run JS at all. ",[49,9936,9937],{},"The second problem is the one that matters for SEO."," Dropping the ",[100,9940,6521],{}," is just a prerequisite.",[58,9943,9945],{"id":9944},"_2-three-options-and-one-constraint-you-cant-get-around","2. Three Options and One Constraint You Can't Get Around",[17,9947,9948],{},"There were three obvious ways to go.",[17,9950,9951,9954,9955,9958,9959,9962,9963,3933,9966,9968,9969,9972,9973,9975,9976,9979],{},[49,9952,9953],{},"Option 1: move the whole app to history mode."," Swap ",[100,9956,9957],{},"createWebHashHistory"," for ",[100,9960,9961],{},"createWebHistory",", and URLs turn into ",[100,9964,9965],{},"\u002Flogin",[100,9967,9874],{},". The catch is that every admin URL changes, so old links need a compatibility shim. The relative asset base ",[100,9970,9971],{},".\u002F"," has to become absolute, or ",[100,9974,9874],{}," will go looking for ",[100,9977,9978],{},"\u002Flanding\u002Fassets\u002F...",". And every environment's static host needs a 404 fallback, which my test environment, tucked into a subdirectory of a shared domain, can't have.",[17,9981,9982,9985],{},[49,9983,9984],{},"Option 2: pull the home page out into its own project on the same domain."," This is the cleanest way to organize the code. But it runs straight into the constraint:",[561,9987,9988],{},[17,9989,9990,9993,9994,9996,9997,9999,10000,10003],{},[49,9991,9992],{},"The root path can only serve one file."," The admin URL is ",[100,9995,9675],{},", which the server sees as plain ",[100,9998,5625],{}," because the fragment never arrives. So you can't have both \"the home page owns the domain root\" and \"admin URLs stay the same\" through deployment alone. Either the home page gives up the root and moves into a subdirectory, leaving the admin shell as the site's front page, or the admin app moves to ",[100,10001,10002],{},"\u002Fapp\u002F"," and every one of its URLs changes. The server simply can't tell someone who came for the home page from someone who came to log in.",[17,10005,10006,10009],{},[49,10007,10008],{},"Option 3: use history mode for the home page only and leave everything else on hash."," You'd pick the router instance at startup based on the URL. It works, but now a single app runs two routing modes and your navigation guards have to handle crossing between them. It also only fixes the URL, not the missing content.",[17,10011,10012,10013],{},"Every option came with a cost I wasn't willing to pay. But turn that constraint around and it becomes the answer: ",[49,10014,10015],{},"if the root path can only serve one file, make that one file do two jobs.",[105,10017,10018,10033],{},[108,10019,10020],{},[111,10021,10022,10024,10027,10030],{},[114,10023],{},[114,10025,10026],{},"Full history mode",[114,10028,10029],{},"Separate project",[114,10031,10032],{},"One HTML, two apps",[121,10034,10035,10053,10067,10079,10091],{},[111,10036,10037,10040,10044,10049],{},[126,10038,10039],{},"Home page URL",[126,10041,10042],{},[100,10043,9874],{},[126,10045,10046,10048],{},[100,10047,5625],{}," or a subdirectory, not both",[126,10050,10051],{},[100,10052,5625],{},[111,10054,10055,10058,10061,10064],{},[126,10056,10057],{},"Admin URLs",[126,10059,10060],{},"All change",[126,10062,10063],{},"Either unchanged or all change",[126,10065,10066],{},"Unchanged",[111,10068,10069,10072,10074,10077],{},[126,10070,10071],{},"Needs a server fallback",[126,10073,9919],{},[126,10075,10076],{},"Partly",[126,10078,5559],{},[111,10080,10081,10084,10087,10089],{},[126,10082,10083],{},"Crawlers can read the body",[126,10085,10086],{},"No, still client-rendered",[126,10088,9919],{},[126,10090,9919],{},[111,10092,10093,10096,10098,10100],{},[126,10094,10095],{},"Home page and admin ship independently",[126,10097,5559],{},[126,10099,9919],{},[126,10101,5559],{},[17,10103,10104],{},"That last row is what it costs. More on that in section 8.",[58,10106,10108],{"id":10107},"_3-the-approach-one-html-file-two-apps","3. The Approach: One HTML File, Two Apps",[17,10110,10111,10112],{},"The whole idea fits in a sentence: ",[49,10113,10114,10116],{},[100,10115,9685],{}," ships with the home page's complete static content already in it, and a tiny inline script at the very top checks the hash in the address bar to decide whether this page load should run the home page code or the admin code.",[191,10118,10120],{"className":193,"code":10119,"language":195,"meta":15,"style":15},"flowchart TD\n    R[\"Request \u002F (same request for any hash)\"] --> H[\"index.html\u003Cbr>contains the home page's static HTML\"]\n    H --> S{\"Inline boot script\u003Cbr>checks location.hash\"}\n    S -- \"empty, #\u002F, #\u002Flanding\u002Fhome\" --> L[\"Load the home page entry\u003Cbr>hydrate the existing HTML\"]\n    S -- \"any other #\u002Fxxx\" --> A[\"Remove the home page content\u003Cbr>load the admin entry, untouched\"]\n    L --> LR[\"Address bar: \u002F\u003Cbr>only the home page's JS and CSS\"]\n    A --> AR[\"Address bar: \u002F#\u002Flogin\u003Cbr>behaves exactly as before\"]\n    style S fill:#E1EDFC,stroke:#3B6FD4,stroke-width:2px\n    style H fill:#E1EDFC,stroke:#3B6FD4,stroke-width:2px\n",[100,10121,10122,10126,10131,10136,10141,10146,10151,10156,10161],{"__ignoreMap":15},[199,10123,10124],{"class":201,"line":202},[199,10125,205],{},[199,10127,10128],{"class":201,"line":25},[199,10129,10130],{},"    R[\"Request \u002F (same request for any hash)\"] --> H[\"index.html\u003Cbr>contains the home page's static HTML\"]\n",[199,10132,10133],{"class":201,"line":213},[199,10134,10135],{},"    H --> S{\"Inline boot script\u003Cbr>checks location.hash\"}\n",[199,10137,10138],{"class":201,"line":219},[199,10139,10140],{},"    S -- \"empty, #\u002F, #\u002Flanding\u002Fhome\" --> L[\"Load the home page entry\u003Cbr>hydrate the existing HTML\"]\n",[199,10142,10143],{"class":201,"line":225},[199,10144,10145],{},"    S -- \"any other #\u002Fxxx\" --> A[\"Remove the home page content\u003Cbr>load the admin entry, untouched\"]\n",[199,10147,10148],{"class":201,"line":231},[199,10149,10150],{},"    L --> LR[\"Address bar: \u002F\u003Cbr>only the home page's JS and CSS\"]\n",[199,10152,10153],{"class":201,"line":237},[199,10154,10155],{},"    A --> AR[\"Address bar: \u002F#\u002Flogin\u003Cbr>behaves exactly as before\"]\n",[199,10157,10158],{"class":201,"line":243},[199,10159,10160],{},"    style S fill:#E1EDFC,stroke:#3B6FD4,stroke-width:2px\n",[199,10162,10163],{"class":201,"line":249},[199,10164,10165],{},"    style H fill:#E1EDFC,stroke:#3B6FD4,stroke-width:2px\n",[17,10167,10168],{},"That keeps all three audiences happy at once:",[348,10170,10171,10180,10193],{},[315,10172,10173,10176,10177,10179],{},[49,10174,10175],{},"Crawlers"," request ",[100,10178,5625],{}," and get HTML with body text, a title, and a description. Whether they run JS no longer matters.",[315,10181,10182,10185,10186,10188,10189,10192],{},[49,10183,10184],{},"Home page visitors"," see a clean ",[100,10187,5625],{}," in the address bar. The home page entry never loads vue-router, and the hash router was the only thing adding ",[100,10190,10191],{},"#\u002F"," in the first place.",[315,10194,10195,10198],{},[49,10196,10197],{},"Admin users"," notice nothing. Hash routing, the deploy directory, and every link out in the wild stay exactly as they were.",[17,10200,10201,10202,10205,10206,346],{},"So where does the static content come from? At ",[49,10203,10204],{},"build time",", I render the home page component once with Vue's server renderer and write the result into the built ",[100,10207,9685],{},[191,10209,10211],{"className":193,"code":10210,"language":195,"meta":15,"style":15},"flowchart LR\n    C[\"Client build\u003Cbr>vite build\"] --> W[\"Output written\u003Cbr>dist\u002Findex.html, container empty\"]\n    W --> S[\"SSR build\u003Cbr>home page entry only\"]\n    S --> R[\"renderToString\u003Cbr>home page HTML\"]\n    R --> P[\"Fix asset URLs\u003Cbr>write back to dist\u002Findex.html\"]\n    P --> O[\"Generate robots.txt\u003Cbr>sitemap.xml\"]\n    style S fill:#E1EDFC,stroke:#3B6FD4,stroke-width:2px\n    style R fill:#E1EDFC,stroke:#3B6FD4,stroke-width:2px\n",[100,10212,10213,10217,10222,10227,10232,10237,10242,10246],{"__ignoreMap":15},[199,10214,10215],{"class":201,"line":202},[199,10216,1201],{},[199,10218,10219],{"class":201,"line":25},[199,10220,10221],{},"    C[\"Client build\u003Cbr>vite build\"] --> W[\"Output written\u003Cbr>dist\u002Findex.html, container empty\"]\n",[199,10223,10224],{"class":201,"line":213},[199,10225,10226],{},"    W --> S[\"SSR build\u003Cbr>home page entry only\"]\n",[199,10228,10229],{"class":201,"line":219},[199,10230,10231],{},"    S --> R[\"renderToString\u003Cbr>home page HTML\"]\n",[199,10233,10234],{"class":201,"line":225},[199,10235,10236],{},"    R --> P[\"Fix asset URLs\u003Cbr>write back to dist\u002Findex.html\"]\n",[199,10238,10239],{"class":201,"line":231},[199,10240,10241],{},"    P --> O[\"Generate robots.txt\u003Cbr>sitemap.xml\"]\n",[199,10243,10244],{"class":201,"line":237},[199,10245,10160],{},[199,10247,10248],{"class":201,"line":243},[199,10249,10250],{},"    style R fill:#E1EDFC,stroke:#3B6FD4,stroke-width:2px\n",[17,10252,10253,10254,10257],{},"To be clear, this isn't SSR at runtime. There's no Node server, and the output is still a folder of static files that gets uploaded to object storage like before. This is usually called ",[49,10255,10256],{},"prerendering",", or static generation.",[58,10259,10261],{"id":10260},"_4-implementation","4. Implementation",[2031,10263,10265],{"id":10264},"_41-the-boot-script","4.1 The boot script",[17,10267,10268,10269,10272],{},"It sits in ",[100,10270,10271],{},"\u003Chead>"," and has to be inline and synchronous, since it needs to finish before the browser paints anything:",[191,10274,10276],{"className":9703,"code":10275,"language":9705,"meta":15,"style":15},"\u003Cscript>\n  (function () {\n    var hash = location.hash;\n    var path = hash.replace(\u002F^#\u002F, \"\").split(\"?\")[0].replace(\u002F\\\u002F+$\u002F, \"\");\n    var isAdminHash = \u002F^#\\\u002F\u002F.test(hash) && path !== \"\" && path !== \"\u002Flanding\" && path !== \"\u002Flanding\u002Fhome\";\n    \u002F\u002F An existing short link, \u002Fm, only gets here because unknown paths fall back to index.html. Hand it back to admin\n    var isShortEntry = \u002F\\\u002Fm$\u002F.test(location.pathname);\n    var landing = !isAdminHash && !isShortEntry;\n    window.__LANDING__ = landing;\n    document.documentElement.className += landing ? \" boot-landing\" : \" boot-admin\";\n    if (landing) {\n      \u002F\u002F Tidy old URLs like \u002F#\u002Flanding\u002Fhome and \u002F#\u002F into a clean one, without a reload\n      if (\u002F^#\\\u002F\u002F.test(hash)) history.replaceState(history.state, \"\", location.pathname + location.search);\n    } else {\n      document.title = \"Admin\";\n    }\n  })();\n\u003C\u002Fscript>\n",[100,10277,10278,10286,10297,10310,10379,10438,10443,10471,10493,10503,10525,10532,10537,10577,10587,10599,10603,10608],{"__ignoreMap":15},[199,10279,10280,10282,10284],{"class":201,"line":202},[199,10281,5865],{"class":1629},[199,10283,9784],{"class":1625},[199,10285,9717],{"class":1629},[199,10287,10288,10291,10294],{"class":201,"line":25},[199,10289,10290],{"class":1629},"  (",[199,10292,10293],{"class":2436},"function",[199,10295,10296],{"class":1629}," () {\n",[199,10298,10299,10302,10305,10307],{"class":201,"line":213},[199,10300,10301],{"class":2436},"    var",[199,10303,10304],{"class":1629}," hash ",[199,10306,3697],{"class":2436},[199,10308,10309],{"class":1629}," location.hash;\n",[199,10311,10312,10314,10317,10319,10322,10325,10327,10329,10332,10335,10337,10339,10342,10344,10346,10348,10350,10353,10355,10358,10360,10362,10364,10368,10371,10373,10375,10377],{"class":201,"line":219},[199,10313,10301],{"class":2436},[199,10315,10316],{"class":1629}," path ",[199,10318,3697],{"class":2436},[199,10320,10321],{"class":1629}," hash.",[199,10323,10324],{"class":1619},"replace",[199,10326,2458],{"class":1629},[199,10328,5625],{"class":1633},[199,10330,10331],{"class":2436},"^",[199,10333,6521],{"class":10334},"sQeJH",[199,10336,5625],{"class":1633},[199,10338,2625],{"class":1629},[199,10340,10341],{"class":1633},"\"\"",[199,10343,8836],{"class":1629},[199,10345,5922],{"class":1619},[199,10347,2458],{"class":1629},[199,10349,5713],{"class":1633},[199,10351,10352],{"class":1629},")[",[199,10354,833],{"class":3645},[199,10356,10357],{"class":1629},"].",[199,10359,10324],{"class":1619},[199,10361,2458],{"class":1629},[199,10363,5625],{"class":1633},[199,10365,10367],{"class":10366},"sAxt1","\\\u002F",[199,10369,10370],{"class":2436},"+$",[199,10372,5625],{"class":1633},[199,10374,2625],{"class":1629},[199,10376,10341],{"class":1633},[199,10378,2463],{"class":1629},[199,10380,10381,10383,10386,10388,10391,10393,10395,10397,10399,10401,10404,10407,10410,10412,10415,10417,10420,10422,10424,10427,10429,10431,10433,10436],{"class":201,"line":225},[199,10382,10301],{"class":2436},[199,10384,10385],{"class":1629}," isAdminHash ",[199,10387,3697],{"class":2436},[199,10389,10390],{"class":1633}," \u002F",[199,10392,10331],{"class":2436},[199,10394,6521],{"class":10334},[199,10396,10367],{"class":10366},[199,10398,5625],{"class":1633},[199,10400,1312],{"class":1629},[199,10402,10403],{"class":1619},"test",[199,10405,10406],{"class":1629},"(hash) ",[199,10408,10409],{"class":2436},"&&",[199,10411,10316],{"class":1629},[199,10413,10414],{"class":2436},"!==",[199,10416,5690],{"class":1633},[199,10418,10419],{"class":2436}," &&",[199,10421,10316],{"class":1629},[199,10423,10414],{"class":2436},[199,10425,10426],{"class":1633}," \"\u002Flanding\"",[199,10428,10419],{"class":2436},[199,10430,10316],{"class":1629},[199,10432,10414],{"class":2436},[199,10434,10435],{"class":1633}," \"\u002Flanding\u002Fhome\"",[199,10437,3703],{"class":1629},[199,10439,10440],{"class":201,"line":231},[199,10441,10442],{"class":2468},"    \u002F\u002F An existing short link, \u002Fm, only gets here because unknown paths fall back to index.html. Hand it back to admin\n",[199,10444,10445,10447,10450,10452,10454,10456,10459,10462,10464,10466,10468],{"class":201,"line":237},[199,10446,10301],{"class":2436},[199,10448,10449],{"class":1629}," isShortEntry ",[199,10451,3697],{"class":2436},[199,10453,10390],{"class":1633},[199,10455,10367],{"class":10366},[199,10457,10458],{"class":10334},"m",[199,10460,10461],{"class":2436},"$",[199,10463,5625],{"class":1633},[199,10465,1312],{"class":1629},[199,10467,10403],{"class":1619},[199,10469,10470],{"class":1629},"(location.pathname);\n",[199,10472,10473,10475,10478,10480,10483,10486,10488,10490],{"class":201,"line":243},[199,10474,10301],{"class":2436},[199,10476,10477],{"class":1629}," landing ",[199,10479,3697],{"class":2436},[199,10481,10482],{"class":2436}," !",[199,10484,10485],{"class":1629},"isAdminHash ",[199,10487,10409],{"class":2436},[199,10489,10482],{"class":2436},[199,10491,10492],{"class":1629},"isShortEntry;\n",[199,10494,10495,10498,10500],{"class":201,"line":249},[199,10496,10497],{"class":1629},"    window.__LANDING__ ",[199,10499,3697],{"class":2436},[199,10501,10502],{"class":1629}," landing;\n",[199,10504,10505,10508,10511,10513,10515,10518,10520,10523],{"class":201,"line":255},[199,10506,10507],{"class":1629},"    document.documentElement.className ",[199,10509,10510],{"class":2436},"+=",[199,10512,10477],{"class":1629},[199,10514,5533],{"class":2436},[199,10516,10517],{"class":1633}," \" boot-landing\"",[199,10519,6118],{"class":2436},[199,10521,10522],{"class":1633}," \" boot-admin\"",[199,10524,3703],{"class":1629},[199,10526,10527,10529],{"class":201,"line":261},[199,10528,3671],{"class":2436},[199,10530,10531],{"class":1629}," (landing) {\n",[199,10533,10534],{"class":201,"line":267},[199,10535,10536],{"class":2468},"      \u002F\u002F Tidy old URLs like \u002F#\u002Flanding\u002Fhome and \u002F#\u002F into a clean one, without a reload\n",[199,10538,10539,10542,10544,10546,10548,10550,10552,10554,10556,10558,10561,10564,10567,10569,10572,10574],{"class":201,"line":273},[199,10540,10541],{"class":2436},"      if",[199,10543,3724],{"class":1629},[199,10545,5625],{"class":1633},[199,10547,10331],{"class":2436},[199,10549,6521],{"class":10334},[199,10551,10367],{"class":10366},[199,10553,5625],{"class":1633},[199,10555,1312],{"class":1629},[199,10557,10403],{"class":1619},[199,10559,10560],{"class":1629},"(hash)) history.",[199,10562,10563],{"class":1619},"replaceState",[199,10565,10566],{"class":1629},"(history.state, ",[199,10568,10341],{"class":1633},[199,10570,10571],{"class":1629},", location.pathname ",[199,10573,5042],{"class":2436},[199,10575,10576],{"class":1629}," location.search);\n",[199,10578,10579,10582,10585],{"class":201,"line":279},[199,10580,10581],{"class":1629},"    } ",[199,10583,10584],{"class":2436},"else",[199,10586,3666],{"class":1629},[199,10588,10589,10592,10594,10597],{"class":201,"line":285},[199,10590,10591],{"class":1629},"      document.title ",[199,10593,3697],{"class":2436},[199,10595,10596],{"class":1633}," \"Admin\"",[199,10598,3703],{"class":1629},[199,10600,10601],{"class":201,"line":651},[199,10602,8475],{"class":1629},[199,10604,10605],{"class":201,"line":970},[199,10606,10607],{"class":1629},"  })();\n",[199,10609,10610,10612,10614],{"class":201,"line":976},[199,10611,9737],{"class":1629},[199,10613,9784],{"class":1625},[199,10615,9717],{"class":1629},[17,10617,10618],{},"Four things worth pointing out:",[348,10620,10621,10634,10647,10659],{},[315,10622,10623,10629,10630,10633],{},[49,10624,10625,10626,10628],{},"Only a hash that starts with ",[100,10627,10191],{}," counts as a route."," A plain anchor like ",[100,10631,10632],{},"#section",", or a fragment some ad platform tacked on, still means the home page.",[315,10635,10636,10639,10640,10642,10643,10646],{},[49,10637,10638],{},"Track down everything that quietly relies on the fallback."," The static host serves ",[100,10641,9685],{}," for unknown paths, and we had a short link, ",[100,10644,10645],{},"\u002Fm",", that depended on exactly that: it would land in the admin app, and the router would rewrite it to a mobile page. After the split it would have been mistaken for the home page, so the script excludes it by path. Hidden dependencies like this aren't in any route table. The only way to find them is to go digging through code and config.",[315,10648,10649,10655,10656,10658],{},[49,10650,10651,10652,10654],{},"Old URLs get cleaned up with ",[100,10653,10563],{},", not a redirect."," Any ",[100,10657,9853],{}," link already floating around opens with a clean address bar, costs no extra request, and keeps its query string.",[315,10660,10661,10667],{},[49,10662,10663,10666],{},[100,10664,10665],{},"\u003Ctitle>"," defaults to the home page's title",", since that's what crawlers read, and the script swaps it back for admin. Do it the other way around and any crawler that skips JS sees the admin title.",[17,10669,10670],{},"The real entry file does nothing but pick one:",[191,10672,10674],{"className":2427,"code":10673,"language":2429,"meta":15,"style":15},"\u002F\u002F src\u002Fboot.ts\nif (window.__LANDING__) {\n  import(\".\u002Flanding\u002Fmain\");\n} else {\n  import(\".\u002Fmain\"); \u002F\u002F the original admin entry, not one line changed\n}\n",[100,10675,10676,10681,10688,10700,10709,10724],{"__ignoreMap":15},[199,10677,10678],{"class":201,"line":202},[199,10679,10680],{"class":2468},"\u002F\u002F src\u002Fboot.ts\n",[199,10682,10683,10685],{"class":201,"line":25},[199,10684,7492],{"class":2436},[199,10686,10687],{"class":1629}," (window.__LANDING__) {\n",[199,10689,10690,10693,10695,10698],{"class":201,"line":213},[199,10691,10692],{"class":2436},"  import",[199,10694,2458],{"class":1629},[199,10696,10697],{"class":1633},"\".\u002Flanding\u002Fmain\"",[199,10699,2463],{"class":1629},[199,10701,10702,10705,10707],{"class":201,"line":219},[199,10703,10704],{"class":1629},"} ",[199,10706,10584],{"class":2436},[199,10708,3666],{"class":1629},[199,10710,10711,10713,10715,10718,10721],{"class":201,"line":225},[199,10712,10692],{"class":2436},[199,10714,2458],{"class":1629},[199,10716,10717],{"class":1633},"\".\u002Fmain\"",[199,10719,10720],{"class":1629},"); ",[199,10722,10723],{"class":2468},"\u002F\u002F the original admin entry, not one line changed\n",[199,10725,10726],{"class":201,"line":231},[199,10727,2502],{"class":1629},[17,10729,10730,10731,10734],{},"Because both are dynamic ",[100,10732,10733],{},"import()"," calls, the bundler splits them into two sets of chunks with nothing shared that shouldn't be. Home page visitors no longer pull down the admin bundle. Before this, the home page was a route inside the admin app, so every visitor downloaded the entire UI component library along with it.",[2031,10736,10738],{"id":10737},"_42-the-build-plugin","4.2 The build plugin",[17,10740,10741,10742,10744,10745,1312],{},"I hooked prerendering onto the end of the build as a Vite plugin instead of adding another command to ",[100,10743,7103],{},". The reason is mundane: I wasn't sure which build command our release pipeline actually calls, and a plugin means ",[49,10746,10747,10748,10751],{},"it runs any time ",[100,10749,10750],{},"vite build"," runs",[191,10753,10755],{"className":2427,"code":10754,"language":2429,"meta":15,"style":15},"\u002F\u002F build\u002FprerenderLanding.ts (skeleton)\nexport const prerenderLanding = (): Plugin => {\n  let config: ResolvedConfig;\n  let written = false;\n\n  return {\n    name: \"prerender-landing\",\n    apply: \"build\",\n    config: (_, { isSsrBuild }) => (isSsrBuild ? undefined : { build: { manifest: true } }),\n    configResolved: resolved => void (config = resolved),\n    writeBundle: () => void (written = true),\n\n    async closeBundle() {\n      \u002F\u002F closeBundle also fires when the build fails, and the nested SSR build loads this plugin too\n      if (config.build.ssr || !written) return;\n\n      \u002F\u002F 1. Run a second, SSR build with the same config, bundling only the home page's server entry\n      await build({\n        configFile: config.configFile,\n        mode: config.mode,\n        build: { ssr: \"src\u002Flanding\u002Fentry-server.ts\", outDir: ssrOutDir, copyPublicDir: false }\n      });\n\n      \u002F\u002F 2. Render and write back into dist\u002Findex.html\n      const { render } = await import(pathToFileURL(ssrEntry).href);\n      const landingHtml = patchLandingHtml(await render());\n      html = html.replace(CONTAINER_RE, () => `\u003Cdiv id=\"landing-root\" data-prerendered>${landingHtml}\u003C\u002Fdiv>`);\n      fs.writeFileSync(htmlPath, html);\n    }\n  };\n};\n",[100,10756,10757,10762,10785,10800,10814,10818,10824,10834,10844,10884,10907,10929,10933,10944,10949,10967,10971,10976,10986,10991,10996,11012,11017,11021,11026,11055,11078,11111,11122,11126,11131],{"__ignoreMap":15},[199,10758,10759],{"class":201,"line":202},[199,10760,10761],{"class":2468},"\u002F\u002F build\u002FprerenderLanding.ts (skeleton)\n",[199,10763,10764,10766,10768,10771,10773,10776,10778,10781,10783],{"class":201,"line":25},[199,10765,5644],{"class":2436},[199,10767,5647],{"class":2436},[199,10769,10770],{"class":1619}," prerenderLanding",[199,10772,3714],{"class":2436},[199,10774,10775],{"class":1629}," ()",[199,10777,346],{"class":2436},[199,10779,10780],{"class":1619}," Plugin",[199,10782,3663],{"class":2436},[199,10784,3666],{"class":1629},[199,10786,10787,10790,10793,10795,10798],{"class":201,"line":213},[199,10788,10789],{"class":2436},"  let",[199,10791,10792],{"class":1629}," config",[199,10794,346],{"class":2436},[199,10796,10797],{"class":1619}," ResolvedConfig",[199,10799,3703],{"class":1629},[199,10801,10802,10804,10807,10809,10812],{"class":201,"line":219},[199,10803,10789],{"class":2436},[199,10805,10806],{"class":1629}," written ",[199,10808,3697],{"class":2436},[199,10810,10811],{"class":3645}," false",[199,10813,3703],{"class":1629},[199,10815,10816],{"class":201,"line":225},[199,10817,461],{"emptyLinePlaceholder":30},[199,10819,10820,10822],{"class":201,"line":231},[199,10821,6018],{"class":2436},[199,10823,3666],{"class":1629},[199,10825,10826,10829,10832],{"class":201,"line":237},[199,10827,10828],{"class":1629},"    name: ",[199,10830,10831],{"class":1633},"\"prerender-landing\"",[199,10833,6123],{"class":1629},[199,10835,10836,10839,10842],{"class":201,"line":243},[199,10837,10838],{"class":1629},"    apply: ",[199,10840,10841],{"class":1633},"\"build\"",[199,10843,6123],{"class":1629},[199,10845,10846,10849,10852,10855,10858,10861,10864,10866,10869,10871,10874,10876,10879,10881],{"class":201,"line":249},[199,10847,10848],{"class":1619},"    config",[199,10850,10851],{"class":1629},": (",[199,10853,10854],{"class":3659},"_",[199,10856,10857],{"class":1629},", { ",[199,10859,10860],{"class":3659},"isSsrBuild",[199,10862,10863],{"class":1629}," }) ",[199,10865,3764],{"class":2436},[199,10867,10868],{"class":1629}," (isSsrBuild ",[199,10870,5533],{"class":2436},[199,10872,10873],{"class":3645}," undefined",[199,10875,6118],{"class":2436},[199,10877,10878],{"class":1629}," { build: { manifest: ",[199,10880,3798],{"class":3645},[199,10882,10883],{"class":1629}," } }),\n",[199,10885,10886,10889,10891,10894,10896,10899,10902,10904],{"class":201,"line":255},[199,10887,10888],{"class":1619},"    configResolved",[199,10890,1630],{"class":1629},[199,10892,10893],{"class":3659},"resolved",[199,10895,3663],{"class":2436},[199,10897,10898],{"class":2436}," void",[199,10900,10901],{"class":1629}," (config ",[199,10903,3697],{"class":2436},[199,10905,10906],{"class":1629}," resolved),\n",[199,10908,10909,10912,10915,10917,10919,10922,10924,10926],{"class":201,"line":261},[199,10910,10911],{"class":1619},"    writeBundle",[199,10913,10914],{"class":1629},": () ",[199,10916,3764],{"class":2436},[199,10918,10898],{"class":2436},[199,10920,10921],{"class":1629}," (written ",[199,10923,3697],{"class":2436},[199,10925,3700],{"class":3645},[199,10927,10928],{"class":1629},"),\n",[199,10930,10931],{"class":201,"line":267},[199,10932,461],{"emptyLinePlaceholder":30},[199,10934,10935,10938,10941],{"class":201,"line":273},[199,10936,10937],{"class":2436},"    async",[199,10939,10940],{"class":1619}," closeBundle",[199,10942,10943],{"class":1629},"() {\n",[199,10945,10946],{"class":201,"line":279},[199,10947,10948],{"class":2468},"      \u002F\u002F closeBundle also fires when the build fails, and the nested SSR build loads this plugin too\n",[199,10950,10951,10953,10956,10958,10960,10963,10965],{"class":201,"line":285},[199,10952,10541],{"class":2436},[199,10954,10955],{"class":1629}," (config.build.ssr ",[199,10957,3677],{"class":2436},[199,10959,10482],{"class":2436},[199,10961,10962],{"class":1629},"written) ",[199,10964,3683],{"class":2436},[199,10966,3703],{"class":1629},[199,10968,10969],{"class":201,"line":651},[199,10970,461],{"emptyLinePlaceholder":30},[199,10972,10973],{"class":201,"line":970},[199,10974,10975],{"class":2468},"      \u002F\u002F 1. Run a second, SSR build with the same config, bundling only the home page's server entry\n",[199,10977,10978,10981,10984],{"class":201,"line":976},[199,10979,10980],{"class":2436},"      await",[199,10982,10983],{"class":1619}," build",[199,10985,6092],{"class":1629},[199,10987,10988],{"class":201,"line":982},[199,10989,10990],{"class":1629},"        configFile: config.configFile,\n",[199,10992,10993],{"class":201,"line":988},[199,10994,10995],{"class":1629},"        mode: config.mode,\n",[199,10997,10998,11001,11004,11007,11010],{"class":201,"line":994},[199,10999,11000],{"class":1629},"        build: { ssr: ",[199,11002,11003],{"class":1633},"\"src\u002Flanding\u002Fentry-server.ts\"",[199,11005,11006],{"class":1629},", outDir: ssrOutDir, copyPublicDir: ",[199,11008,11009],{"class":3645},"false",[199,11011,3801],{"class":1629},[199,11013,11014],{"class":201,"line":2371},[199,11015,11016],{"class":1629},"      });\n",[199,11018,11019],{"class":201,"line":2377},[199,11020,461],{"emptyLinePlaceholder":30},[199,11022,11023],{"class":201,"line":2383},[199,11024,11025],{"class":2468},"      \u002F\u002F 2. Render and write back into dist\u002Findex.html\n",[199,11027,11028,11031,11033,11036,11039,11041,11044,11047,11049,11052],{"class":201,"line":2389},[199,11029,11030],{"class":2436},"      const",[199,11032,5979],{"class":1629},[199,11034,11035],{"class":3645},"render",[199,11037,11038],{"class":1629}," } ",[199,11040,3697],{"class":2436},[199,11042,11043],{"class":2436}," await",[199,11045,11046],{"class":1619}," import",[199,11048,2458],{"class":1629},[199,11050,11051],{"class":1619},"pathToFileURL",[199,11053,11054],{"class":1629},"(ssrEntry).href);\n",[199,11056,11057,11059,11062,11064,11067,11069,11072,11075],{"class":201,"line":2395},[199,11058,11030],{"class":2436},[199,11060,11061],{"class":3645}," landingHtml",[199,11063,3714],{"class":2436},[199,11065,11066],{"class":1619}," patchLandingHtml",[199,11068,2458],{"class":1629},[199,11070,11071],{"class":2436},"await",[199,11073,11074],{"class":1619}," render",[199,11076,11077],{"class":1629},"());\n",[199,11079,11080,11083,11085,11088,11090,11092,11095,11098,11100,11103,11106,11109],{"class":201,"line":2401},[199,11081,11082],{"class":1629},"      html ",[199,11084,3697],{"class":2436},[199,11086,11087],{"class":1629}," html.",[199,11089,10324],{"class":1619},[199,11091,2458],{"class":1629},[199,11093,11094],{"class":3645},"CONTAINER_RE",[199,11096,11097],{"class":1629},", () ",[199,11099,3764],{"class":2436},[199,11101,11102],{"class":1633}," `\u003Cdiv id=\"landing-root\" data-prerendered>${",[199,11104,11105],{"class":1629},"landingHtml",[199,11107,11108],{"class":1633},"}\u003C\u002Fdiv>`",[199,11110,2463],{"class":1629},[199,11112,11113,11116,11119],{"class":201,"line":2407},[199,11114,11115],{"class":1629},"      fs.",[199,11117,11118],{"class":1619},"writeFileSync",[199,11120,11121],{"class":1629},"(htmlPath, html);\n",[199,11123,11124],{"class":201,"line":3331},[199,11125,8475],{"class":1629},[199,11127,11128],{"class":201,"line":3337},[199,11129,11130],{"class":1629},"  };\n",[199,11132,11133],{"class":201,"line":3343},[199,11134,6036],{"class":1629},[17,11136,11137],{},"The server entry is three lines that matter:",[191,11139,11141],{"className":2427,"code":11140,"language":2429,"meta":15,"style":15},"\u002F\u002F src\u002Flanding\u002Fentry-server.ts\nimport { createSSRApp } from \"vue\";\nimport { renderToString } from \"vue\u002Fserver-renderer\";\nimport Home from \"@\u002Fviews\u002Flanding\u002Fhome.vue\";\n\nexport const render = () => renderToString(createSSRApp(Home));\n",[100,11142,11143,11148,11164,11178,11192,11196],{"__ignoreMap":15},[199,11144,11145],{"class":201,"line":202},[199,11146,11147],{"class":2468},"\u002F\u002F src\u002Flanding\u002Fentry-server.ts\n",[199,11149,11150,11153,11156,11159,11162],{"class":201,"line":25},[199,11151,11152],{"class":2436},"import",[199,11154,11155],{"class":1629}," { createSSRApp } ",[199,11157,11158],{"class":2436},"from",[199,11160,11161],{"class":1633}," \"vue\"",[199,11163,3703],{"class":1629},[199,11165,11166,11168,11171,11173,11176],{"class":201,"line":213},[199,11167,11152],{"class":2436},[199,11169,11170],{"class":1629}," { renderToString } ",[199,11172,11158],{"class":2436},[199,11174,11175],{"class":1633}," \"vue\u002Fserver-renderer\"",[199,11177,3703],{"class":1629},[199,11179,11180,11182,11185,11187,11190],{"class":201,"line":219},[199,11181,11152],{"class":2436},[199,11183,11184],{"class":1629}," Home ",[199,11186,11158],{"class":2436},[199,11188,11189],{"class":1633}," \"@\u002Fviews\u002Flanding\u002Fhome.vue\"",[199,11191,3703],{"class":1629},[199,11193,11194],{"class":201,"line":225},[199,11195,461],{"emptyLinePlaceholder":30},[199,11197,11198,11200,11202,11204,11206,11209,11211,11214,11216,11219],{"class":201,"line":231},[199,11199,5644],{"class":2436},[199,11201,5647],{"class":2436},[199,11203,11074],{"class":1619},[199,11205,3714],{"class":2436},[199,11207,11208],{"class":1629}," () ",[199,11210,3764],{"class":2436},[199,11212,11213],{"class":1619}," renderToString",[199,11215,2458],{"class":1629},[199,11217,11218],{"class":1619},"createSSRApp",[199,11220,11221],{"class":1629},"(Home));\n",[17,11223,11224],{},"A few choices here deserve an explanation:",[348,11226,11227,11236,11252,11275],{},[315,11228,11229,11235],{},[49,11230,11231,11232,1312],{},"The SSR build reuses the same ",[100,11233,11234],{},"vite.config"," Aliases, plugins, and asset naming are identical, so the image URLs coming out of the server render, content hashes included, line up with the client build's files. There's no mapping step.",[315,11237,11238,11244,11245,11248,11249,11251],{},[49,11239,4203,11240,11243],{},[100,11241,11242],{},"written"," flag."," Rollup calls ",[100,11246,11247],{},"closeBundle"," even when the build fails. Without this guard, the plugin would try to patch an ",[100,11250,9685],{}," left over from an earlier build, then throw an error that has nothing to do with what actually went wrong and bury the real one.",[315,11253,11254,11260,11261,11264,11265,3933,11268,11271,11272,11274],{},[49,11255,11256,11257,11259],{},"Pass a function to ",[100,11258,10324],{},", not a string."," When the second argument to ",[100,11262,11263],{},"String.prototype.replace"," is a string, sequences like ",[100,11266,11267],{},"$&",[100,11269,11270],{},"$1"," in it are treated as placeholders. Marketing copy with a ",[100,11273,10461],{}," in it is hardly unusual (think prices), and the function form sidesteps the whole issue.",[315,11276,11277,11280],{},[49,11278,11279],{},"A failed prerender fails the build."," It throws. I'd much rather ship nothing than quietly publish a home page with no body text. Nothing errors when that happens, and you only find out when traffic falls off.",[2031,11282,11284],{"id":11283},"_43-the-browser-entry","4.3 The browser entry",[191,11286,11288],{"className":2427,"code":11287,"language":2429,"meta":15,"style":15},"\u002F\u002F src\u002Flanding\u002Fmain.ts\nconst container = document.getElementById(\"landing-root\")!;\n\n\u002F\u002F By the time this module runs, its styles have loaded (the bundler waits for CSS dependencies)\ndocument.getElementById(\"app\")?.remove(); \u002F\u002F drop the loading spinner\ndocument.documentElement.classList.add(\"landing-ready\"); \u002F\u002F reveal the home page container\n\nconst prerendered = container.hasAttribute(\"data-prerendered\");\nconst app = prerendered ? createSSRApp(Home) : createApp(Home);\napp.mount(container);\n\n\u002F\u002F Going to admin from the home page only changes the hash. There is no router here,\n\u002F\u002F so reload once and let the boot script load admin\nwindow.addEventListener(\"hashchange\", () => {\n  if (isAdminHash(location.hash)) location.reload();\n});\n",[100,11289,11290,11295,11321,11325,11330,11353,11371,11375,11397,11425,11436,11440,11445,11450,11468,11486],{"__ignoreMap":15},[199,11291,11292],{"class":201,"line":202},[199,11293,11294],{"class":2468},"\u002F\u002F src\u002Flanding\u002Fmain.ts\n",[199,11296,11297,11299,11302,11304,11307,11310,11312,11315,11317,11319],{"class":201,"line":25},[199,11298,5475],{"class":2436},[199,11300,11301],{"class":3645}," container",[199,11303,3714],{"class":2436},[199,11305,11306],{"class":1629}," document.",[199,11308,11309],{"class":1619},"getElementById",[199,11311,2458],{"class":1629},[199,11313,11314],{"class":1633},"\"landing-root\"",[199,11316,5665],{"class":1629},[199,11318,3727],{"class":2436},[199,11320,3703],{"class":1629},[199,11322,11323],{"class":201,"line":213},[199,11324,461],{"emptyLinePlaceholder":30},[199,11326,11327],{"class":201,"line":219},[199,11328,11329],{"class":2468},"\u002F\u002F By the time this module runs, its styles have loaded (the bundler waits for CSS dependencies)\n",[199,11331,11332,11335,11337,11339,11341,11344,11347,11350],{"class":201,"line":225},[199,11333,11334],{"class":1629},"document.",[199,11336,11309],{"class":1619},[199,11338,2458],{"class":1629},[199,11340,9765],{"class":1633},[199,11342,11343],{"class":1629},")?.",[199,11345,11346],{"class":1619},"remove",[199,11348,11349],{"class":1629},"(); ",[199,11351,11352],{"class":2468},"\u002F\u002F drop the loading spinner\n",[199,11354,11355,11358,11361,11363,11366,11368],{"class":201,"line":231},[199,11356,11357],{"class":1629},"document.documentElement.classList.",[199,11359,11360],{"class":1619},"add",[199,11362,2458],{"class":1629},[199,11364,11365],{"class":1633},"\"landing-ready\"",[199,11367,10720],{"class":1629},[199,11369,11370],{"class":2468},"\u002F\u002F reveal the home page container\n",[199,11372,11373],{"class":201,"line":237},[199,11374,461],{"emptyLinePlaceholder":30},[199,11376,11377,11379,11382,11384,11387,11390,11392,11395],{"class":201,"line":243},[199,11378,5475],{"class":2436},[199,11380,11381],{"class":3645}," prerendered",[199,11383,3714],{"class":2436},[199,11385,11386],{"class":1629}," container.",[199,11388,11389],{"class":1619},"hasAttribute",[199,11391,2458],{"class":1629},[199,11393,11394],{"class":1633},"\"data-prerendered\"",[199,11396,2463],{"class":1629},[199,11398,11399,11401,11404,11406,11409,11411,11414,11417,11419,11422],{"class":201,"line":249},[199,11400,5475],{"class":2436},[199,11402,11403],{"class":3645}," app",[199,11405,3714],{"class":2436},[199,11407,11408],{"class":1629}," prerendered ",[199,11410,5533],{"class":2436},[199,11412,11413],{"class":1619}," createSSRApp",[199,11415,11416],{"class":1629},"(Home) ",[199,11418,346],{"class":2436},[199,11420,11421],{"class":1619}," createApp",[199,11423,11424],{"class":1629},"(Home);\n",[199,11426,11427,11430,11433],{"class":201,"line":255},[199,11428,11429],{"class":1629},"app.",[199,11431,11432],{"class":1619},"mount",[199,11434,11435],{"class":1629},"(container);\n",[199,11437,11438],{"class":201,"line":261},[199,11439,461],{"emptyLinePlaceholder":30},[199,11441,11442],{"class":201,"line":267},[199,11443,11444],{"class":2468},"\u002F\u002F Going to admin from the home page only changes the hash. There is no router here,\n",[199,11446,11447],{"class":201,"line":273},[199,11448,11449],{"class":2468},"\u002F\u002F so reload once and let the boot script load admin\n",[199,11451,11452,11454,11457,11459,11462,11464,11466],{"class":201,"line":279},[199,11453,3642],{"class":1629},[199,11455,11456],{"class":1619},"addEventListener",[199,11458,2458],{"class":1629},[199,11460,11461],{"class":1633},"\"hashchange\"",[199,11463,11097],{"class":1629},[199,11465,3764],{"class":2436},[199,11467,3666],{"class":1629},[199,11469,11470,11472,11474,11477,11480,11483],{"class":201,"line":285},[199,11471,5678],{"class":2436},[199,11473,3724],{"class":1629},[199,11475,11476],{"class":1619},"isAdminHash",[199,11478,11479],{"class":1629},"(location.hash)) location.",[199,11481,11482],{"class":1619},"reload",[199,11484,11485],{"class":1629},"();\n",[199,11487,11488],{"class":201,"line":651},[199,11489,6128],{"class":1629},[17,11491,11492,11495,11496,3933,11498,11501,11502,9838,11505,11508],{},[100,11493,11494],{},"data-prerendered"," is a marker the build plugin leaves behind. Production builds have it, so the entry calls ",[100,11497,11218],{},[49,11499,11500],{},"hydrates",", which means wiring events and reactivity onto the DOM that's already there instead of rebuilding it. In local dev the container is empty, so it falls back to a plain ",[100,11503,11504],{},"createApp",[49,11506,11507],{},"One entry file covers both cases",", and the dev workflow doesn't change.",[17,11510,11511,11512,11515,11516,11519,11520,11523,11524,11527],{},"Buttons on the home page that used to call ",[100,11513,11514],{},"router.push(\"\u002Foverview\")"," now just set ",[100,11517,11518],{},"location.hash = \"#\u002Foverview\"",". What I like about this is that it ",[49,11521,11522],{},"works whether or not there's a router",". On the standalone home page it fires the ",[100,11525,11526],{},"hashchange"," listener above. The header and footer are also shared with a legal page that still lives in the admin app, and over there the hash router picks up the very same change.",[58,11529,11531],{"id":11530},"_5-four-things-that-only-bite-once-you-ship","5. Four Things That Only Bite Once You Ship",[2031,11533,11535],{"id":11534},"pitfall-1-the-content-shows-up-before-its-styles","Pitfall 1: the content shows up before its styles",[17,11537,11538],{},"Once the page is prerendered, the home page's markup is in the DOM the instant the HTML arrives. Its CSS, though, is a dependency of the JS entry and loads a beat later. What you get is a flash of raw, completely unstyled HTML.",[17,11540,11541,11542,11544],{},"The fix is to collapse the container with an inline style in ",[100,11543,10271],{},", then let it go once the entry runs:",[191,11546,11550],{"className":11547,"code":11548,"language":11549,"meta":15,"style":15},"language-css shiki shiki-themes github-light github-dark github-dark","html.boot-landing:not(.landing-ready) #landing-root {\n  height: 0;\n  overflow: hidden;\n  visibility: hidden;\n}\n","css",[100,11551,11552,11571,11582,11594,11605],{"__ignoreMap":15},[199,11553,11554,11556,11559,11561,11564,11566,11569],{"class":201,"line":202},[199,11555,9705],{"class":1625},[199,11557,11558],{"class":1619},".boot-landing:not",[199,11560,2458],{"class":1629},[199,11562,11563],{"class":1619},".landing-ready",[199,11565,5846],{"class":1629},[199,11567,11568],{"class":1619},"#landing-root",[199,11570,3666],{"class":1629},[199,11572,11573,11576,11578,11580],{"class":201,"line":25},[199,11574,11575],{"class":3645},"  height",[199,11577,1630],{"class":1629},[199,11579,833],{"class":3645},[199,11581,3703],{"class":1629},[199,11583,11584,11587,11589,11592],{"class":201,"line":213},[199,11585,11586],{"class":3645},"  overflow",[199,11588,1630],{"class":1629},[199,11590,11591],{"class":3645},"hidden",[199,11593,3703],{"class":1629},[199,11595,11596,11599,11601,11603],{"class":201,"line":219},[199,11597,11598],{"class":3645},"  visibility",[199,11600,1630],{"class":1629},[199,11602,11591],{"class":3645},[199,11604,3703],{"class":1629},[199,11606,11607],{"class":201,"line":225},[199,11608,2502],{"class":1629},[17,11610,11611,11612,11615],{},"Crawlers don't care. The ones that skip JS parse the text and ignore visibility, and the ones that run JS see the final state. But it does mean ",[49,11613,11614],{},"prerendering didn't get the page in front of users any faster",". That's a real limitation, and I come back to it in section 8.",[2031,11617,11619],{"id":11618},"pitfall-2-the-ssr-builds-asset-urls-break-under-a-subdirectory-deploy","Pitfall 2: the SSR build's asset URLs break under a subdirectory deploy",[17,11621,11622,11623,11626,11627,11629],{},"My ",[100,11624,11625],{},"base"," is the relative ",[100,11628,9971],{},", so the same build works at a domain root or in any subdirectory. The client build resolves assets relative to the current file. The SSR build doesn't. Here's the branch in the Vite 5 source:",[191,11631,11635],{"className":11632,"code":11633,"language":11634,"meta":15,"style":15},"language-js shiki shiki-themes github-light github-dark github-dark","if (relative && !config.build.ssr) {\n  return toRelative(filename, hostId);\n}\nreturn joinUrlSegments(config.base, filename);\n","js",[100,11636,11637,11651,11661,11665],{"__ignoreMap":15},[199,11638,11639,11641,11644,11646,11648],{"class":201,"line":202},[199,11640,7492],{"class":2436},[199,11642,11643],{"class":1629}," (relative ",[199,11645,10409],{"class":2436},[199,11647,10482],{"class":2436},[199,11649,11650],{"class":1629},"config.build.ssr) {\n",[199,11652,11653,11655,11658],{"class":201,"line":25},[199,11654,6018],{"class":2436},[199,11656,11657],{"class":1619}," toRelative",[199,11659,11660],{"class":1629},"(filename, hostId);\n",[199,11662,11663],{"class":201,"line":213},[199,11664,2502],{"class":1629},[199,11666,11667,11669,11672],{"class":201,"line":219},[199,11668,3683],{"class":2436},[199,11670,11671],{"class":1619}," joinUrlSegments",[199,11673,11674],{"class":1629},"(config.base, filename);\n",[17,11676,11677,11678,2625,11681,11684,11685,11688],{},"A relative base only kicks in for client builds. The SSR build emits URLs like ",[100,11679,11680],{},"\u002Fassets\u002Fpng\u002Fxxx.png",[49,11682,11683],{},"anchored at the domain root",". Production sits at the root, so it was fine. The test environment sits under ",[100,11686,11687],{},"\u002Fadmin\u002F",", and every image there came back 404.",[17,11690,11691,11692,11695,11696,11698],{},"Here's the nasty part: ",[49,11693,11694],{},"hydration won't fix it for you."," In production mode Vue doesn't patch static attributes when it hydrates, so whatever ",[100,11697,6455],{}," the server wrote is what stays on the page. I had to rewrite the HTML before saving it:",[191,11700,11702],{"className":2427,"code":11701,"language":2429,"meta":15,"style":15},"html.replace(\u002F\\s(src|poster)=\"\\\u002Fassets\\\u002F\u002Fg, ' $1=\".\u002Fassets\u002F');\n",[100,11703,11704],{"__ignoreMap":15},[199,11705,11706,11709,11711,11713,11715,11718,11721,11724,11727,11729,11732,11734,11736,11739,11741,11744],{"class":201,"line":202},[199,11707,11708],{"class":1629},"html.",[199,11710,10324],{"class":1619},[199,11712,2458],{"class":1629},[199,11714,5625],{"class":1633},[199,11716,11717],{"class":3645},"\\s",[199,11719,11720],{"class":10334},"(src",[199,11722,11723],{"class":2436},"|",[199,11725,11726],{"class":10334},"poster)=\"",[199,11728,10367],{"class":10366},[199,11730,11731],{"class":10334},"assets",[199,11733,10367],{"class":10366},[199,11735,5625],{"class":1633},[199,11737,11738],{"class":2436},"g",[199,11740,2625],{"class":1629},[199,11742,11743],{"class":1633},"' $1=\".\u002Fassets\u002F'",[199,11745,2463],{"class":1629},[17,11747,11748],{},"You only see this when three things line up: a subdirectory deploy, a relative base, and prerendering. I didn't catch it until I ran a local static server that mimicked the subdirectory.",[2031,11750,11752],{"id":11751},"pitfall-3-the-browser-downloads-hidden-content-anyway","Pitfall 3: the browser downloads hidden content anyway",[17,11754,11755,11756,11759,11760,11763],{},"On an admin URL, the home page HTML is dead weight. The boot script sets it to ",[100,11757,11758],{},"display: none",", and a script immediately after it removes the node altogether. That sounds airtight, but browsers have a ",[49,11761,11762],{},"preload scanner",". It races ahead of the main parser through the raw HTML and kicks off requests for images and other resources early. It has no idea those elements are about to be hidden or thrown away.",[17,11765,11766],{},"The home page has more than seventy images. Do nothing, and every admin user downloads all of them for no reason.",[17,11768,11769,11770,11773,11774,11777,11778,11781],{},"The fix is to stamp ",[100,11771,11772],{},"loading=\"lazy\""," on every image during prerendering. The preload scanner leaves lazy images alone, and a lazy image inside a hidden container never reaches the viewport, so it's never requested. Video posters don't have a lazy equivalent, so I stash ",[100,11775,11776],{},"poster"," in a ",[100,11779,11780],{},"data-"," attribute and put it back right before the home page entry mounts.",[17,11783,11784],{},"What I measured in Chrome: on an admin URL, zero requests for the home page's images or video posters. I haven't checked how the preload scanner behaves in other browsers.",[2031,11786,11788],{"id":11787},"pitfall-4-removing-the-loading-spinner-took-the-page-margins-with-it","Pitfall 4: removing the loading spinner took the page margins with it",[17,11790,11791,11792,11794,11795,11798,11799,11802,11803,11806,11807,11810],{},"I did this one to myself. In the original ",[100,11793,9685],{},", the few lines of CSS that zero out the margins on ",[100,11796,11797],{},"html, body"," lived in a ",[100,11800,11801],{},"\u003Cstyle>"," tag inside ",[100,11804,11805],{},"\u003Cdiv id=\"app\">",", right beside the loading spinner. When the admin app mounts it takes over ",[100,11808,11809],{},"#app",", and its own global stylesheet has the same reset, so nobody ever noticed.",[17,11812,11813,11814,11817,11818,11820,11821,11823],{},"My home page entry calls ",[100,11815,11816],{},"document.getElementById(\"app\").remove()",". The ",[100,11819,11801],{}," tag went out with it, the standalone entry doesn't load the admin's global styles, and ",[100,11822,9748],{}," snapped back to the browser's default 8px margin. The whole page picked up a white border.",[17,11825,11826,11827,11829],{},"The fix is simple: move the reset into an inline style in ",[100,11828,10271],{},", so it no longer hangs off a node that's going to be removed.",[191,11831,11833],{"className":9703,"code":11832,"language":9705,"meta":15,"style":15},"\u003Chead>\n  \u003Cstyle>\n    html,\n    body {\n      width: 100%;\n      height: 100%;\n      padding: 0;\n      margin: 0;\n    }\n  \u003C\u002Fstyle>\n\u003C\u002Fhead>\n",[100,11834,11835,11843,11851,11858,11865,11879,11892,11903,11914,11918,11927],{"__ignoreMap":15},[199,11836,11837,11839,11841],{"class":201,"line":202},[199,11838,5865],{"class":1629},[199,11840,9714],{"class":1625},[199,11842,9717],{"class":1629},[199,11844,11845,11847,11849],{"class":201,"line":25},[199,11846,9722],{"class":1629},[199,11848,1042],{"class":1625},[199,11850,9717],{"class":1629},[199,11852,11853,11856],{"class":201,"line":213},[199,11854,11855],{"class":1625},"    html",[199,11857,6123],{"class":1629},[199,11859,11860,11863],{"class":201,"line":219},[199,11861,11862],{"class":1625},"    body",[199,11864,3666],{"class":1629},[199,11866,11867,11870,11872,11875,11877],{"class":201,"line":225},[199,11868,11869],{"class":3645},"      width",[199,11871,1630],{"class":1629},[199,11873,11874],{"class":3645},"100",[199,11876,6339],{"class":2436},[199,11878,3703],{"class":1629},[199,11880,11881,11884,11886,11888,11890],{"class":201,"line":231},[199,11882,11883],{"class":3645},"      height",[199,11885,1630],{"class":1629},[199,11887,11874],{"class":3645},[199,11889,6339],{"class":2436},[199,11891,3703],{"class":1629},[199,11893,11894,11897,11899,11901],{"class":201,"line":237},[199,11895,11896],{"class":3645},"      padding",[199,11898,1630],{"class":1629},[199,11900,833],{"class":3645},[199,11902,3703],{"class":1629},[199,11904,11905,11908,11910,11912],{"class":201,"line":243},[199,11906,11907],{"class":3645},"      margin",[199,11909,1630],{"class":1629},[199,11911,833],{"class":3645},[199,11913,3703],{"class":1629},[199,11915,11916],{"class":201,"line":249},[199,11917,8475],{"class":1629},[199,11919,11920,11923,11925],{"class":201,"line":255},[199,11921,11922],{"class":1629},"  \u003C\u002F",[199,11924,1042],{"class":1625},[199,11926,9717],{"class":1629},[199,11928,11929,11931,11933],{"class":201,"line":261},[199,11930,9737],{"class":1629},[199,11932,9714],{"class":1625},[199,11934,9717],{"class":1629},[17,11936,11937,11938,11940],{},"I left the original copy inside ",[100,11939,11809],{}," alone. The admin entry still works the way it always has, and deduplicating two CSS rules isn't a good enough reason to touch a path that's been running fine for a long time.",[17,11942,11943,11944,11950],{},"The real lesson here is bigger than 8px: ",[49,11945,11946,11947,11949],{},"when a node is removed, any ",[100,11948,11801],{}," inside it stops applying",", and nobody keeps track of which node a global style happens to live in. If you're about to delete or replace a container that was already on the page, check first whether it's carrying styles or scripts along with it.",[17,11952,11953,11954,11957],{},"Type checking passed. Lint passed. The build passed. Every piece of runtime state my script read was correct. ",[49,11955,11956],{},"It took a screenshot to catch it."," More on that in the takeaways.",[58,11959,11961],{"id":11960},"_6-getting-preloading-back-after-the-entries-went-dynamic","6. Getting Preloading Back After the Entries Went Dynamic",[17,11963,11964,11965,11968,11969,11972,11973,1312],{},"Before any of this, the ",[100,11966,11967],{},"\u003Cscript type=\"module\">"," in the HTML pointed straight at the admin entry, and the bundler emitted ",[100,11970,11971],{},"\u003Clink rel=\"modulepreload\">"," tags for its static dependencies. The browser could start downloading them in parallel as soon as it parsed ",[100,11974,10271],{},[17,11976,11977,11978,11981,11982,11984,11985,11987,11988,11991],{},"Now the HTML points at ",[100,11979,11980],{},"boot.ts",", which is a handful of lines, and both real entries are dynamic ",[100,11983,10733],{}," calls. Bundlers don't emit preload tags in the HTML for dynamic entries. So the browser has to download and run ",[100,11986,11980],{}," before it even knows what to fetch next. That's ",[49,11989,11990],{},"one extra round trip",", and a performance regression for admin users that I wasn't going to accept.",[17,11993,11994,11995,346],{},"To fix it, the build plugin reads Vite's manifest, which records the output file for each entry and the files it statically depends on. From that it works out what each of the two entries needs on first load, and injects an inline script just before ",[100,11996,11997],{},"\u003C\u002Fhead>",[191,11999,12001],{"className":11632,"code":12000,"language":11634,"meta":15,"style":15},"var files = window.__LANDING__ ? manifest.landing : manifest.admin;\nfiles.js.forEach(function (f) { add(\"modulepreload\", f); });\nfiles.css.forEach(function (f) { add(\"preload\", f, \"style\"); });\n",[100,12002,12003,12026,12056],{"__ignoreMap":15},[199,12004,12005,12008,12011,12013,12016,12018,12021,12023],{"class":201,"line":202},[199,12006,12007],{"class":2436},"var",[199,12009,12010],{"class":1629}," files ",[199,12012,3697],{"class":2436},[199,12014,12015],{"class":1629}," window.__LANDING__ ",[199,12017,5533],{"class":2436},[199,12019,12020],{"class":1629}," manifest.landing ",[199,12022,346],{"class":2436},[199,12024,12025],{"class":1629}," manifest.admin;\n",[199,12027,12028,12031,12034,12036,12038,12040,12043,12046,12048,12050,12053],{"class":201,"line":25},[199,12029,12030],{"class":1629},"files.js.",[199,12032,12033],{"class":1619},"forEach",[199,12035,2458],{"class":1629},[199,12037,10293],{"class":2436},[199,12039,3724],{"class":1629},[199,12041,12042],{"class":3659},"f",[199,12044,12045],{"class":1629},") { ",[199,12047,11360],{"class":1619},[199,12049,2458],{"class":1629},[199,12051,12052],{"class":1633},"\"modulepreload\"",[199,12054,12055],{"class":1629},", f); });\n",[199,12057,12058,12061,12063,12065,12067,12069,12071,12073,12075,12077,12080,12083,12086],{"class":201,"line":213},[199,12059,12060],{"class":1629},"files.css.",[199,12062,12033],{"class":1619},[199,12064,2458],{"class":1629},[199,12066,10293],{"class":2436},[199,12068,3724],{"class":1629},[199,12070,12042],{"class":3659},[199,12072,12045],{"class":1629},[199,12074,11360],{"class":1619},[199,12076,2458],{"class":1629},[199,12078,12079],{"class":1633},"\"preload\"",[199,12081,12082],{"class":1629},", f, ",[199,12084,12085],{"class":1633},"\"style\"",[199,12087,12088],{"class":1629},"); });\n",[17,12090,12091,12092],{},"There's one part of this that's easy to get wrong: ",[49,12093,12094,12095,12098],{},"the CSS goes in as ",[100,12096,12097],{},"rel=\"preload\" as=\"style\"",", not as a stylesheet.",[1036,12100,12101,12109,12112,12165,12172,12182],{},[17,12102,12103],{},[49,12104,12105,12106,5533],{},"Why not just insert a ",[100,12107,12108],{},"\u003Clink rel=\"stylesheet\">",[17,12110,12111],{},"Before Vite loads a dynamic entry at runtime, it takes care of that entry's CSS. Its preload helper has this check (Vite 5):",[191,12113,12115],{"className":11632,"code":12114,"language":11634,"meta":15,"style":15},"if (link.href === dep && (!isCss || link.rel === \"stylesheet\")) {\n  return; \u002F\u002F a stylesheet with this URL is already on the page: bail out, don't wait\n}\n",[100,12116,12117,12152,12161],{"__ignoreMap":15},[199,12118,12119,12121,12124,12127,12130,12132,12134,12136,12139,12141,12144,12146,12149],{"class":201,"line":202},[199,12120,7492],{"class":2436},[199,12122,12123],{"class":1629}," (link.href ",[199,12125,12126],{"class":2436},"===",[199,12128,12129],{"class":1629}," dep ",[199,12131,10409],{"class":2436},[199,12133,3724],{"class":1629},[199,12135,3727],{"class":2436},[199,12137,12138],{"class":1629},"isCss ",[199,12140,3677],{"class":2436},[199,12142,12143],{"class":1629}," link.rel ",[199,12145,12126],{"class":2436},[199,12147,12148],{"class":1633}," \"stylesheet\"",[199,12150,12151],{"class":1629},")) {\n",[199,12153,12154,12156,12158],{"class":201,"line":25},[199,12155,6018],{"class":2436},[199,12157,7787],{"class":1629},[199,12159,12160],{"class":2468},"\u002F\u002F a stylesheet with this URL is already on the page: bail out, don't wait\n",[199,12162,12163],{"class":201,"line":213},[199,12164,2502],{"class":1629},[17,12166,12167,12168,12171],{},"If I add the stylesheet myself ahead of time, Vite sees it's \"already there\" and returns right away, which means ",[49,12169,12170],{},"the JS starts running before the CSS has finished loading",". The home page's intro animation measures elements when it mounts, and every one of those measurements is wrong if the styles aren't applied yet.",[17,12173,7195,12174,12177,12178,12181],{},[100,12175,12176],{},"rel=\"preload\""," link doesn't match that condition, so Vite still inserts its own stylesheet and waits for the ",[100,12179,12180],{},"load"," event. By then the file is already cached, so the wait is close to free. You get the warm cache and the correct execution order.",[17,12183,12184,12187],{},[100,12185,12186],{},"crossOrigin"," also has to match what Vite puts on its own tags, which is an empty string. If it doesn't, the two requests use different credentials modes and the browser won't reuse the cached response.",[17,12189,12190],{},"The manifest is deleted once it's been read. It never ships.",[17,12192,12193,12194,12197,12198,12201],{},"One more manifest gotcha. I first looked up the admin entry by its source path, ",[100,12195,12196],{},"src\u002Fmain.ts",", and it wasn't there. Something in the admin code imports the entry file back, so the bundler folded it into a shared chunk keyed by a hashed chunk name. I ended up finding it through the HTML entry's ",[100,12199,12200],{},"dynamicImports"," instead: it's whichever one isn't the home page.",[58,12203,12205],{"id":12204},"_7-verification-driving-a-real-browser-without-a-test-library","7. Verification: Driving a Real Browser Without a Test Library",[17,12207,12208],{},"All the risk in a change like this is at runtime. What does the address bar end up showing? Which resources got requested? Did hydration complain? Type checks and a green build can't tell you any of that.",[17,12210,12211,12212,12215,12216,12219,12220,12223],{},"I didn't reach for Puppeteer or Playwright. I talked to Chrome directly over the ",[49,12213,12214],{},"Chrome DevTools Protocol"," (CDP): launch the local Chrome with ",[100,12217,12218],{},"--headless=new --remote-debugging-port"," and send protocol commands over a WebSocket. On Node 20, ",[100,12221,12222],{},"--experimental-websocket"," turns on the built-in WebSocket client, so there's nothing to install:",[191,12225,12227],{"className":11632,"code":12226,"language":11634,"meta":15,"style":15},"const send = (method, params = {}) =>\n  new Promise(resolve => {\n    const id = ++seq;\n    pending.set(id, resolve);\n    ws.send(JSON.stringify({ id, method, params }));\n  });\n\nawait send(\"Page.navigate\", { url });\nconst state = await send(\"Runtime.evaluate\", {\n  expression: `JSON.stringify({ href: location.href, hasApp: !!document.getElementById(\"app\") })`,\n  returnByValue: true\n});\n",[100,12228,12229,12256,12273,12287,12298,12319,12324,12328,12342,12363,12373,12381],{"__ignoreMap":15},[199,12230,12231,12233,12236,12238,12240,12243,12245,12248,12250,12253],{"class":201,"line":202},[199,12232,5475],{"class":2436},[199,12234,12235],{"class":1619}," send",[199,12237,3714],{"class":2436},[199,12239,3724],{"class":1629},[199,12241,12242],{"class":3659},"method",[199,12244,2625],{"class":1629},[199,12246,12247],{"class":3659},"params",[199,12249,3714],{"class":2436},[199,12251,12252],{"class":1629}," {}) ",[199,12254,12255],{"class":2436},"=>\n",[199,12257,12258,12261,12264,12266,12269,12271],{"class":201,"line":25},[199,12259,12260],{"class":2436},"  new",[199,12262,12263],{"class":3645}," Promise",[199,12265,2458],{"class":1629},[199,12267,12268],{"class":3659},"resolve",[199,12270,3663],{"class":2436},[199,12272,3666],{"class":1629},[199,12274,12275,12277,12279,12281,12284],{"class":201,"line":213},[199,12276,3708],{"class":2436},[199,12278,9760],{"class":3645},[199,12280,3714],{"class":2436},[199,12282,12283],{"class":2436}," ++",[199,12285,12286],{"class":1629},"seq;\n",[199,12288,12289,12292,12295],{"class":201,"line":219},[199,12290,12291],{"class":1629},"    pending.",[199,12293,12294],{"class":1619},"set",[199,12296,12297],{"class":1629},"(id, resolve);\n",[199,12299,12300,12303,12306,12308,12311,12313,12316],{"class":201,"line":225},[199,12301,12302],{"class":1629},"    ws.",[199,12304,12305],{"class":1619},"send",[199,12307,2458],{"class":1629},[199,12309,12310],{"class":3645},"JSON",[199,12312,1312],{"class":1629},[199,12314,12315],{"class":1619},"stringify",[199,12317,12318],{"class":1629},"({ id, method, params }));\n",[199,12320,12321],{"class":201,"line":231},[199,12322,12323],{"class":1629},"  });\n",[199,12325,12326],{"class":201,"line":237},[199,12327,461],{"emptyLinePlaceholder":30},[199,12329,12330,12332,12334,12336,12339],{"class":201,"line":243},[199,12331,11071],{"class":2436},[199,12333,12235],{"class":1619},[199,12335,2458],{"class":1629},[199,12337,12338],{"class":1633},"\"Page.navigate\"",[199,12340,12341],{"class":1629},", { url });\n",[199,12343,12344,12346,12349,12351,12353,12355,12357,12360],{"class":201,"line":249},[199,12345,5475],{"class":2436},[199,12347,12348],{"class":3645}," state",[199,12350,3714],{"class":2436},[199,12352,11043],{"class":2436},[199,12354,12235],{"class":1619},[199,12356,2458],{"class":1629},[199,12358,12359],{"class":1633},"\"Runtime.evaluate\"",[199,12361,12362],{"class":1629},", {\n",[199,12364,12365,12368,12371],{"class":201,"line":255},[199,12366,12367],{"class":1629},"  expression: ",[199,12369,12370],{"class":1633},"`JSON.stringify({ href: location.href, hasApp: !!document.getElementById(\"app\") })`",[199,12372,6123],{"class":1629},[199,12374,12375,12378],{"class":201,"line":261},[199,12376,12377],{"class":1629},"  returnByValue: ",[199,12379,12380],{"class":3645},"true\n",[199,12382,12383],{"class":201,"line":267},[199,12384,6128],{"class":1629},[17,12386,12387,12388,12391],{},"Next to it runs a static server, about twenty lines long, that serves the build output ",[49,12389,12390],{},"from a subdirectory and from the domain root at the same time",". That covers both the test setup and production, including production's habit of serving the home page for unknown paths. The server also logs every request path, which is how I can actually back up a claim like \"zero home page image requests on an admin URL.\"",[17,12393,12394],{},"I ran nine URLs through it, and for each one read back the final address, the title, the DOM state, and any console errors:",[105,12396,12397,12407],{},[108,12398,12399],{},[111,12400,12401,12404],{},[114,12402,12403],{},"Scenario",[114,12405,12406],{},"What I checked",[121,12408,12409,12420,12434,12445,12453,12463,12471],{},[111,12410,12411,12414],{},[126,12412,12413],{},"Home page, once in a subdirectory and once at the root",[126,12415,12416,12417,12419],{},"No ",[100,12418,6521],{}," in the address; container hydrated; no console errors; no broken images in the subdirectory",[111,12421,12422,12431],{},[126,12423,12424,12425,3933,12428],{},"Old URLs ",[100,12426,12427],{},"#\u002Flanding\u002Fhome",[100,12429,12430],{},"\u002F?utm=x#\u002F",[126,12432,12433],{},"Address cleaned up, query string intact",[111,12435,12436,12442],{},[126,12437,12438,12439],{},"Admin URL ",[100,12440,12441],{},"#\u002Flogin",[126,12443,12444],{},"Home page container gone; zero requests for home page images, posters, or styles",[111,12446,12447,12450],{},[126,12448,12449],{},"Clicking through to admin from the home page",[126,12451,12452],{},"One reload, then the login page",[111,12454,12455,12458],{},[126,12456,12457],{},"Navigating to the root path from inside admin",[126,12459,12460,12461],{},"Full reload back to the home page, no ",[100,12462,6521],{},[111,12464,12465,12468],{},[126,12466,12467],{},"The legal page inside admin",[126,12469,12470],{},"Shared header and footer links work",[111,12472,12473,12478],{},[126,12474,12475,12476],{},"Short link ",[100,12477,10645],{},[126,12479,12480],{},"Still reaches the mobile page instead of being treated as the home page",[17,12482,12483,12484,12487],{},"Last, I used ",[100,12485,12486],{},"Page.captureScreenshot"," to grab three screenshots and looked at them myself. That's where pitfall 4 turned up.",[58,12489,12491],{"id":12490},"_8-where-this-approach-falls-short","8. Where This Approach Falls Short",[17,12493,12494],{},"None of this is free, so here's what it costs.",[17,12496,12497],{},[49,12498,12499],{},"What it doesn't fix",[348,12501,12502,12508,12514],{},[315,12503,12504,12507],{},[49,12505,12506],{},"Users don't see the page any sooner."," The hero's intro animation waits for JS to add a state class before it fades in. Combine that with the hiding from pitfall 1, and content shows up at about the same moment it did before. Prerendering decides whether content can be read, not how quickly it's seen. Page experience metrics are a separate job.",[315,12509,12510,12513],{},[49,12511,12512],{},"Only one page benefits."," The legal page and everything else are still hash routes.",[315,12515,12516,12519,12520,12523],{},[49,12517,12518],{},"Unknown paths still return 200."," The static host's fallback hasn't changed. A ",[100,12521,12522],{},"canonical"," tag tells search engines the domain root is the real address.",[17,12525,12526],{},[49,12527,12528],{},"What it adds",[348,12530,12531,12539,12545,12559,12565],{},[315,12532,12533,5248,12536,12538],{},[49,12534,12535],{},"The entry HTML got heavier.",[100,12537,9685],{},", which is only a shell, went from about 4 kB to about 98 kB, or roughly 17 kB gzipped, and the extra home page markup is no use to admin users. My first version was actually 165 kB (40 kB gzipped), and two trims brought it down. First, the contact modal, which only appears on click, now renders in the browser only. It's worthless to crawlers, yet its template is packed with inline icons. Second, the home page's small images are no longer inlined as data URIs. As separate files they also get lazy loading for free. What's left is only paid on a full page load, since in-app route changes never re-request the HTML. Next to the roughly 1.8 MB of JavaScript the admin app loads up front (uncompressed, about 590 kB gzipped), it's a small fixed cost.",[315,12540,12541,12544],{},[49,12542,12543],{},"The home page and admin still ship together."," Fixing a typo on the home page means releasing the entire admin app. If the home page is going to grow into a multi-page content site, this is the wrong approach. At that point, split it into its own project and accept that the admin app has to move.",[315,12546,12547,12550,12551,12554,12555,12558],{},[49,12548,12549],{},"Home page components now come with rules."," They have to render in Node, which means no top-level ",[100,12552,12553],{},"window"," or ",[100,12556,12557],{},"document",", and nothing that differs between server and client, like random numbers or the current time. The build fails if you break this, but whoever edits those components needs to know the rule going in.",[315,12560,12561,12564],{},[49,12562,12563],{},"There's build code to re-test on every bundler upgrade."," The plugin leans on the shape of the manifest and on how the SSR build treats a relative base. Neither is a stable public contract.",[315,12566,12567,12570,12571,12573],{},[49,12568,12569],{},"The routing check lives in two places."," An inline script can't ",[100,12572,11152],{},", so the hash rule is written once in the HTML and once in TypeScript, with nothing but comments keeping them in sync.",[58,12575,12577],{"id":12576},"_9-takeaways","9. Takeaways",[312,12579,12580,12589,12595,12601,12607],{},[315,12581,12582,12585,12586,12588],{},[49,12583,12584],{},"Work out which problem you actually have before you touch anything."," The ask was \"get rid of the ",[100,12587,6521],{},".\" The goal was \"be readable by search engines.\" The first is just one prerequisite for the second. Take the ask literally and you end up with a lovely clean URL on a page crawlers still see as an empty shell.",[315,12590,12591,12594],{},[49,12592,12593],{},"Flip a constraint around and it often turns into the design."," \"The root path can only serve one file\" killed two obvious options and pointed directly at a third: make that file do two jobs. When a constraint has you stuck, it's worth asking what things would look like if the constraint were part of the design.",[315,12596,12597,12600],{},[49,12598,12599],{},"What you add shouldn't cost anything for the people who don't use it."," Home page visitors and crawlers benefit here, but the change lands in an entry point everyone shares. Getting preloading back, lazy-loading the images, and deferring the posters are all there so admin users don't pay for a feature that has nothing to do with them. When you're weighing an approach, give \"impact on unrelated paths\" a column of its own.",[315,12602,12603,12606],{},[49,12604,12605],{},"A silent failure is worse than a loud one."," Failing the build when prerendering fails, and refusing to patch stale output when the build fails, both exist to surface problems before release. That matters most for SEO work, because nobody files a bug when it breaks.",[315,12608,12609,12612],{},[49,12610,12611],{},"Screenshots catch what assertions miss."," That 8px white border sailed through every automated check. If a change touches rendering, get a person to look at the actual page, even if that person is you.",[1042,12614,12615],{},"html .light .shiki span {color: var(--shiki-light);background: var(--shiki-light-bg);font-style: var(--shiki-light-font-style);font-weight: var(--shiki-light-font-weight);text-decoration: var(--shiki-light-text-decoration);}html.light .shiki span {color: var(--shiki-light);background: var(--shiki-light-bg);font-style: var(--shiki-light-font-style);font-weight: var(--shiki-light-font-weight);text-decoration: var(--shiki-light-text-decoration);}html .default .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html.dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html pre.shiki code .slsVL, html code.shiki .slsVL{--shiki-light:#24292E;--shiki-default:#E1E4E8;--shiki-dark:#E1E4E8}html pre.shiki code .sByVh, html code.shiki .sByVh{--shiki-light:#22863A;--shiki-default:#85E89D;--shiki-dark:#85E89D}html pre.shiki code .shcOC, html code.shiki .shcOC{--shiki-light:#6F42C1;--shiki-default:#B392F0;--shiki-dark:#B392F0}html pre.shiki code .sfrk1, html code.shiki .sfrk1{--shiki-light:#032F62;--shiki-default:#9ECBFF;--shiki-dark:#9ECBFF}html pre.shiki code .sCsY4, html code.shiki .sCsY4{--shiki-light:#6A737D;--shiki-default:#6A737D;--shiki-dark:#6A737D}html pre.shiki code .so5gQ, html code.shiki .so5gQ{--shiki-light:#D73A49;--shiki-default:#F97583;--shiki-dark:#F97583}html pre.shiki code .sQeJH, html code.shiki .sQeJH{--shiki-light:#032F62;--shiki-default:#DBEDFF;--shiki-dark:#DBEDFF}html pre.shiki code .suiK_, html code.shiki .suiK_{--shiki-light:#005CC5;--shiki-default:#79B8FF;--shiki-dark:#79B8FF}html pre.shiki code .sAxt1, html code.shiki .sAxt1{--shiki-light:#22863A;--shiki-light-font-weight:bold;--shiki-default:#85E89D;--shiki-default-font-weight:bold;--shiki-dark:#85E89D;--shiki-dark-font-weight:bold}html pre.shiki code .sQHwn, html code.shiki .sQHwn{--shiki-light:#E36209;--shiki-default:#FFAB70;--shiki-dark:#FFAB70}",{"title":15,"searchDepth":25,"depth":25,"links":12617},[12618,12620,12621,12622,12627,12633,12634,12635,12636],{"id":9689,"depth":25,"text":12619},"1. Where It Started: Is # Really the Problem?",{"id":9944,"depth":25,"text":9945},{"id":10107,"depth":25,"text":10108},{"id":10260,"depth":25,"text":10261,"children":12623},[12624,12625,12626],{"id":10264,"depth":213,"text":10265},{"id":10737,"depth":213,"text":10738},{"id":11283,"depth":213,"text":11284},{"id":11530,"depth":25,"text":11531,"children":12628},[12629,12630,12631,12632],{"id":11534,"depth":213,"text":11535},{"id":11618,"depth":213,"text":11619},{"id":11751,"depth":213,"text":11752},{"id":11787,"depth":213,"text":11788},{"id":11960,"depth":25,"text":11961},{"id":12204,"depth":25,"text":12205},{"id":12490,"depth":25,"text":12491},{"id":12576,"depth":25,"text":12577},"2026-11-26","Our marketing home page lived at #\u002Flanding\u002Fhome inside an admin SPA, so crawlers saw an empty shell. Here's why I ended up serving two apps from a single index.html and prerendering one of them at build time, plus the build plugin behind it, four things that bit me, and how I got preloading back after the entry points became dynamic imports.","\u002Farticles\u002Fspa-hash-seo-prerender.svg",{},"\u002Farticles\u002Fspa-hash-seo-prerender",{"title":9629,"description":12638},{"loc":12641},"articles\u002Fspa-hash-seo-prerender",[7011,12646],"Engineering","NLpNmjWUHvqr5RpCs1KC_6L67bKZCviEFzlRl6WYOjc",{"id":12649,"title":12650,"body":12651,"date":13570,"description":13571,"extension":28,"head":27,"image":13572,"meta":13573,"navigation":30,"ogImage":27,"path":13574,"rating":225,"readingTime":7006,"robots":27,"schemaOrg":27,"seo":13575,"sitemap":13576,"stem":13577,"tags":13578,"__hash__":13579},"articles_en\u002Farticles\u002Ftool-or-sub-agent.md","Tool or Sub-Agent? A Decision Tree Forced Out of Me by Four Bugs",{"type":7,"value":12652,"toc":13561},[12653,12656,12659,12662,12665,12668,12671,12675,12678,12685,12688,12692,12695,12705,12708,12713,12716,12778,12862,12865,12869,12876,12955,12958,13066,13069,13155,13158,13161,13168,13171,13175,13182,13185,13314,13317,13320,13324,13331,13338,13398,13405,13412,13419,13426,13430,13433,13467,13470,13531,13534,13538,13541,13548,13551,13553,13556,13559],[17,12654,12655],{},"In the last round of self-testing before handing the feature to QA, I played the visitor and walked through the appointment flow from start to finish. I wanted a treatment on Saturday afternoon, and the AI enthusiastically recommended a specialist named Anna the whole way through: \"Anna is free on Saturday afternoon, and this treatment is one of her specialties.\" Fine, I said, let's go with her. The AI replied: \"You're all booked!\"",[17,12657,12658],{},"I opened the admin console. The name on the appointment was Bella.",[17,12660,12661],{},"It took a dig through the logs to see what had happened. At the submit step, the API returned a list of available specialists in which Anna came later, and the model simply picked whoever was first. What gets promised in the conversation is one thing, and what gets submitted is another. Nothing forced the two to agree.",[17,12663,12664],{},"My first reaction was still that the prompt wasn't tight enough and one more sentence would fix it. Then I kept testing, and the problems kept coming. In a fresh session, the AI got the available slots and placed the booking without ever collecting my contact details, even though the prompt said in plain words \"collect the name and phone before booking\". In another scenario I said \"I'll arrive at 14:00\" and was rejected outright: the backend schedule was a single row covering 13:30–15:00 that only accepts the row's start time, 14:00 was not a start time, and what the visitor experiences is \"there's clearly a free slot, yet I can't book it\". And one that wasn't serious but looked bad: before booking, the AI had a habit of querying the slots once more \"just to confirm\", so the availability card showed up twice in the conversation.",[17,12666,12667],{},"Add the booking where I asked for Anna and got Bella, and that's one afternoon of self-testing and four bugs. All of them were behavioral. Not one was an API error.",[17,12669,12670],{},"The architecture of the appointment feature at the time was very straightforward: check availability, create the appointment, write back a summary. Three tools attached directly to the main agent. The main agent's system prompt was simultaneously in charge of persona, language rules, emoji usage, and three rules of appointment discipline on top.",[58,12672,12674],{"id":12673},"a-prompt-can-lower-the-odds-but-it-cant-give-a-guarantee","A prompt can lower the odds, but it can't give a guarantee",[17,12676,12677],{},"The first round of fixes naturally took the cheapest route: edit the prompt. The rather soft \"ideally collect the visitor's name and phone\" was upgraded to MUST, bolded, and moved to the top of the list. It worked, in the sense that the bug reproduced noticeably less often. But less often is not never. A prompt's hold on behavior is probabilistic; however harsh the wording, it only pushes the violation rate down, never to zero, and after a few more rounds of conversation I would still hit a case of \"got the slots, booked right away\". One bad phrasing in chat does no harm. Booking is a write operation, and one miss is a real order with no contact details on it. That kind of place needs a 0-or-1 guarantee, not a score of 95.",[17,12679,12680,12681,12684],{},"This approach also has a hidden cost that I only saw clearly after a few rounds: ",[49,12682,12683],{},"the model isn't short on intelligence, it's that one brain is in charge of too many things",". Instruction adherence gets diluted as the number of concerns in the prompt grows. Bolding the contact-details rule amounts to turning down the volume on the specialist-selection rule. Bug fixing turns into whack-a-mole: press one down and another pops up.",[17,12686,12687],{},"What needed fixing wasn't any single instruction. It was the structure.",[58,12689,12691],{"id":12690},"before-touching-code-a-sub-agent-is-a-tool-too","Before touching code: a sub-agent is a tool too",[17,12693,12694],{},"The direction of the refactor wasn't hard to come up with: move appointments out as a whole block and give them a brain of their own. But before I started, there was one concept I was forced to get straight.",[17,12696,12697,12698,12704],{},"Discussions of multi-agent architecture tend to describe \"tools\" and \"sub-agents\" as two parallel things. Down at the code level, though, ",[49,12699,12700,12701],{},"in the main agent's eyes a sub-agent is just a ",[100,12702,12703],{},"@tool",": it sits in the same tool list and goes through the same function calling protocol. The main agent has no idea, and has no need to know, whether three lines of code or another LLM sits behind that tool.",[17,12706,12707],{},"So the precise way to ask \"tool or sub-agent\" is really this:",[424,12709,12710],{},[17,12711,12712],{},"Inside this tool's implementation, is there a piece of deterministic code, or is another LLM hidden in there, with its own prompt, its own context, and its own loop?",[17,12714,12715],{},"Here are the two execution paths side by side:",[191,12717,12719],{"className":193,"code":12718,"language":195,"meta":15,"style":15},"flowchart TB\n    subgraph pure[\"Plain tool (e.g. show the store card, get the current time)\"]\n        A1[\"Main agent LLM decides to call\"] --> A2[\"Deterministic code runs\"]\n        A2 --> A3[\"Result is appended to the main\u003Cbr\u002F>conversation context as a ToolMessage\"]\n        A3 --> A4[\"The same LLM keeps thinking\"]\n    end\n\n    subgraph sub[\"Sub-agent (e.g. appointments, knowledge base lookup)\"]\n        B1[\"Main agent LLM decides to call\"] --> B2[\"Another LLM starts inside\u003Cbr\u002F>the tool implementation\"]\n        B2 --> B3[\"Its own system prompt\u003Cbr\u002F>Its own clean context\u003Cbr\u002F>Its own tools and its own loop\"]\n        B3 --> B4[\"Only a compressed factual report\u003Cbr\u002F>returns to the main context as the tool result\"]\n    end\n",[100,12720,12721,12726,12731,12736,12741,12746,12750,12754,12759,12764,12769,12774],{"__ignoreMap":15},[199,12722,12723],{"class":201,"line":202},[199,12724,12725],{},"flowchart TB\n",[199,12727,12728],{"class":201,"line":25},[199,12729,12730],{},"    subgraph pure[\"Plain tool (e.g. show the store card, get the current time)\"]\n",[199,12732,12733],{"class":201,"line":213},[199,12734,12735],{},"        A1[\"Main agent LLM decides to call\"] --> A2[\"Deterministic code runs\"]\n",[199,12737,12738],{"class":201,"line":219},[199,12739,12740],{},"        A2 --> A3[\"Result is appended to the main\u003Cbr\u002F>conversation context as a ToolMessage\"]\n",[199,12742,12743],{"class":201,"line":225},[199,12744,12745],{},"        A3 --> A4[\"The same LLM keeps thinking\"]\n",[199,12747,12748],{"class":201,"line":231},[199,12749,2354],{},[199,12751,12752],{"class":201,"line":237},[199,12753,461],{"emptyLinePlaceholder":30},[199,12755,12756],{"class":201,"line":243},[199,12757,12758],{},"    subgraph sub[\"Sub-agent (e.g. appointments, knowledge base lookup)\"]\n",[199,12760,12761],{"class":201,"line":249},[199,12762,12763],{},"        B1[\"Main agent LLM decides to call\"] --> B2[\"Another LLM starts inside\u003Cbr\u002F>the tool implementation\"]\n",[199,12765,12766],{"class":201,"line":255},[199,12767,12768],{},"        B2 --> B3[\"Its own system prompt\u003Cbr\u002F>Its own clean context\u003Cbr\u002F>Its own tools and its own loop\"]\n",[199,12770,12771],{"class":201,"line":261},[199,12772,12773],{},"        B3 --> B4[\"Only a compressed factual report\u003Cbr\u002F>returns to the main context as the tool result\"]\n",[199,12775,12776],{"class":201,"line":267},[199,12777,2354],{},[105,12779,12780,12792],{},[108,12781,12782],{},[111,12783,12784,12786,12789],{},[114,12785,3839],{},[114,12787,12788],{},"Plain tool",[114,12790,12791],{},"Sub-agent",[121,12793,12794,12804,12815,12829,12840,12851],{},[111,12795,12796,12798,12801],{},[126,12797,4474],{},[126,12799,12800],{},"Deterministic code",[126,12802,12803],{},"Another LLM (plus its own tools)",[111,12805,12806,12809,12812],{},[126,12807,12808],{},"Where instructions live",[126,12810,12811],{},"Only the docstring (weak constraint)",[126,12813,12814],{},"A dedicated system prompt (strong constraint)",[111,12816,12817,12820,12826],{},[126,12818,12819],{},"Where intermediate output goes",[126,12821,12822,12823],{},"Straight into the main conversation history, ",[49,12824,12825],{},"costing tokens forever",[126,12827,12828],{},"Stays in the worker's temporary context and is destroyed with the task",[111,12830,12831,12834,12837],{},[126,12832,12833],{},"Decision structure",[126,12835,12836],{},"One brain makes every decision",[126,12838,12839],{},"Layered: the supervisor hands out work, the worker decides how to do it",[111,12841,12842,12845,12848],{},[126,12843,12844],{},"Extra cost",[126,12846,12847],{},"0 LLM calls",[126,12849,12850],{},"+1 to N LLM calls, plus one hop of latency",[111,12852,12853,12856,12859],{},[126,12854,12855],{},"Iteration radius",[126,12857,12858],{},"Changing behavior means touching the main prompt, with global regression risk",[126,12860,12861],{},"Only the worker prompt changes; the main conversation notices nothing",[17,12863,12864],{},"The last row of that table is both the root cause of those four bugs and the cure.",[58,12866,12868],{"id":12867},"the-refactor-the-main-agent-only-hands-out-work","The refactor: the main agent only hands out work",[17,12870,12871,12872,12875],{},"After the refactor, the main agent no longer carries the three appointment tools. It carries a single dispatch tool, ",[100,12873,12874],{},"handle_appointment(request)",". Its docstring is itself a \"dispatch contract\" that forces the main agent to pack up, in one go, the information scattered across the conversation:",[191,12877,12879],{"className":384,"code":12878,"language":386,"meta":15,"style":15},"@tool\nasync def handle_appointment(request: str) -> str:\n    \"\"\"Handle anything appointment-related: check availability, create\n    a booking, or update the appointment summary.\n\n    Hand off ONE clear English request carrying everything known from\n    the conversation: the concrete date (convert relative dates first)\n    and time; the specialist by name whenever a specific one came up —\n    or an explicit note that the visitor said anyone is fine; the\n    visitor's name \u002F phone if collected; and a 2-3 sentence summary\n    of the visitor's needs for the store staff.\n    \"\"\"\n    task = task_mgr.create(request)\n    await run_booking_subagent(task)   # awaited in the same turn; returns only when the worker is done\n    return task.result                  # only the compressed factual report goes back to the main conversation\n",[100,12880,12881,12886,12891,12896,12901,12905,12910,12915,12920,12925,12930,12935,12940,12945,12950],{"__ignoreMap":15},[199,12882,12883],{"class":201,"line":202},[199,12884,12885],{},"@tool\n",[199,12887,12888],{"class":201,"line":25},[199,12889,12890],{},"async def handle_appointment(request: str) -> str:\n",[199,12892,12893],{"class":201,"line":213},[199,12894,12895],{},"    \"\"\"Handle anything appointment-related: check availability, create\n",[199,12897,12898],{"class":201,"line":219},[199,12899,12900],{},"    a booking, or update the appointment summary.\n",[199,12902,12903],{"class":201,"line":225},[199,12904,461],{"emptyLinePlaceholder":30},[199,12906,12907],{"class":201,"line":231},[199,12908,12909],{},"    Hand off ONE clear English request carrying everything known from\n",[199,12911,12912],{"class":201,"line":237},[199,12913,12914],{},"    the conversation: the concrete date (convert relative dates first)\n",[199,12916,12917],{"class":201,"line":243},[199,12918,12919],{},"    and time; the specialist by name whenever a specific one came up —\n",[199,12921,12922],{"class":201,"line":249},[199,12923,12924],{},"    or an explicit note that the visitor said anyone is fine; the\n",[199,12926,12927],{"class":201,"line":255},[199,12928,12929],{},"    visitor's name \u002F phone if collected; and a 2-3 sentence summary\n",[199,12931,12932],{"class":201,"line":261},[199,12933,12934],{},"    of the visitor's needs for the store staff.\n",[199,12936,12937],{"class":201,"line":267},[199,12938,12939],{},"    \"\"\"\n",[199,12941,12942],{"class":201,"line":273},[199,12943,12944],{},"    task = task_mgr.create(request)\n",[199,12946,12947],{"class":201,"line":279},[199,12948,12949],{},"    await run_booking_subagent(task)   # awaited in the same turn; returns only when the worker is done\n",[199,12951,12952],{"class":201,"line":285},[199,12953,12954],{},"    return task.result                  # only the compressed factual report goes back to the main conversation\n",[17,12956,12957],{},"On the worker side I didn't bring in a heavy framework. It's a small hand-written ReAct loop (the LLM picks a tool, the tool runs, the result is fed back, the LLM thinks again) plus a step budget:",[191,12959,12961],{"className":384,"code":12960,"language":386,"meta":15,"style":15},"_MAX_LLM_STEPS = 5   # check slots → create → final report fits in this; guards against runaway loops\n\nasync def run_booking_subagent(task):\n    messages = [\n        SystemMessage(content=BOOKING_WORKER_PROMPT),  # dedicated prompt\n        HumanMessage(content=task.request),            # only the task description; no conversation history\n    ]\n    for _ in range(_MAX_LLM_STEPS):\n        ai = await worker_llm.ainvoke(messages)\n        if not ai.tool_calls:               # no more tool calls = the final report\n            task.result = ai.text\n            break\n        messages.append(ai)\n        for tc in ai.tool_calls:            # tool results are fed back only into the worker's own context\n            out = await tools[tc[\"name\"]].ainvoke(tc[\"args\"])\n            messages.append(ToolMessage(content=out, tool_call_id=tc[\"id\"]))\n    else:\n        # budget exhausted while still picking tools: return a fallback report\n        # the main agent can phrase, rather than coming back empty-handed\n        task.result = (\"Booking task did not complete within the step budget; \"\n                       \"suggest the visitor contact the store directly.\")\n",[100,12962,12963,12968,12972,12977,12982,12987,12992,12997,13002,13007,13012,13017,13022,13027,13032,13037,13042,13046,13051,13056,13061],{"__ignoreMap":15},[199,12964,12965],{"class":201,"line":202},[199,12966,12967],{},"_MAX_LLM_STEPS = 5   # check slots → create → final report fits in this; guards against runaway loops\n",[199,12969,12970],{"class":201,"line":25},[199,12971,461],{"emptyLinePlaceholder":30},[199,12973,12974],{"class":201,"line":213},[199,12975,12976],{},"async def run_booking_subagent(task):\n",[199,12978,12979],{"class":201,"line":219},[199,12980,12981],{},"    messages = [\n",[199,12983,12984],{"class":201,"line":225},[199,12985,12986],{},"        SystemMessage(content=BOOKING_WORKER_PROMPT),  # dedicated prompt\n",[199,12988,12989],{"class":201,"line":231},[199,12990,12991],{},"        HumanMessage(content=task.request),            # only the task description; no conversation history\n",[199,12993,12994],{"class":201,"line":237},[199,12995,12996],{},"    ]\n",[199,12998,12999],{"class":201,"line":243},[199,13000,13001],{},"    for _ in range(_MAX_LLM_STEPS):\n",[199,13003,13004],{"class":201,"line":249},[199,13005,13006],{},"        ai = await worker_llm.ainvoke(messages)\n",[199,13008,13009],{"class":201,"line":255},[199,13010,13011],{},"        if not ai.tool_calls:               # no more tool calls = the final report\n",[199,13013,13014],{"class":201,"line":261},[199,13015,13016],{},"            task.result = ai.text\n",[199,13018,13019],{"class":201,"line":267},[199,13020,13021],{},"            break\n",[199,13023,13024],{"class":201,"line":273},[199,13025,13026],{},"        messages.append(ai)\n",[199,13028,13029],{"class":201,"line":279},[199,13030,13031],{},"        for tc in ai.tool_calls:            # tool results are fed back only into the worker's own context\n",[199,13033,13034],{"class":201,"line":285},[199,13035,13036],{},"            out = await tools[tc[\"name\"]].ainvoke(tc[\"args\"])\n",[199,13038,13039],{"class":201,"line":651},[199,13040,13041],{},"            messages.append(ToolMessage(content=out, tool_call_id=tc[\"id\"]))\n",[199,13043,13044],{"class":201,"line":970},[199,13045,8085],{},[199,13047,13048],{"class":201,"line":976},[199,13049,13050],{},"        # budget exhausted while still picking tools: return a fallback report\n",[199,13052,13053],{"class":201,"line":982},[199,13054,13055],{},"        # the main agent can phrase, rather than coming back empty-handed\n",[199,13057,13058],{"class":201,"line":988},[199,13059,13060],{},"        task.result = (\"Booking task did not complete within the step budget; \"\n",[199,13062,13063],{"class":201,"line":994},[199,13064,13065],{},"                       \"suggest the visitor contact the store directly.\")\n",[17,13067,13068],{},"The full path of one booking:",[191,13070,13072],{"className":193,"code":13071,"language":195,"meta":15,"style":15},"sequenceDiagram\n    autonumber\n    participant V as Visitor\n    participant M as Main agent\n    participant W as Booking worker\n    participant T as Booking tools (deterministic code)\n    participant B as Business backend\n\n    V->>M: Saturday at 2 pm, with Anna\n    M->>W: handle_appointment(packed task description in English)\n    Note over W: Own prompt + clean context\u003Cbr\u002F>ReAct loop, ≤5 steps\n    W->>T: book_appointment(date, time, specialist_name=\"Anna\", ...)\n    T->>B: Query the day's availability + validate + submit\n    B-->>T: appointment_id\n    T-->>W: Structured result (the card reaches the frontend via a separate channel)\n    W-->>M: Compressed factual report\n    M-->>V: Confirmation worded for the visitor\n",[100,13073,13074,13078,13082,13087,13091,13096,13101,13106,13110,13115,13120,13125,13130,13135,13140,13145,13150],{"__ignoreMap":15},[199,13075,13076],{"class":201,"line":202},[199,13077,892],{},[199,13079,13080],{"class":201,"line":25},[199,13081,2276],{},[199,13083,13084],{"class":201,"line":213},[199,13085,13086],{},"    participant V as Visitor\n",[199,13088,13089],{"class":201,"line":219},[199,13090,8142],{},[199,13092,13093],{"class":201,"line":225},[199,13094,13095],{},"    participant W as Booking worker\n",[199,13097,13098],{"class":201,"line":231},[199,13099,13100],{},"    participant T as Booking tools (deterministic code)\n",[199,13102,13103],{"class":201,"line":237},[199,13104,13105],{},"    participant B as Business backend\n",[199,13107,13108],{"class":201,"line":243},[199,13109,461],{"emptyLinePlaceholder":30},[199,13111,13112],{"class":201,"line":249},[199,13113,13114],{},"    V->>M: Saturday at 2 pm, with Anna\n",[199,13116,13117],{"class":201,"line":255},[199,13118,13119],{},"    M->>W: handle_appointment(packed task description in English)\n",[199,13121,13122],{"class":201,"line":261},[199,13123,13124],{},"    Note over W: Own prompt + clean context\u003Cbr\u002F>ReAct loop, ≤5 steps\n",[199,13126,13127],{"class":201,"line":267},[199,13128,13129],{},"    W->>T: book_appointment(date, time, specialist_name=\"Anna\", ...)\n",[199,13131,13132],{"class":201,"line":273},[199,13133,13134],{},"    T->>B: Query the day's availability + validate + submit\n",[199,13136,13137],{"class":201,"line":279},[199,13138,13139],{},"    B-->>T: appointment_id\n",[199,13141,13142],{"class":201,"line":285},[199,13143,13144],{},"    T-->>W: Structured result (the card reaches the frontend via a separate channel)\n",[199,13146,13147],{"class":201,"line":651},[199,13148,13149],{},"    W-->>M: Compressed factual report\n",[199,13151,13152],{"class":201,"line":970},[199,13153,13154],{},"    M-->>V: Confirmation worded for the visitor\n",[17,13156,13157],{},"Only after it had been running in production for a while did the real value of this refactor gradually show, and it went beyond \"the bugs are fixed\".",[17,13159,13160],{},"The raw response of a slot query is a large JSON of \"many specialists × many time ranges\". In the direct-attach days, that blob entered the main conversation history permanently as a ToolMessage, and every later turn paid tokens to carry it. Now it lives only in the worker's one-off context and is destroyed when the task ends. All that comes back to the main conversation is a single line: \"Anna is available at 14:00 on Saturday, booked, id=xxx\".",[17,13162,13163,13164,13167],{},"The behavioral discipline of booking (don't query slots before booking, don't submit without contact details, how to read the specialist signal) moved wholesale into the worker's own system prompt, and the three appointment bullets in the main agent collapsed into one dispatch guideline. I tuned booking behavior several more rounds after that, each time touching only the worker's prompt, and the persona and language style of the main conversation never regressed once. ",[49,13165,13166],{},"The blast radius is locked inside the worker",", and that is the most valuable thing the refactor bought.",[17,13169,13170],{},"There is one more, less visible layer: the act of packing the task description is itself an inventory of information. Has the date been converted to an absolute one? Is there a specialist signal? Have the contact details been collected? Whatever is missing is exposed at packing time, rather than blowing up at submit time.",[58,13172,13174],{"id":13173},"the-worker-cant-see-the-conversation-history-so-there-has-to-be-code-that-says-no","The worker can't see the conversation history, so there has to be code that says \"no\"",[17,13176,13177,13178,13181],{},"The sub-agent pattern has a structural risk that should be stated openly: ",[49,13179,13180],{},"the worker can't see the conversation history",". If the main agent, while packing, drops the phone number the visitor mentioned five turns ago, the worker has no way of ever knowing. This is an inherent flaw of free-text dispatch. \"Writing a stricter prompt\" can only make it rarer, never seal it off, and I had already paid the tuition for that lesson.",[17,13183,13184],{},"So every hard constraint was pushed down into deterministic code. However freely the worker improvises, if the code doesn't let it through, nothing gets submitted:",[191,13186,13188],{"className":384,"code":13187,"language":386,"meta":15,"style":15},"# Gate 1: specialist selection. With no explicit signal (a given id \u002F an explicit\n# \"anyone is fine\") and several people available, never pick silently. Return the\n# candidate list and bounce it back so the main agent asks the visitor.\nif not specialist_id and not any_specialist and len(available_at_time) > 1:\n    return {\n        \"success\": False,\n        \"needs_specialist_choice\": True,\n        \"specialists\": [{\"id\": sp_id, \"name\": sp_name} for ...],\n    }\n\n# Gate 2: contact details. Intercept after the slot and specialist have passed\n# validation and before submitting. The bounce carries the fact that \"this time is\n# confirmed available\", so the main agent can mention it when asking for contact details.\nif not customer_name.strip() or not phone.strip():\n    return {\n        \"success\": False,\n        \"needs_contact\": True,\n        \"verified_available\": True,   # availability already verified; don't waste it when following up\n        \"date\": date, \"start_time\": start_time,\n    }\n\n# Gate 3: time alignment. The backend schedule only accepts a row's start time, but a\n# visitor saying 14:00 shouldn't be rejected. Snap to the free row that covers it (13:30)\n# and write the visitor's actual arrival time into the note for the store staff.\nif booked_start != start_time:\n    note += f\" Customer plans to arrive at {start_time}.\"\n",[100,13189,13190,13195,13200,13205,13210,13215,13220,13225,13230,13234,13238,13243,13248,13253,13258,13262,13266,13271,13276,13281,13285,13289,13294,13299,13304,13309],{"__ignoreMap":15},[199,13191,13192],{"class":201,"line":202},[199,13193,13194],{},"# Gate 1: specialist selection. With no explicit signal (a given id \u002F an explicit\n",[199,13196,13197],{"class":201,"line":25},[199,13198,13199],{},"# \"anyone is fine\") and several people available, never pick silently. Return the\n",[199,13201,13202],{"class":201,"line":213},[199,13203,13204],{},"# candidate list and bounce it back so the main agent asks the visitor.\n",[199,13206,13207],{"class":201,"line":219},[199,13208,13209],{},"if not specialist_id and not any_specialist and len(available_at_time) > 1:\n",[199,13211,13212],{"class":201,"line":225},[199,13213,13214],{},"    return {\n",[199,13216,13217],{"class":201,"line":231},[199,13218,13219],{},"        \"success\": False,\n",[199,13221,13222],{"class":201,"line":237},[199,13223,13224],{},"        \"needs_specialist_choice\": True,\n",[199,13226,13227],{"class":201,"line":243},[199,13228,13229],{},"        \"specialists\": [{\"id\": sp_id, \"name\": sp_name} for ...],\n",[199,13231,13232],{"class":201,"line":249},[199,13233,8475],{},[199,13235,13236],{"class":201,"line":255},[199,13237,461],{"emptyLinePlaceholder":30},[199,13239,13240],{"class":201,"line":261},[199,13241,13242],{},"# Gate 2: contact details. Intercept after the slot and specialist have passed\n",[199,13244,13245],{"class":201,"line":267},[199,13246,13247],{},"# validation and before submitting. The bounce carries the fact that \"this time is\n",[199,13249,13250],{"class":201,"line":273},[199,13251,13252],{},"# confirmed available\", so the main agent can mention it when asking for contact details.\n",[199,13254,13255],{"class":201,"line":279},[199,13256,13257],{},"if not customer_name.strip() or not phone.strip():\n",[199,13259,13260],{"class":201,"line":285},[199,13261,13214],{},[199,13263,13264],{"class":201,"line":651},[199,13265,13219],{},[199,13267,13268],{"class":201,"line":970},[199,13269,13270],{},"        \"needs_contact\": True,\n",[199,13272,13273],{"class":201,"line":976},[199,13274,13275],{},"        \"verified_available\": True,   # availability already verified; don't waste it when following up\n",[199,13277,13278],{"class":201,"line":982},[199,13279,13280],{},"        \"date\": date, \"start_time\": start_time,\n",[199,13282,13283],{"class":201,"line":988},[199,13284,8475],{},[199,13286,13287],{"class":201,"line":994},[199,13288,461],{"emptyLinePlaceholder":30},[199,13290,13291],{"class":201,"line":2371},[199,13292,13293],{},"# Gate 3: time alignment. The backend schedule only accepts a row's start time, but a\n",[199,13295,13296],{"class":201,"line":2377},[199,13297,13298],{},"# visitor saying 14:00 shouldn't be rejected. Snap to the free row that covers it (13:30)\n",[199,13300,13301],{"class":201,"line":2383},[199,13302,13303],{},"# and write the visitor's actual arrival time into the note for the store staff.\n",[199,13305,13306],{"class":201,"line":2389},[199,13307,13308],{},"if booked_start != start_time:\n",[199,13310,13311],{"class":201,"line":2395},[199,13312,13313],{},"    note += f\" Customer plans to arrive at {start_time}.\"\n",[17,13315,13316],{},"Count them off against the four bugs from the beginning. Silently swapping the specialist: sealed by gate 1. Skipping contact details: sealed by gate 2. The rejected 14:00: resolved by gate 3. The card showing twice: handled by one rule in the worker prompt, \"for a booking task, submit directly; the tool validates on its own; do not query slots first\". That rule is followed reliably precisely because the worker's prompt does this one thing only.",[17,13318,13319],{},"The prompt guides, and the code says \"no\". That is the precondition for free-text dispatch to work safely.",[58,13321,13323],{"id":13322},"the-knowledge-base-is-a-one-step-job-worth-another-layer","The knowledge base: is a one-step job worth another layer?",[17,13325,13326,13327,13330],{},"Putting appointments behind a sub-agent makes obvious sense: multiple steps, dependencies, fallbacks. What actually made me hesitate was knowledge base retrieval. It is a single step: pick a query and search the vector store. Why not attach ",[100,13328,13329],{},"knowledge_retrieve(query)"," straight to the main agent and save an LLM call?",[17,13332,13333,13334,13337],{},"In the end I wrapped it in a layer anyway, as a \"single-shot sub-agent\": the worker calls the LLM exactly ",[49,13335,13336],{},"once"," to translate the goal given by the main agent into retrieval queries (several can run in parallel), and after retrieval it returns the factual digest as is, without even a second summarization pass.",[191,13339,13341],{"className":384,"code":13340,"language":386,"meta":15,"style":15},"async def run_knowledge_subagent(task):\n    # exactly 1 LLM call: decide which queries to send\n    ai = await worker_llm.ainvoke([\n        SystemMessage(content=KNOWLEDGE_WORKER_PROMPT),  # prompt dedicated to retrieval engineering\n        HumanMessage(content=task.goal),\n    ])\n    facts = []\n    for tc in ai.tool_calls:          # one decision can fan out into several parallel retrievals\n        out = await tools[tc[\"name\"]].ainvoke(tc[\"args\"])\n        facts.append(out)\n    task.result = \"\\n\".join(facts)    # the factual digest goes straight back to the main agent, no second summary\n",[100,13342,13343,13348,13353,13358,13363,13368,13373,13378,13383,13388,13393],{"__ignoreMap":15},[199,13344,13345],{"class":201,"line":202},[199,13346,13347],{},"async def run_knowledge_subagent(task):\n",[199,13349,13350],{"class":201,"line":25},[199,13351,13352],{},"    # exactly 1 LLM call: decide which queries to send\n",[199,13354,13355],{"class":201,"line":213},[199,13356,13357],{},"    ai = await worker_llm.ainvoke([\n",[199,13359,13360],{"class":201,"line":219},[199,13361,13362],{},"        SystemMessage(content=KNOWLEDGE_WORKER_PROMPT),  # prompt dedicated to retrieval engineering\n",[199,13364,13365],{"class":201,"line":225},[199,13366,13367],{},"        HumanMessage(content=task.goal),\n",[199,13369,13370],{"class":201,"line":231},[199,13371,13372],{},"    ])\n",[199,13374,13375],{"class":201,"line":237},[199,13376,13377],{},"    facts = []\n",[199,13379,13380],{"class":201,"line":243},[199,13381,13382],{},"    for tc in ai.tool_calls:          # one decision can fan out into several parallel retrievals\n",[199,13384,13385],{"class":201,"line":249},[199,13386,13387],{},"        out = await tools[tc[\"name\"]].ainvoke(tc[\"args\"])\n",[199,13389,13390],{"class":201,"line":255},[199,13391,13392],{},"        facts.append(out)\n",[199,13394,13395],{"class":201,"line":261},[199,13396,13397],{},"    task.result = \"\\n\".join(facts)    # the factual digest goes straight back to the main agent, no second summary\n",[17,13399,13400,13401,13404],{},"What convinced me to pay for that extra LLM call was something that kept happening in the direct-attach days: the main agent tends to use the visitor's own words as the query. A visitor asks in Chinese \"can I cancel my appointment?\", while the knowledge base documents are in English. The original Chinese sentence doesn't line up with the English documents in embedding space, and the retrieval misses. ",[49,13402,13403],{},"A goal and a query are two different things, and translating the former into the latter is a craft",": one query for a single topic, two parallel queries for a double topic, always phrased in the language of the documents. That body of retrieval know-how deserves a dedicated prompt. And stuffing it into the main prompt? That would be whack-a-mole again, the pit I had just climbed out of.",[17,13406,13407,13408,13411],{},"As for why even the second summary is dropped: the main agent has to compose the final reply from the digest anyway, so having the worker summarize once more is a double rewrite, the classic source of distortion in a RAG pipeline, with an extra call paid for nothing. Retrieved facts should simply be passed up as they are. If I later add a reranker, hybrid search, or a retry with rephrased queries on empty results, all of it happens inside the worker, and the ",[100,13409,13410],{},"query_knowledge_base(goal)"," that the main agent sees doesn't change by a single character.",[17,13413,13414,13415,13418],{},"One point that is easy to confuse, while I'm here: ",[49,13416,13417],{},"\"single-shot\" limits the number of decision rounds, not the number of queries",". In the function calling protocol, one LLM response can carry several parallel tool calls, so the worker can fan out three queries at once from a single decision. What costs money is each round of decision (one LLM call plus a few hundred milliseconds), not each execution.",[17,13420,13421,13422,13425],{},"Conversely, if your knowledge base is monolingual and the user's own words hit as a query, attaching the retrieval tool directly is entirely valid, and the call you save is pure gain. Where the line falls depends on one thing: ",[49,13423,13424],{},"whether \"how to search\" involves expertise independent of \"how to talk\"",". Only if it does is it worth giving it a brain.",[58,13427,13429],{"id":13428},"four-capabilities-that-happen-to-form-a-tree","Four capabilities that happen to form a tree",[17,13431,13432],{},"This project has four capabilities: showing the store card, getting the current time, knowledge base retrieval, and appointments. Having stepped on every one of them, I found they cover the whole spectrum, and the selection logic grew into a tree on its own:",[191,13434,13436],{"className":193,"code":13435,"language":195,"meta":15,"style":15},"flowchart TD\n    Q1{\"Does this capability need\u003Cbr\u002F>LLM judgment?\"}\n    Q1 -- \"No\u003Cbr\u002F>(read a cache, get the time)\" --> T1[\"Plain tool\u003Cbr\u002F>Store card \u002F current time\"]\n    Q1 -- Yes --> Q2{\"Can it finish in one step,\u003Cbr\u002F>or do the steps depend on each other?\"}\n    Q2 -- \"One step\u003Cbr\u002F>(multiple queries via parallel fan-out)\" --> T2[\"Single-shot sub-agent\u003Cbr\u002F>Knowledge base retrieval: 1 LLM call picks the queries\"]\n    Q2 -- \"Dependencies \u002F retries and fallbacks\" --> T3[\"Looping sub-agent\u003Cbr\u002F>Appointments: ReAct, ≤5 steps + fallback on exhaustion\"]\n",[100,13437,13438,13442,13447,13452,13457,13462],{"__ignoreMap":15},[199,13439,13440],{"class":201,"line":202},[199,13441,205],{},[199,13443,13444],{"class":201,"line":25},[199,13445,13446],{},"    Q1{\"Does this capability need\u003Cbr\u002F>LLM judgment?\"}\n",[199,13448,13449],{"class":201,"line":213},[199,13450,13451],{},"    Q1 -- \"No\u003Cbr\u002F>(read a cache, get the time)\" --> T1[\"Plain tool\u003Cbr\u002F>Store card \u002F current time\"]\n",[199,13453,13454],{"class":201,"line":219},[199,13455,13456],{},"    Q1 -- Yes --> Q2{\"Can it finish in one step,\u003Cbr\u002F>or do the steps depend on each other?\"}\n",[199,13458,13459],{"class":201,"line":225},[199,13460,13461],{},"    Q2 -- \"One step\u003Cbr\u002F>(multiple queries via parallel fan-out)\" --> T2[\"Single-shot sub-agent\u003Cbr\u002F>Knowledge base retrieval: 1 LLM call picks the queries\"]\n",[199,13463,13464],{"class":201,"line":231},[199,13465,13466],{},"    Q2 -- \"Dependencies \u002F retries and fallbacks\" --> T3[\"Looping sub-agent\u003Cbr\u002F>Appointments: ReAct, ≤5 steps + fallback on exhaustion\"]\n",[17,13468,13469],{},"Every step from left to right on the tree buys something and adds cost. These are the signals that it is time to move right:",[105,13471,13472,13485],{},[108,13473,13474],{},[111,13475,13476,13479,13482],{},[114,13477,13478],{},"Signal",[114,13480,13481],{},"Keep it attached directly",[114,13483,13484],{},"Time to upgrade",[121,13486,13487,13498,13509,13520],{},[111,13488,13489,13492,13495],{},[126,13490,13491],{},"Size of tool output",[126,13493,13494],{},"Small; fine to put straight into the context",[126,13496,13497],{},"Large raw payload that needs digesting and compressing",[111,13499,13500,13503,13506],{},[126,13501,13502],{},"Shape of the steps",[126,13504,13505],{},"A single call",[126,13507,13508],{},"A chain of tools plus retries and fallbacks",[111,13510,13511,13514,13517],{},[126,13512,13513],{},"Iteration rhythm",[126,13515,13516],{},"Tuning it together with the main conversation is fine",[126,13518,13519],{},"Needs frequent tuning independent of the main conversation",[111,13521,13522,13525,13528],{},[126,13523,13524],{},"Number of tools on the main agent",[126,13526,13527],{},"Still modest after adding it (no more than 6 or 7)",[126,13529,13530],{},"Tool selection has already started going wrong",[17,13532,13533],{},"The depth of the loop likewise follows the dependencies, not the importance of the task. The multiple queries of a retrieval are independent of each other, so one decision with parallel fan-out is enough, and one more step buys no new information. Booking is a dependency chain of \"specialist name → id → submit → fallback on failure\", where you must observe a result before deciding again, and only that earns a loop. And the loop must have a step budget and a fallback for exhaustion; otherwise you have merely moved \"runaway\" from the main conversation into the worker, to run away somewhere else.",[58,13535,13537],{"id":13536},"this-layer-of-abstraction-is-billed-per-call","This layer of abstraction is billed per call",[17,13539,13540],{},"The muscle memory I built writing frontend code hurt me here for a while: when logic gets complicated, extract a component or a composable, since abstraction is nearly free and costs two more files at most.",[17,13542,13543,13544,13547],{},"Not so in agents. ",[49,13545,13546],{},"Every sub-agent layer you extract costs real money on every call",": 1 to N more LLM calls and one more hop of latency. And that is only the visible bill. There are two hidden ones. First, in the direct-attach days the tool parameters were a strongly typed schema (date must be a date, phone must be present); after dispatch, what the main agent passes to the worker is a piece of free text, so the type constraints moved down a whole layer, and the code gates exist to make up for exactly that. Second, debugging: for any behavioral problem you first have to work out whether the main agent dropped information while packing or the worker went off track while executing. The investigation path gets longer, and none of the supporting pieces, such as task ids and per-step logs, can be skipped.",[17,13549,13550],{},"So every time I feel like extracting a layer now, I ask myself first: do leaner context, isolated iteration, and better decisions, added together, outweigh a cost that is billed per call? If not, I attach the tool directly and leave it at that. No symmetry for symmetry's sake, and no paying for architectural neatness.",[1940,13552],{},[17,13554,13555],{},"This structure is a lightweight version of the same idea behind LangGraph's supervisor pattern: a supervisor turns sub-agents into graph nodes dispatched by a routing function, whereas we wrap the sub-agent inside a tool implementation. It is transparent to the main agent, leaves the main graph untouched, and reuses the existing tool-calling infrastructure. The price is that workers can't talk to each other directly, and everything has to be relayed through the main agent. For a customer service scenario, that is enough.",[17,13557,13558],{},"If one day it isn't, upgrading then won't be too late. Architecture has always been pushed forward by problems. Had it not been for those four bugs, starting with asking for Anna and getting Bella, I would probably still think \"the difference between a tool and a sub-agent\" was a question that only mattered on paper.",[1042,13560,1044],{},{"title":15,"searchDepth":25,"depth":25,"links":13562},[13563,13564,13565,13566,13567,13568,13569],{"id":12673,"depth":25,"text":12674},{"id":12690,"depth":25,"text":12691},{"id":12867,"depth":25,"text":12868},{"id":13173,"depth":25,"text":13174},{"id":13322,"depth":25,"text":13323},{"id":13428,"depth":25,"text":13429},{"id":13536,"depth":25,"text":13537},"2026-07-17","One afternoon of self-testing an appointment feature surfaced four behavioral bugs and pushed me to refactor directly attached tools into a sub-agent. This is the post-mortem, plus a decision tree for choosing between a plain tool, a single-shot sub-agent, and a looping sub-agent.","\u002Farticles\u002Ftool-or-sub-agent.svg",{},"\u002Farticles\u002Ftool-or-sub-agent",{"title":12650,"description":13571},{"loc":13574},"articles\u002Ftool-or-sub-agent",[1066,1067],"7nwIpAP96NJUnXEfQR5-BTEI_OPrrKOPSVnisfXIFXc",{"id":13581,"title":13582,"body":13583,"date":15065,"description":15066,"extension":28,"head":27,"image":15067,"meta":15068,"navigation":30,"ogImage":27,"path":15069,"rating":225,"readingTime":15070,"robots":27,"schemaOrg":27,"seo":15071,"sitemap":15072,"stem":15073,"tags":15074,"__hash__":15075},"articles_en\u002Farticles\u002Fvite-proxy-change-origin.md","I Switched My Dev Server to HTTPS and Login Broke — The changeOrigin Naming Trap",{"type":7,"value":13584,"toc":15054},[13585,13596,13618,13622,13633,13647,13654,13658,13661,13675,13689,13709,13716,13968,13997,14000,14015,14018,14022,14025,14046,14049,14052,14056,14059,14106,14113,14137,14140,14203,14225,14236,14240,14243,14269,14294,14300,14303,14347,14354,14357,14361,14390,14416,14440,14449,14502,14508,14533,14537,14540,14670,14680,14683,14688,14737,14742,14787,14793,14799,14833,14839,14843,14862,14931,14941,14945,14980,14985,15051],[17,13586,13587,13588,13591,13592,13595],{},"The config said ",[100,13589,13590],{},"changeOrigin: true",", yet the Origin header was forwarded to the upstream untouched. ",[49,13593,13594],{},"The \"origin\" in that option's name and the Origin of the same-origin policy are not the same concept."," This post documents a complete 403 investigation: the final fix is six lines of code, but getting there meant digging into several low-level details of how vite's proxy works.",[43,13597,13598,13602],{},[17,13599,13600],{},[49,13601,9655],{},[348,13603,13604,13609],{},[315,13605,13606,13608],{},[49,13607,2523],{},": The day after I enabled HTTPS on my local dev server, the login endpoint started returning 403 with an empty body. The test and production environments were fine, and no business code had changed. Read-only pages worked perfectly; only form-submission requests failed.",[315,13610,13611,13613,13614,13617],{},[49,13612,9681],{},": A full investigation path for \"request headers passed through a proxy\" (controlled variables plus bisecting with curl), a correction of the common misunderstanding about the ",[100,13615,13616],{},"changeOrigin"," option, and a checklist for what to verify after enabling HTTPS in dev.",[58,13619,13621],{"id":13620},"_1-where-it-started-whatsapp-embedded-signup","1. Where It Started: WhatsApp Embedded Signup",[17,13623,13624,13625,13628,13629,13632],{},"I had been integrating the WhatsApp channel into an admin console. Meta provides a flow for the WhatsApp Business Platform called ",[49,13626,13627],{},"Embedded Signup",": the merchant never leaves our page. They click a button, a Facebook JS SDK popup walks them through authorization, the frontend receives a temporary code and hands it to the backend to exchange for a token, and the ",[49,13630,13631],{},"WABA"," (WhatsApp Business Account) is linked.",[17,13634,13635,13636,13639,13640,13643,13644,1312],{},"The flow has one hard prerequisite: ",[49,13637,13638],{},"Facebook Login requires an HTTPS origin",". That's a non-issue in production, which is HTTPS anyway. The problem shows up during local integration: ",[100,13641,13642],{},"npm run dev"," serves ",[100,13645,13646],{},"http:\u002F\u002Flocalhost:5173",[17,13648,13649,13650,13653],{},"Local integration came with a second requirement. The Embedded Signup authorization callback endpoint needed to point at my local Python service (FastAPI, running on ",[100,13651,13652],{},"127.0.0.1:8000",") so I could debug it, while every other endpoint on the page (login, session, and so on) still had to go to the test environment. Two streams of traffic, routed to two places.",[58,13655,13657],{"id":13656},"_2-the-plan-self-signed-https-same-origin-proxy-routing","2. The Plan: Self-Signed HTTPS + Same-Origin Proxy Routing",[17,13659,13660],{},"Two changes (vite 5.4).",[17,13662,13663,13670,13671,13674],{},[49,13664,13665,13666,13669],{},"(1) Enable ",[100,13667,13668],{},"@vitejs\u002Fplugin-basic-ssl"," in dev."," This official plugin generates a ",[49,13672,13673],{},"self-signed certificate"," at startup (signed by itself and trusted by no CA, which is where the browser's \"Not secure\" warning in the address bar comes from) so the dev server can serve over HTTPS.",[17,13676,13677,13680,13681,13684,13685,13688],{},[49,13678,13679],{},"(2) Empty the API baseURL and route through a same-origin proxy."," The axios instance takes its baseURL from an environment variable (",[100,13682,13683],{},"axios.create({ baseURL: import.meta.env.VITE_API_BASE_URL })","). Leave it empty in dev and requests become relative paths sent to the page's own origin, where vite's ",[100,13686,13687],{},"server.proxy"," routes them:",[191,13690,13692],{"className":6559,"code":13691,"language":6561,"meta":15,"style":15},"# .env.development\n# Empty → axios uses relative paths → requests go to the page's own origin, where vite's server.proxy takes over routing\nVITE_API_BASE_URL=\n",[100,13693,13694,13699,13704],{"__ignoreMap":15},[199,13695,13696],{"class":201,"line":202},[199,13697,13698],{},"# .env.development\n",[199,13700,13701],{"class":201,"line":25},[199,13702,13703],{},"# Empty → axios uses relative paths → requests go to the page's own origin, where vite's server.proxy takes over routing\n",[199,13705,13706],{"class":201,"line":213},[199,13707,13708],{},"VITE_API_BASE_URL=\n",[17,13710,13711,13712,13715],{},"Here is the complete ",[100,13713,13714],{},"vite.config.ts"," as it stood at the end of that day (all structure relevant to this post is kept, business plugins are omitted, and it can be pasted as-is for comparison):",[191,13717,13719],{"className":2427,"code":13718,"language":2429,"meta":15,"style":15},"\u002F\u002F vite.config.ts\nimport { defineConfig, loadEnv, type ConfigEnv, type UserConfig } from \"vite\";\nimport basicSsl from \"@vitejs\u002Fplugin-basic-ssl\";\n\nexport default defineConfig(({ mode }: ConfigEnv): UserConfig => {\n  \u002F\u002F Load .env.development \u002F .env.test \u002F ... by mode (this post only relies on VITE_API_BASE_URL being empty)\n  const env = loadEnv(mode, process.cwd());\n\n  return {\n    server: {\n      port: 5173,\n      proxy: {\n        \u002F\u002F Authorization callback → local Python. Must come before \u002Fsvc: vite matches prefixes in declaration order, first hit wins\n        \"\u002Fsvc\u002Fwhatsapp\u002Fembedded-signup\": { target: \"http:\u002F\u002F127.0.0.1:8000\", changeOrigin: true },\n        \u002F\u002F Everything else → test environment\n        \"\u002Fsvc\": { target: \"https:\u002F\u002Fdev-gateway.example.com\", changeOrigin: true },\n        \"\u002Fapi\": { target: \"https:\u002F\u002Fdev-gateway.example.com\", changeOrigin: true }\n      }\n    },\n    \u002F\u002F Self-signed HTTPS in development mode only; production builds don't include this plugin\n    plugins: mode === \"development\" ? [basicSsl()] : []\n  };\n});\n",[100,13720,13721,13726,13751,13765,13769,13804,13809,13829,13833,13839,13844,13854,13859,13864,13883,13888,13904,13919,13924,13929,13934,13960,13964],{"__ignoreMap":15},[199,13722,13723],{"class":201,"line":202},[199,13724,13725],{"class":2468},"\u002F\u002F vite.config.ts\n",[199,13727,13728,13730,13733,13736,13739,13741,13744,13746,13749],{"class":201,"line":25},[199,13729,11152],{"class":2436},[199,13731,13732],{"class":1629}," { defineConfig, loadEnv, ",[199,13734,13735],{"class":2436},"type",[199,13737,13738],{"class":1629}," ConfigEnv, ",[199,13740,13735],{"class":2436},[199,13742,13743],{"class":1629}," UserConfig } ",[199,13745,11158],{"class":2436},[199,13747,13748],{"class":1633}," \"vite\"",[199,13750,3703],{"class":1629},[199,13752,13753,13755,13758,13760,13763],{"class":201,"line":213},[199,13754,11152],{"class":2436},[199,13756,13757],{"class":1629}," basicSsl ",[199,13759,11158],{"class":2436},[199,13761,13762],{"class":1633}," \"@vitejs\u002Fplugin-basic-ssl\"",[199,13764,3703],{"class":1629},[199,13766,13767],{"class":201,"line":219},[199,13768,461],{"emptyLinePlaceholder":30},[199,13770,13771,13773,13776,13779,13782,13785,13788,13790,13793,13795,13797,13800,13802],{"class":201,"line":225},[199,13772,5644],{"class":2436},[199,13774,13775],{"class":2436}," default",[199,13777,13778],{"class":1619}," defineConfig",[199,13780,13781],{"class":1629},"(({ ",[199,13783,13784],{"class":3659},"mode",[199,13786,13787],{"class":1629}," }",[199,13789,346],{"class":2436},[199,13791,13792],{"class":1619}," ConfigEnv",[199,13794,5665],{"class":1629},[199,13796,346],{"class":2436},[199,13798,13799],{"class":1619}," UserConfig",[199,13801,3663],{"class":2436},[199,13803,3666],{"class":1629},[199,13805,13806],{"class":201,"line":231},[199,13807,13808],{"class":2468},"  \u002F\u002F Load .env.development \u002F .env.test \u002F ... by mode (this post only relies on VITE_API_BASE_URL being empty)\n",[199,13810,13811,13813,13816,13818,13821,13824,13827],{"class":201,"line":237},[199,13812,5697],{"class":2436},[199,13814,13815],{"class":3645}," env",[199,13817,3714],{"class":2436},[199,13819,13820],{"class":1619}," loadEnv",[199,13822,13823],{"class":1629},"(mode, process.",[199,13825,13826],{"class":1619},"cwd",[199,13828,11077],{"class":1629},[199,13830,13831],{"class":201,"line":243},[199,13832,461],{"emptyLinePlaceholder":30},[199,13834,13835,13837],{"class":201,"line":249},[199,13836,6018],{"class":2436},[199,13838,3666],{"class":1629},[199,13840,13841],{"class":201,"line":255},[199,13842,13843],{"class":1629},"    server: {\n",[199,13845,13846,13849,13852],{"class":201,"line":261},[199,13847,13848],{"class":1629},"      port: ",[199,13850,13851],{"class":3645},"5173",[199,13853,6123],{"class":1629},[199,13855,13856],{"class":201,"line":267},[199,13857,13858],{"class":1629},"      proxy: {\n",[199,13860,13861],{"class":201,"line":273},[199,13862,13863],{"class":2468},"        \u002F\u002F Authorization callback → local Python. Must come before \u002Fsvc: vite matches prefixes in declaration order, first hit wins\n",[199,13865,13866,13869,13872,13875,13878,13880],{"class":201,"line":279},[199,13867,13868],{"class":1633},"        \"\u002Fsvc\u002Fwhatsapp\u002Fembedded-signup\"",[199,13870,13871],{"class":1629},": { target: ",[199,13873,13874],{"class":1633},"\"http:\u002F\u002F127.0.0.1:8000\"",[199,13876,13877],{"class":1629},", changeOrigin: ",[199,13879,3798],{"class":3645},[199,13881,13882],{"class":1629}," },\n",[199,13884,13885],{"class":201,"line":285},[199,13886,13887],{"class":2468},"        \u002F\u002F Everything else → test environment\n",[199,13889,13890,13893,13895,13898,13900,13902],{"class":201,"line":651},[199,13891,13892],{"class":1633},"        \"\u002Fsvc\"",[199,13894,13871],{"class":1629},[199,13896,13897],{"class":1633},"\"https:\u002F\u002Fdev-gateway.example.com\"",[199,13899,13877],{"class":1629},[199,13901,3798],{"class":3645},[199,13903,13882],{"class":1629},[199,13905,13906,13909,13911,13913,13915,13917],{"class":201,"line":970},[199,13907,13908],{"class":1633},"        \"\u002Fapi\"",[199,13910,13871],{"class":1629},[199,13912,13897],{"class":1633},[199,13914,13877],{"class":1629},[199,13916,3798],{"class":3645},[199,13918,3801],{"class":1629},[199,13920,13921],{"class":201,"line":976},[199,13922,13923],{"class":1629},"      }\n",[199,13925,13926],{"class":201,"line":982},[199,13927,13928],{"class":1629},"    },\n",[199,13930,13931],{"class":201,"line":988},[199,13932,13933],{"class":2468},"    \u002F\u002F Self-signed HTTPS in development mode only; production builds don't include this plugin\n",[199,13935,13936,13939,13941,13944,13946,13949,13952,13955,13957],{"class":201,"line":994},[199,13937,13938],{"class":1629},"    plugins: mode ",[199,13940,12126],{"class":2436},[199,13942,13943],{"class":1633}," \"development\"",[199,13945,5736],{"class":2436},[199,13947,13948],{"class":1629}," [",[199,13950,13951],{"class":1619},"basicSsl",[199,13953,13954],{"class":1629},"()] ",[199,13956,346],{"class":2436},[199,13958,13959],{"class":1629}," []\n",[199,13961,13962],{"class":201,"line":2371},[199,13963,11130],{"class":1629},[199,13965,13966],{"class":201,"line":2377},[199,13967,6128],{"class":1629},[191,13969,13971],{"className":193,"code":13970,"language":195,"meta":15,"style":15},"flowchart LR\n    B[\"Browser\u003Cbr>https:\u002F\u002Flocalhost:5173\"] --> V[\"vite dev server\u003Cbr>server.proxy\"]\n    V -- \"\u002Fsvc\u002Fwhatsapp\u002Fembedded-signup\" --> P[\"Local Python\u003Cbr>http:\u002F\u002F127.0.0.1:8000\"]\n    V -- \"\u002Fapi, the rest of \u002Fsvc\" --> T[\"Test environment gateway\u003Cbr>https:\u002F\u002Fdev-gateway.example.com\"]\n    style V fill:#E1EDFC,stroke:#3B6FD4,stroke-width:2px\n",[100,13972,13973,13977,13982,13987,13992],{"__ignoreMap":15},[199,13974,13975],{"class":201,"line":202},[199,13976,1201],{},[199,13978,13979],{"class":201,"line":25},[199,13980,13981],{},"    B[\"Browser\u003Cbr>https:\u002F\u002Flocalhost:5173\"] --> V[\"vite dev server\u003Cbr>server.proxy\"]\n",[199,13983,13984],{"class":201,"line":213},[199,13985,13986],{},"    V -- \"\u002Fsvc\u002Fwhatsapp\u002Fembedded-signup\" --> P[\"Local Python\u003Cbr>http:\u002F\u002F127.0.0.1:8000\"]\n",[199,13988,13989],{"class":201,"line":219},[199,13990,13991],{},"    V -- \"\u002Fapi, the rest of \u002Fsvc\" --> T[\"Test environment gateway\u003Cbr>https:\u002F\u002Fdev-gateway.example.com\"]\n",[199,13993,13994],{"class":201,"line":225},[199,13995,13996],{},"    style V fill:#E1EDFC,stroke:#3B6FD4,stroke-width:2px\n",[17,13998,13999],{},"The node with the darker border is the key component of this post: the proxy layer built into the vite dev server. The two streams of traffic split here, and this is also the layer where the problem later occurred.",[17,14001,14002,14003,14006,14007,14010,14011,14014],{},"Why a same-origin proxy rather than letting the browser talk to both backends directly? Hitting the local Python service directly means an HTTPS page calling an ",[100,14004,14005],{},"http:\u002F\u002F"," endpoint, which lands in ",[49,14008,14009],{},"mixed content"," territory. Mainstream browsers do exempt loopback addresses, but their behavior differs. Hitting the test environment directly means depending on its ",[49,14012,14013],{},"CORS"," configuration. Put everything behind a same-origin proxy and, from the browser's point of view, every request is same-origin. Both problems go away at once.",[17,14016,14017],{},"On the day I finished the setup, the WhatsApp authorization flow worked end to end.",[58,14019,14021],{"id":14020},"_3-the-next-day-login-returns-403","3. The Next Day: Login Returns 403",[17,14023,14024],{},"The next day I started the local server, tried to log in again, and the endpoint misbehaved:",[348,14026,14027,14033,14040],{},[315,14028,14029,14030],{},"Request URL: ",[100,14031,14032],{},"https:\u002F\u002Flocalhost:5173\u002Fapi\u002Fauth\u002Flogin",[315,14034,14035,14036,14039],{},"Status: ",[49,14037,14038],{},"403 Forbidden",", empty response body",[315,14041,14042,14043],{},"The response headers included ",[100,14044,14045],{},"Access-Control-Allow-Origin: *",[17,14047,14048],{},"Three things were odd: the test and production environments were fine, no business code had changed, and everything had worked locally the day before. Had I opened a page that only issues GET requests, I would have noticed one more detail: the page loads perfectly, and only POST requests such as login return 403 (section 5 explains why).",[17,14050,14051],{},"There were three candidate causes: vite blocking the request locally, the test environment gateway blocking it, or the proxy configuration itself being wrong.",[58,14053,14055],{"id":14054},"_4-investigation-control-the-variables-until-the-trigger-is-one-value-of-one-header","4. Investigation: Control the Variables Until the Trigger Is \"One Value of One Header\"",[17,14057,14058],{},"A request in the browser has too many variables, so I used curl to take the chain apart and test each piece on its own. Step one, call the test environment upstream directly with curl:",[191,14060,14062],{"className":5351,"code":14061,"language":5353,"meta":15,"style":15},"curl -sk -i --noproxy \"*\" -X POST \"https:\u002F\u002Fdev-gateway.example.com\u002Fapi\u002Fauth\u002Flogin\" \\\n  -H \"Content-Type: application\u002Fjson\" -d \"{}\"\n",[100,14063,14064,14092],{"__ignoreMap":15},[199,14065,14066,14068,14071,14074,14077,14080,14083,14086,14089],{"class":201,"line":202},[199,14067,5365],{"class":1619},[199,14069,14070],{"class":3645}," -sk",[199,14072,14073],{"class":3645}," -i",[199,14075,14076],{"class":3645}," --noproxy",[199,14078,14079],{"class":1633}," \"*\"",[199,14081,14082],{"class":3645}," -X",[199,14084,14085],{"class":1633}," POST",[199,14087,14088],{"class":1633}," \"https:\u002F\u002Fdev-gateway.example.com\u002Fapi\u002Fauth\u002Flogin\"",[199,14090,14091],{"class":3645}," \\\n",[199,14093,14094,14097,14100,14103],{"class":201,"line":25},[199,14095,14096],{"class":3645},"  -H",[199,14098,14099],{"class":1633}," \"Content-Type: application\u002Fjson\"",[199,14101,14102],{"class":3645}," -d",[199,14104,14105],{"class":1633}," \"{}\"\n",[17,14107,14108,14109,14112],{},"It returned 200 plus a business error, \"email must not be empty\". ",[49,14110,14111],{},"The upstream service itself was healthy","; the problem was not on the service side.",[43,14114,14115],{},[17,14116,14117,14120,14121,14124,14125,14128,14129,14132,14133,14136],{},[49,14118,14119],{},"Side note: a proxy detour."," My first curl request didn't include ",[100,14122,14123],{},"--noproxy",", and the first line of output contained ",[100,14126,14127],{},"HTTP\u002F1.1 200 Connection established",". That is the reply from the proxy tool on my machine when it sets up a ",[49,14130,14131],{},"CONNECT tunnel",", which means curl was actually going out through the system proxy. vite's forwarding, on the other hand, is a Node process connecting straight to the upstream, so the two take different network paths. To rule this variable out, I cross-checked both paths, \"through the system proxy\" and \"forced direct\": ",[49,14134,14135],{},"with the same combination of request headers, both paths produced identical results",". That eliminated the network path as a variable, and the rest of this post shows only the direct-connection results.",[17,14138,14139],{},"The only real variable left was the request headers. I added the headers a browser sends to the curl command one at a time and quickly narrowed it down to Origin, then bisected on its value:",[105,14141,14142,14151],{},[108,14143,14144],{},[111,14145,14146,14149],{},[114,14147,14148],{},"Origin header added",[114,14150,6250],{},[121,14152,14153,14161,14170,14183,14193],{},[111,14154,14155,14158],{},[126,14156,14157],{},"No Origin",[126,14159,14160],{},"200",[111,14162,14163,14168],{},[126,14164,14165],{},[100,14166,14167],{},"Origin: http:\u002F\u002Flocalhost:5173",[126,14169,14160],{},[111,14171,14172,14179],{},[126,14173,14174],{},[49,14175,14176],{},[100,14177,14178],{},"Origin: https:\u002F\u002Flocalhost:5173",[126,14180,14181],{},[49,14182,4767],{},[111,14184,14185,14191],{},[126,14186,14187,14190],{},[100,14188,14189],{},"Origin: https:\u002F\u002Fapp.example.com"," (the real domain)",[126,14192,14160],{},[111,14194,14195,14201],{},[126,14196,14197,14198],{},"No Origin, only ",[100,14199,14200],{},"Referer: https:\u002F\u002Flocalhost:5173\u002F",[126,14202,14160],{},[17,14204,14205,14206,1630,14209,14212,14213,14216,14217,14220,14221,14224],{},"Of the five cases, exactly one returned 403. The trigger had been narrowed down to ",[49,14207,14208],{},"one value of one header",[100,14210,14211],{},"Origin: https:\u002F\u002Flocalhost",". The upstream is a ",[49,14214,14215],{},"reverse-proxy gateway",", and either it or the ",[49,14218,14219],{},"WAF"," (web application firewall) in front of it has a rule that treats an \"HTTPS + ",[100,14222,14223],{},"localhost","\" origin as the signature of a forged request and answers with a 403.",[17,14226,14227,14228,14231,14232,14235],{},"The response itself carries extra information. The semantics of 403 are \"the server ",[49,14229,14230],{},"understood"," the request but ",[49,14233,14234],{},"refuses"," to fulfil it\". It is not 405 (method not allowed) and not 500 (the server itself failed), which means the request arrived intact, was recognized, and was deliberately rejected by the server. An empty body is common WAF practice: reject without explaining, so that rule details aren't leaked to anyone probing. The combination \"403 + empty body\" is itself circumstantial evidence of a rule-based block.",[58,14237,14239],{"id":14238},"_5-root-cause-i-didnt-upgrade-the-protocol-i-changed-the-origin","5. Root Cause: I Didn't Upgrade the Protocol, I Changed the Origin",[17,14241,14242],{},"Three pieces of knowledge come together here.",[17,14244,14245,14248,14249,14252,14253,9838,14256,3933,14258,14261,14262,14265,14266,1312],{},[49,14246,14247],{},"1. An origin is a triple."," In the ",[49,14250,14251],{},"same-origin policy",", an origin is defined as ",[49,14254,14255],{},"scheme + host + port",[100,14257,13646],{},[100,14259,14260],{},"https:\u002F\u002Flocalhost:5173"," differ in scheme, so they are ",[49,14263,14264],{},"two different origins",". The real meaning of that one basicSsl line is therefore not \"add a certificate\" but ",[49,14267,14268],{},"\"move the entire local development environment to a new origin\"",[17,14270,14271,5431,14274,14277,14278,14281,14282,14285,14286,14289,14290,14293],{},[49,14272,14273],{},"2. The Origin request header is attached by the browser, and frontend code cannot change it.",[49,14275,14276],{},"Origin header"," is added to a request by the browser, and its value is the origin of the initiating page (just the triple, no path). Per the Fetch spec, cross-origin requests in CORS mode always carry it, and ",[49,14279,14280],{},"so does any request whose method is not GET or HEAD, same-origin or not",", as a signal for ",[49,14283,14284],{},"CSRF"," (cross-site request forgery) protection. It is a ",[49,14287,14288],{},"forbidden header",": frontend code can neither forge nor remove it. That explains what I saw in section 3. Same-origin GET requests don't carry Origin, so display-only pages are unaffected. The login POST always carries Origin, so it always trips the rule. It is also worth distinguishing the similar-looking ",[49,14291,14292],{},"Referer",": it carries the full URL (path included, trimmed according to Referrer-Policy) and is not the same thing as the Origin header.",[17,14295,14296,14299],{},[49,14297,14298],{},"3. vite's proxy passes Origin through when forwarding."," After receiving the browser's request, the proxy opens a new request to the upstream and copies the request headers over as they are (except Host, see the next section), including that Origin header I cannot touch.",[17,14301,14302],{},"The causal chain is now complete:",[191,14304,14306],{"className":193,"code":14305,"language":195,"meta":15,"style":15},"flowchart TD\n    A[\"basicSsl goes live\"] --> B[\"The page's origin changes:\u003Cbr>http:\u002F\u002Flocalhost:5173 → https:\u002F\u002Flocalhost:5173\"]\n    B --> C[\"The Origin header sent by the browser changes with it\"]\n    C --> D[\"vite proxy passes Origin through to the test environment gateway unchanged\"]\n    D --> E[\"A WAF rule matches:\u003Cbr>HTTPS + localhost is treated as a forged origin\"]\n    E --> F[\"403 (empty body)\"]\n    style F fill:#F5E6E6,stroke:#B85C5C,color:#8A3A3A\n    style B fill:#E1EDFC,stroke:#3B6FD4,stroke-width:2px\n",[100,14307,14308,14312,14317,14322,14327,14332,14337,14342],{"__ignoreMap":15},[199,14309,14310],{"class":201,"line":202},[199,14311,205],{},[199,14313,14314],{"class":201,"line":25},[199,14315,14316],{},"    A[\"basicSsl goes live\"] --> B[\"The page's origin changes:\u003Cbr>http:\u002F\u002Flocalhost:5173 → https:\u002F\u002Flocalhost:5173\"]\n",[199,14318,14319],{"class":201,"line":213},[199,14320,14321],{},"    B --> C[\"The Origin header sent by the browser changes with it\"]\n",[199,14323,14324],{"class":201,"line":219},[199,14325,14326],{},"    C --> D[\"vite proxy passes Origin through to the test environment gateway unchanged\"]\n",[199,14328,14329],{"class":201,"line":225},[199,14330,14331],{},"    D --> E[\"A WAF rule matches:\u003Cbr>HTTPS + localhost is treated as a forged origin\"]\n",[199,14333,14334],{"class":201,"line":231},[199,14335,14336],{},"    E --> F[\"403 (empty body)\"]\n",[199,14338,14339],{"class":201,"line":237},[199,14340,14341],{},"    style F fill:#F5E6E6,stroke:#B85C5C,color:#8A3A3A\n",[199,14343,14344],{"class":201,"line":243},[199,14345,14346],{},"    style B fill:#E1EDFC,stroke:#3B6FD4,stroke-width:2px\n",[17,14348,14349,14350,14353],{},"What makes this chain hard is that ",[49,14351,14352],{},"every link, viewed on its own, is behaving exactly as expected",". The plugin works correctly, the browser follows the spec, the proxy forwards faithfully, and the WAF blocks according to its rules. The final 403 only appears once all of them are stacked together. That is why this class of problem is hard to track down: no single link is \"broken\".",[17,14355,14356],{},"It also explains every qualifier on the failure. In the test and production environments the Origin is a real domain, which doesn't match the rule. The WhatsApp integration the day before went through the proxy rule for the local Python service and never touched this gateway. So the failure appeared only locally, only after HTTPS was enabled, and only for write requests sent to the test environment gateway.",[58,14358,14360],{"id":14359},"_6-one-level-deeper-how-vites-proxy-actually-works","6. One Level Deeper: How vite's Proxy Actually Works",[17,14362,14363,14366,14367,14369,14370,14373,14374,14377,14378,14381,14382,14385,14386,14389],{},[49,14364,14365],{},"What the dev server really is."," The vite dev server started by ",[100,14368,13642],{}," is a Node HTTP server that does three things: it compiles and serves source modules on demand (native ESM plus esbuild transforms), it pushes ",[49,14371,14372],{},"HMR"," (hot module replacement) updates over WebSocket, and it mounts a ",[49,14375,14376],{},"reverse proxy"," middleware. A reverse proxy accepts requests on behalf of the ",[49,14379,14380],{},"server"," and forwards them to the real backend, without the client being aware of it. A ",[49,14383,14384],{},"forward proxy",", by contrast (such as that proxy tool on my machine), goes out on behalf of the ",[49,14387,14388],{},"client",". You can think of the vite dev server as a mini nginx built into your frontend tooling.",[17,14391,14392,14395,14396,14398,14399,14404,14405,14408,14409,5625,14412,14415],{},[49,14393,14394],{},"The proxy is built on node-http-proxy."," The vite docs state explicitly that ",[100,14397,13687],{}," uses the ",[6929,14400,14403],{"href":14401,"rel":14402},"https:\u002F\u002Fgithub.com\u002Fhttp-party\u002Fnode-http-proxy",[6933],"http-proxy"," library under the hood. It doesn't shuttle bytes at the TCP layer. It does an ",[49,14406,14407],{},"application-layer replay",": it uses Node's ",[100,14410,14411],{},"http",[100,14413,14414],{},"https"," modules to open a brand-new request to the target, copies over the original request's method, path, and headers, and writes the response back to the browser once it arrives. That act of \"copying the request headers\" is the mechanism by which Origin reaches the upstream.",[17,14417,14418,14421,14422,14425,14426,14428,14429,14432,14433,14436,14437,14439],{},[49,14419,14420],{},"Matching rules: declaration order + prefix."," vite matches the request path against prefixes one rule at a time, in the order the keys are written in the config object, and ",[49,14423,14424],{},"the first match wins"," (keys starting with ",[100,14427,10331],{}," are treated as regular expressions). This is exactly why ",[100,14430,14431],{},"\u002Fsvc\u002Fwhatsapp\u002Fembedded-signup"," has to be written before ",[100,14434,14435],{},"\u002Fsvc",". Reverse the order and the authorization callback matches the ",[100,14438,14435],{}," rule first and gets forwarded to the test environment.",[17,14441,14442,14448],{},[49,14443,14444,14445,14447],{},"The name ",[100,14446,13616],{}," invites misunderstanding."," It rewrites the Host header, not the Origin header. The two headers mean different things, and the difference deserves to be spelled out:",[1036,14450,14451,14456],{},[17,14452,14453],{},[49,14454,14455],{},"Origin header vs. Host header, once and for all",[348,14457,14458,14471,14485],{},[315,14459,14460,14462,14463,14466,14467,14470],{},[49,14461,14276],{},": generated by the browser. It represents the scheme + domain + port of ",[49,14464,14465],{},"the page that initiated the request"," and answers \"where does the request ",[49,14468,14469],{},"come from","\". JavaScript cannot change it, and it is used for CORS and CSRF protection.",[315,14472,14473,14476,14477,14480,14481,14484],{},[49,14474,14475],{},"Host header",": filled in by the client (or a proxy). It represents ",[49,14478,14479],{},"the target host this request is addressed to"," and answers \"where is the request ",[49,14482,14483],{},"going","\". Virtual hosts and gateway routing rely on it to dispatch requests.",[315,14486,14487,14489,14490,14493,14494,14497,14498,14501],{},[100,14488,13590],{}," rewrites only ",[49,14491,14492],{},"Host"," (from ",[100,14495,14496],{},"localhost:5173"," to the target's hostname; without that, many gateways that route by domain will simply return 404) and ",[49,14499,14500],{},"never touches Origin",". The \"origin\" in the name is used in the plain sense of \"where the request originates\", and it happens to collide with the Origin of the same-origin policy. It is a historical naming leftover and shouldn't be read literally.",[17,14503,14504,14505,14507],{},"This was the easiest point to misjudge in the whole investigation: the config says ",[100,14506,13590],{},", yet the Origin header arrives at the upstream unchanged.",[17,14509,14510,14516,14517,14520,14521,14524,14525,14528,14529,14532],{},[49,14511,4203,14512,14515],{},[100,14513,14514],{},"configure"," hook exposes the underlying instance."," On every proxy rule, vite offers a ",[100,14518,14519],{},"configure(proxy, options)"," hook that hands you the http-proxy instance so you can listen to its lifecycle events. Among them, the ",[100,14522,14523],{},"proxyReq"," event fires ",[49,14526,14527],{},"just before the new request to the upstream is sent",", and its callback receives an ",[100,14530,14531],{},"http.ClientRequest",". This is the last chance to modify the outgoing request.",[58,14534,14536],{"id":14535},"_7-the-fix-remove-the-origin-header-before-forwarding","7. The Fix: Remove the Origin Header Before Forwarding",[17,14538,14539],{},"At this point the fix is clear. The minimal change is to remove the Origin header before forwarding.",[191,14541,14543],{"className":2427,"code":14542,"language":2429,"meta":15,"style":15},"import type { ProxyOptions } from \"vite\";\n\nconst stripOrigin: ProxyOptions[\"configure\"] = proxy => {\n  proxy.on(\"proxyReq\", proxyReq => proxyReq.removeHeader(\"origin\"));\n};\n\n\u002F\u002F In server.proxy, attach the hook to the two rules that target the test environment:\n\"\u002Fsvc\": { target: \"https:\u002F\u002Fdev-gateway.example.com\", changeOrigin: true, configure: stripOrigin },\n\"\u002Fapi\": { target: \"https:\u002F\u002Fdev-gateway.example.com\", changeOrigin: true, configure: stripOrigin },\n",[100,14544,14545,14560,14564,14594,14626,14630,14634,14639,14655],{"__ignoreMap":15},[199,14546,14547,14549,14551,14554,14556,14558],{"class":201,"line":202},[199,14548,11152],{"class":2436},[199,14550,9787],{"class":2436},[199,14552,14553],{"class":1629}," { ProxyOptions } ",[199,14555,11158],{"class":2436},[199,14557,13748],{"class":1633},[199,14559,3703],{"class":1629},[199,14561,14562],{"class":201,"line":25},[199,14563,461],{"emptyLinePlaceholder":30},[199,14565,14566,14568,14571,14573,14576,14579,14582,14585,14587,14590,14592],{"class":201,"line":213},[199,14567,5475],{"class":2436},[199,14569,14570],{"class":1619}," stripOrigin",[199,14572,346],{"class":2436},[199,14574,14575],{"class":1619}," ProxyOptions",[199,14577,14578],{"class":1629},"[",[199,14580,14581],{"class":1633},"\"configure\"",[199,14583,14584],{"class":1629},"] ",[199,14586,3697],{"class":2436},[199,14588,14589],{"class":3659}," proxy",[199,14591,3663],{"class":2436},[199,14593,3666],{"class":1629},[199,14595,14596,14599,14602,14604,14607,14609,14611,14613,14616,14619,14621,14624],{"class":201,"line":219},[199,14597,14598],{"class":1629},"  proxy.",[199,14600,14601],{"class":1619},"on",[199,14603,2458],{"class":1629},[199,14605,14606],{"class":1633},"\"proxyReq\"",[199,14608,2625],{"class":1629},[199,14610,14523],{"class":3659},[199,14612,3663],{"class":2436},[199,14614,14615],{"class":1629}," proxyReq.",[199,14617,14618],{"class":1619},"removeHeader",[199,14620,2458],{"class":1629},[199,14622,14623],{"class":1633},"\"origin\"",[199,14625,3779],{"class":1629},[199,14627,14628],{"class":201,"line":225},[199,14629,6036],{"class":1629},[199,14631,14632],{"class":201,"line":231},[199,14633,461],{"emptyLinePlaceholder":30},[199,14635,14636],{"class":201,"line":237},[199,14637,14638],{"class":2468},"\u002F\u002F In server.proxy, attach the hook to the two rules that target the test environment:\n",[199,14640,14641,14644,14646,14648,14650,14652],{"class":201,"line":243},[199,14642,14643],{"class":1633},"\"\u002Fsvc\"",[199,14645,13871],{"class":1629},[199,14647,13897],{"class":1633},[199,14649,13877],{"class":1629},[199,14651,3798],{"class":3645},[199,14653,14654],{"class":1629},", configure: stripOrigin },\n",[199,14656,14657,14660,14662,14664,14666,14668],{"class":201,"line":249},[199,14658,14659],{"class":1633},"\"\u002Fapi\"",[199,14661,13871],{"class":1629},[199,14663,13897],{"class":1633},[199,14665,13877],{"class":1629},[199,14667,3798],{"class":3645},[199,14669,14654],{"class":1629},[17,14671,14672,14673,14676,14677,14679],{},"Six lines changed in total (lowercase in ",[100,14674,14675],{},"removeHeader(\"origin\")"," is fine, since HTTP header names are case-insensitive). Restart the dev server, because changes to ",[100,14678,13714],{}," are not hot-reloaded, and login returns 200 again.",[17,14681,14682],{},"The request's journey before and after the fix is easiest to understand side by side:",[17,14684,14685],{},[49,14686,14687],{},"Before the fix (the failing path):",[191,14689,14691],{"className":193,"code":14690,"language":195,"meta":15,"style":15},"sequenceDiagram\n    participant B as Browser\u003Cbr>https:\u002F\u002Flocalhost:5173\n    participant V as vite proxy\n    participant G as Test environment gateway (WAF)\n    B->>V: POST \u002Fapi\u002Fauth\u002Flogin\u003Cbr>Origin: https:\u002F\u002Flocalhost:5173\n    Note over V: Application-layer replay: copies all request headers\u003Cbr>❌ Origin is carried along unchanged\n    V->>G: POST (Origin: https:\u002F\u002Flocalhost:5173)\n    G-->>V: 403, empty body\n    V-->>B: 403\n",[100,14692,14693,14697,14702,14707,14712,14717,14722,14727,14732],{"__ignoreMap":15},[199,14694,14695],{"class":201,"line":202},[199,14696,892],{},[199,14698,14699],{"class":201,"line":25},[199,14700,14701],{},"    participant B as Browser\u003Cbr>https:\u002F\u002Flocalhost:5173\n",[199,14703,14704],{"class":201,"line":213},[199,14705,14706],{},"    participant V as vite proxy\n",[199,14708,14709],{"class":201,"line":219},[199,14710,14711],{},"    participant G as Test environment gateway (WAF)\n",[199,14713,14714],{"class":201,"line":225},[199,14715,14716],{},"    B->>V: POST \u002Fapi\u002Fauth\u002Flogin\u003Cbr>Origin: https:\u002F\u002Flocalhost:5173\n",[199,14718,14719],{"class":201,"line":231},[199,14720,14721],{},"    Note over V: Application-layer replay: copies all request headers\u003Cbr>❌ Origin is carried along unchanged\n",[199,14723,14724],{"class":201,"line":237},[199,14725,14726],{},"    V->>G: POST (Origin: https:\u002F\u002Flocalhost:5173)\n",[199,14728,14729],{"class":201,"line":243},[199,14730,14731],{},"    G-->>V: 403, empty body\n",[199,14733,14734],{"class":201,"line":249},[199,14735,14736],{},"    V-->>B: 403\n",[17,14738,14739],{},[49,14740,14741],{},"After the fix:",[191,14743,14745],{"className":193,"code":14744,"language":195,"meta":15,"style":15},"sequenceDiagram\n    participant B as Browser\u003Cbr>https:\u002F\u002Flocalhost:5173\n    participant V as vite proxy\n    participant G as Test environment gateway (WAF)\n    B->>V: POST \u002Fapi\u002Fauth\u002Flogin\u003Cbr>Origin: https:\u002F\u002Flocalhost:5173\n    Note over V: In the proxyReq event\u003Cbr>✅ removeHeader(\"origin\")\n    V->>G: POST (no Origin header)\n    G-->>V: 200\n    V-->>B: 200\n",[100,14746,14747,14751,14755,14759,14763,14767,14772,14777,14782],{"__ignoreMap":15},[199,14748,14749],{"class":201,"line":202},[199,14750,892],{},[199,14752,14753],{"class":201,"line":25},[199,14754,14701],{},[199,14756,14757],{"class":201,"line":213},[199,14758,14706],{},[199,14760,14761],{"class":201,"line":219},[199,14762,14711],{},[199,14764,14765],{"class":201,"line":225},[199,14766,14716],{},[199,14768,14769],{"class":201,"line":231},[199,14770,14771],{},"    Note over V: In the proxyReq event\u003Cbr>✅ removeHeader(\"origin\")\n",[199,14773,14774],{"class":201,"line":237},[199,14775,14776],{},"    V->>G: POST (no Origin header)\n",[199,14778,14779],{"class":201,"line":243},[199,14780,14781],{},"    G-->>V: 200\n",[199,14783,14784],{"class":201,"line":249},[199,14785,14786],{},"    V-->>B: 200\n",[17,14788,14789,14790,14792],{},"The only difference between the two diagrams is in the vite proxy box. On the failing path it faithfully copies every request header, Origin included. After the fix it runs ",[100,14791,14675],{}," before forwarding. Not a single byte of the browser's request has changed. What changed is only the copy the proxy sends out.",[17,14794,14795,14798],{},[49,14796,14797],{},"Is it safe to remove the Origin header?"," This question needs clear boundaries, so here are three points:",[312,14800,14801,14807,14827],{},[315,14802,14803,14806],{},[49,14804,14805],{},"On the local dev path, nothing consumes this header in the first place."," Behind a same-origin proxy, the browser sees the request as same-origin and makes no security decision based on Origin (the CORS check never happens). The upstream's business authentication is token-based and doesn't read it either. On this path, removing the Origin header weakens no protection that is actually in effect.",[315,14808,14809,5248,14812,14814,14815,14818,14819,14821,14822,3933,14824,14826],{},[49,14810,14811],{},"The change does not affect the test or production environments.",[100,14813,13687],{}," is ",[49,14816,14817],{},"runtime behavior"," of the dev server, while ",[100,14820,10750],{}," produces nothing but static files. I searched the build output for ",[100,14823,14523],{},[100,14825,13652],{}," and found no matches. In production the browser talks to the backend directly, and cross-origin security is handled by the gateway's CORS configuration, which has nothing to do with this change.",[315,14828,14829,14832],{},[49,14830,14831],{},"⚠️ But don't treat this as a universal answer."," The Fetch spec makes every non-GET\u002FHEAD request carry Origin precisely to give servers a CSRF-defense signal, and some gateways and frameworks really do check write requests against an Origin allowlist. If your upstream relies on Origin for CSRF protection, removing it takes away a layer of defense. Confirm the upstream's authentication model before you remove it.",[17,14834,14835,14836,14838],{},"Why not adjust the rule on the gateway side instead? First, the gateway is outside what the frontend controls, and changing a rule there requires cross-team coordination. Second, \"a dev proxy shouldn't send a ",[100,14837,14223],{}," Origin to a public gateway\" holds up on its own merits. Removing it at the proxy layer is arguably the more expected behavior.",[58,14840,14842],{"id":14841},"_8-the-big-picture-one-line-of-code-three-environments-three-paths","8. The Big Picture: One Line of Code, Three Environments, Three Paths",[17,14844,14845,14846,14849,14850,14853,14854,14857,14858,14861],{},"The business code is a single line, ",[100,14847,14848],{},"axios.post(\"\u002Fapi\u002Fauth\u002Flogin\")",", yet it maps to completely different paths in different environments. The fork is an environment variable that is ",[49,14851,14852],{},"statically inlined"," at build time. vite replaces ",[100,14855,14856],{},"import.meta.env.VITE_*"," with string literals, and you can find plain text such as ",[100,14859,14860],{},"baseURL:\"https:\u002F\u002F...\""," in the build output:",[105,14863,14864,14882],{},[108,14865,14866],{},[111,14867,14868,14871,14876,14879],{},[114,14869,14870],{},"Environment",[114,14872,14873],{},[100,14874,14875],{},"VITE_API_BASE_URL",[114,14877,14878],{},"Actual path",[114,14880,14881],{},"Cross-origin approach",[121,14883,14884,14901,14917],{},[111,14885,14886,14889,14892,14898],{},[126,14887,14888],{},"Local dev",[126,14890,14891],{},"empty",[126,14893,14894,14895,14897],{},"Relative path → same origin ",[100,14896,14496],{}," → forwarded by vite proxy",[126,14899,14900],{},"Same-origin proxy (nothing is cross-origin)",[111,14902,14903,14906,14911,14914],{},[126,14904,14905],{},"Test",[126,14907,14908],{},[100,14909,14910],{},"https:\u002F\u002Fdev-gateway.example.com",[126,14912,14913],{},"Browser connects directly",[126,14915,14916],{},"CORS response headers",[111,14918,14919,14922,14927,14929],{},[126,14920,14921],{},"Production",[126,14923,14924],{},[100,14925,14926],{},"https:\u002F\u002Fapi.example.com",[126,14928,14913],{},[126,14930,14916],{},[17,14932,14933,14934,14936,14937,14940],{},"Now look back at the ",[100,14935,14045],{}," response header from section 3. It is the CORS configuration the gateway provides for the ",[49,14938,14939],{},"direct-connection scenario",". On the proxied local path, the browser never consumes it at any point. Its presence on the 403 response only shows that the gateway attaches this header to everything. It has nothing to do with the logic that decided to block the request.",[58,14942,14944],{"id":14943},"_9-retrospective","9. Retrospective",[312,14946,14947,14960,14968,14974],{},[315,14948,14949,14952,14953,5625,14956,14959],{},[49,14950,14951],{},"Putting HTTPS on dev isn't adding a certificate, it's changing the origin."," Every behavior keyed on origin changes with it: the Origin header, CORS, the ",[100,14954,14955],{},"Secure",[100,14957,14958],{},"SameSite"," cookie attributes, localStorage isolation. A change like this deserves to be treated as a \"migration\", not as a \"config tweak\".",[315,14961,14962,14967],{},[49,14963,14964,14966],{},[100,14965,13616],{}," doesn't change Origin. It changes Host."," When reading a config option, read its definition in the docs, not its name.",[315,14969,14970,14973],{},[49,14971,14972],{},"Controlling variables is the backbone of debugging."," Change one variable at a time (network path, request headers, header value) and four or five curl comparisons will narrow the trigger down to one value of one header. That is far more efficient than guessing item by item in the browser console.",[315,14975,14976,14979],{},[49,14977,14978],{},"Headers passed through a proxy are an invisible contract."," You think the proxy forwards \"your request\", but what it actually forwards is \"the request the browser assembled\". That request contains several headers the browser generates automatically and the frontend cannot modify, and the upstream may well be making decisions based on them.",[17,14981,14982],{},[49,14983,14984],{},"Appendix: checklist after enabling HTTPS on local dev",[348,14986,14988,14998,15008,15024,15039],{"className":14987},[6801],[315,14989,14991,14993,14994,14997],{"className":14990},[6805],[6807,14992],{"disabled":30,"type":6809}," Run every ",[49,14995,14996],{},"write endpoint"," (POST\u002FPUT\u002FDELETE) through the main flows such as login and form submission. They carry the Origin header whether same-origin or not, so focus on whether the proxy or the upstream gateway has any rule keyed on Origin",[315,14999,15001,15003,15004,15007],{"className":15000},[6805],[6807,15002],{"disabled":30,"type":6809}," localStorage \u002F sessionStorage \u002F IndexedDB are ",[49,15005,15006],{},"isolated by origin",": login state, drafts, and caches stored under the http origin are all unreadable under the https origin. This is expected behavior and doesn't need to be investigated as a bug",[315,15009,15011,15013,15014,15016,15017,15020,15021,15023],{"className":15010},[6805],[6807,15012],{"disabled":30,"type":6809}," Re-check cookie behavior: cookies with the ",[100,15015,14955],{}," attribute are only sent and received over HTTPS, and ",[100,15018,15019],{},"SameSite=None"," must be paired with ",[100,15022,14955],{},". Verify login state and session persistence once before and once after the scheme switch",[315,15025,15027,15029,15030,15032,15033,15035,15036,15038],{"className":15026},[6805],[6807,15028],{"disabled":30,"type":6809}," Use a packet capture tool, or log from the ",[100,15031,14523],{}," event, to verify that ",[100,15034,13616],{}," really rewrites ",[49,15037,14492],{}," to the target's hostname, and remember that it does not change Origin",[315,15040,15042,15044,15045,15050],{"className":15041},[6805],[6807,15043],{"disabled":30,"type":6809}," If the self-signed certificate isn't trusted by the browser, the page may open while the HMR WebSocket (wss) connection fails. Trust the certificate in the browser first, or switch to ",[6929,15046,15049],{"href":15047,"rel":15048},"https:\u002F\u002Fgithub.com\u002FFiloSottile\u002Fmkcert",[6933],"mkcert"," to generate a locally trusted certificate",[1042,15052,15053],{},"html .light .shiki span {color: var(--shiki-light);background: var(--shiki-light-bg);font-style: var(--shiki-light-font-style);font-weight: var(--shiki-light-font-weight);text-decoration: var(--shiki-light-text-decoration);}html.light .shiki span {color: var(--shiki-light);background: var(--shiki-light-bg);font-style: var(--shiki-light-font-style);font-weight: var(--shiki-light-font-weight);text-decoration: var(--shiki-light-text-decoration);}html .default .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html.dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html pre.shiki code .sCsY4, html code.shiki .sCsY4{--shiki-light:#6A737D;--shiki-default:#6A737D;--shiki-dark:#6A737D}html pre.shiki code .so5gQ, html code.shiki .so5gQ{--shiki-light:#D73A49;--shiki-default:#F97583;--shiki-dark:#F97583}html pre.shiki code .slsVL, html code.shiki .slsVL{--shiki-light:#24292E;--shiki-default:#E1E4E8;--shiki-dark:#E1E4E8}html pre.shiki code .sfrk1, html code.shiki .sfrk1{--shiki-light:#032F62;--shiki-default:#9ECBFF;--shiki-dark:#9ECBFF}html pre.shiki code .shcOC, html code.shiki .shcOC{--shiki-light:#6F42C1;--shiki-default:#B392F0;--shiki-dark:#B392F0}html pre.shiki code .sQHwn, html code.shiki .sQHwn{--shiki-light:#E36209;--shiki-default:#FFAB70;--shiki-dark:#FFAB70}html pre.shiki code .suiK_, html code.shiki .suiK_{--shiki-light:#005CC5;--shiki-default:#79B8FF;--shiki-dark:#79B8FF}",{"title":15,"searchDepth":25,"depth":25,"links":15055},[15056,15057,15058,15059,15060,15061,15062,15063,15064],{"id":13620,"depth":25,"text":13621},{"id":13656,"depth":25,"text":13657},{"id":14020,"depth":25,"text":14021},{"id":14054,"depth":25,"text":14055},{"id":14238,"depth":25,"text":14239},{"id":14359,"depth":25,"text":14360},{"id":14535,"depth":25,"text":14536},{"id":14841,"depth":25,"text":14842},{"id":14943,"depth":25,"text":14944},"2026-08-06","Enabling self-signed HTTPS on a local dev server changes the page's origin, so the Origin header changes too and trips a WAF rule in the test environment, returning 403. A controlled-variable investigation, a look inside vite's proxy, and a six-line fix.","\u002Farticles\u002Fvite-proxy-change-origin.svg",{},"\u002Farticles\u002Fvite-proxy-change-origin","14",{"title":13582,"description":15066},{"loc":15069},"articles\u002Fvite-proxy-change-origin",[7011,7012],"Xjb90E4mcRuKnozMev6uV-u0obQ7qveOWW6MQlF09to",{"id":15077,"title":15078,"body":15079,"date":15796,"description":15797,"extension":28,"head":27,"image":15798,"meta":15799,"navigation":30,"ogImage":27,"path":15800,"rating":219,"readingTime":15801,"robots":27,"schemaOrg":27,"seo":15802,"sitemap":15803,"stem":15804,"tags":15805,"__hash__":15806},"articles_en\u002Farticles\u002Fvue-component-library-npm.md","Turning Components Copy-Pasted Across 6 Projects into One npm Package",{"type":7,"value":15080,"toc":15784},[15081,15089,15093,15113,15120,15124,15131,15153,15164,15184,15189,15193,15207,15218,15230,15255,15275,15284,15288,15315,15330,15388,15401,15405,15418,15430,15464,15472,15476,15486,15500,15522,15548,15563,15567,15576,15649,15655,15659,15662,15687,15705,15709,15728,15737,15740,15744,15747,15776,15782],[43,15082,15083],{},[17,15084,15085,15086],{},"A hands-on retrospective on taking components that had been copy-pasted across 6 H5 projects, migrating them to Vue 3 + Vant 4, and packaging them as an npm package. ",[49,15087,15088],{},"The conclusion up front: the component code is simple. The hard part was never the components, but the layer of \"engineering contract\" that surrounds them.",[58,15090,15092],{"id":15091},"opening-the-components-are-simple-and-they-are-not-the-hard-part","Opening: the components are simple, and they are not the hard part",[17,15094,15095,15096,15099,15100,2625,15103,9856,15105,15108,15109,15112],{},"When I took this on, I also assumed it was grunt work. Across a dozen or so H5 projects in the ",[100,15097,15098],{},"acme-*"," family, components like ",[100,15101,15102],{},"cascader",[100,15104,4103],{},[100,15106,15107],{},"dialog"," had been copy-pasted several times over. Copy them into a new repo, run ",[100,15110,15111],{},"npm publish",", and call it a day, right?",[17,15114,15115,15116,15119],{},"Only once I started did I realize: ",[49,15117,15118],{},"each component, taken alone, really is simple (a thin wrapper around Vant plus some styling), but \"turning it into a package that other people can safely depend on\" hides a pile of pitfalls the compiler will never report for you."," Below are the ones I think are most worth explaining in depth.",[58,15121,15123],{"id":15122},"_1-what-can-be-extracted-and-what-cant-look-at-coupling-not-complexity","1. What can be extracted and what can't: look at coupling, not complexity",[17,15125,15126,15127,15130],{},"My first instinct was \"extract the simple ones first\". Wrong. What decides whether a component can be extracted cleanly is its ",[49,15128,15129],{},"dependency graph",", not its line count.",[348,15132,15133,15141],{},[315,15134,15135,15137,15138,1312],{},[100,15136,15102],{}," is 260 lines with complicated logic, but it depends only on Vant → ",[49,15139,15140],{},"easy to extract",[315,15142,15143,15146,15147,6275,15150,1312],{},[100,15144,15145],{},"city-search"," is a simple search box, yet it does ",[100,15148,15149],{},"import { queryCityList } from '@\u002Fapi'",[49,15151,15152],{},"hard to extract",[17,15154,15155,15156,15159,15160,15163],{},"A library component cannot assume the host has some ",[100,15157,15158],{},"@\u002Fapi",". The fix is ",[49,15161,15162],{},"dependency inversion",": push \"fetching the data\" out of the component. There are three ways to do it, and the trade-off is \"who owns loading \u002F caching \u002F error handling\":",[191,15165,15167],{"className":6559,"code":15166,"language":6561,"meta":15,"style":15},"data prop   : host fetches data and passes it in        → purest component, most work for the host\nfetcher     : pass the fetch function in as a prop      → flexible, but couples the call timing\nemit event  : component emits @search, host fills data  → decoupled interaction, usually the best\n",[100,15168,15169,15174,15179],{"__ignoreMap":15},[199,15170,15171],{"class":201,"line":202},[199,15172,15173],{},"data prop   : host fetches data and passes it in        → purest component, most work for the host\n",[199,15175,15176],{"class":201,"line":25},[199,15177,15178],{},"fetcher     : pass the fetch function in as a prop      → flexible, but couples the call timing\n",[199,15180,15181],{"class":201,"line":213},[199,15182,15183],{},"emit event  : component emits @search, host fills data  → decoupled interaction, usually the best\n",[424,15185,15186],{},[17,15187,15188],{},"Takeaway: to judge \"can this become a library\", draw the dependency graph first. Visual complexity will fool you; coupling won't.",[58,15190,15192],{"id":15191},"_2-a-pitfall-that-compiles-but-doesnt-run","2. A pitfall that \"compiles but doesn't run\"",[17,15194,15195,15196,15202,15203,15206],{},"This was the most valuable lesson of the whole exercise. Vant 4 ",[49,15197,15198,15199],{},"removed ",[100,15200,15201],{},"DatetimePicker"," (it was split into ",[100,15204,15205],{},"DatePicker","). Without thinking, I wrote:",[191,15208,15212],{"className":15209,"code":15210,"language":15211,"meta":15,"style":15},"language-javascript shiki shiki-themes github-light github-dark github-dark","import { DatetimePicker } from 'vant'   \u002F\u002F in Vant 4, this is undefined\n","javascript",[100,15213,15214],{"__ignoreMap":15},[199,15215,15216],{"class":201,"line":202},[199,15217,15210],{},[17,15219,15220,5248,15222,15225,15226,15229],{},[100,15221,10750],{},[49,15223,15224],{},"went green",". TypeScript didn't complain, esbuild didn't complain, nothing said a word. Only when the component rendered in the browser did a ",[100,15227,15228],{},"[Vue warn]: Failed to resolve component"," show up.",[17,15231,15232,15233,15236,15237,15240,15241,15244,15245,11817,15248,15250,15251,15254],{},"Why can't the build catch it? Because ",[49,15234,15235],{},"Vue resolves components at runtime",". The template ",[100,15238,15239],{},"\u003Cvan-datetime-picker>"," is compiled into ",[100,15242,15243],{},"resolveComponent(\"van-datetime-picker\")",", a call that ",[49,15246,15247],{},"looks up the component registry by string name at runtime",[100,15249,11152],{}," yielding ",[100,15252,15253],{},"undefined"," is perfectly legal as far as JS is concerned (you have merely registered a local component whose value is undefined). The warning only appears when rendering actually happens and the lookup fails.",[191,15256,15258],{"className":15209,"code":15257,"language":15211,"meta":15,"style":15},"\u002F\u002F What the compiled template looks like (simplified)\nconst _component_van_datetime_picker = resolveComponent(\"van-datetime-picker\")\n\u002F\u002F import is undefined → not found in the registry → warns only at runtime, silent at compile time\n",[100,15259,15260,15265,15270],{"__ignoreMap":15},[199,15261,15262],{"class":201,"line":202},[199,15263,15264],{},"\u002F\u002F What the compiled template looks like (simplified)\n",[199,15266,15267],{"class":201,"line":25},[199,15268,15269],{},"const _component_van_datetime_picker = resolveComponent(\"van-datetime-picker\")\n",[199,15271,15272],{"class":201,"line":213},[199,15273,15274],{},"\u002F\u002F import is undefined → not found in the registry → warns only at runtime, silent at compile time\n",[424,15276,15277],{},[17,15278,15279,15280,15283],{},"Takeaway: ",[49,15281,15282],{},"\"the build is green\" is the weakest guarantee there is."," For a major framework upgrade you must read the migration guide, check for removed \u002F renamed APIs, and use \"export-name existence checks + real rendering\" to cover the blind spots the compiler can't.",[58,15285,15287],{"id":15286},"_3-migrating-v-model-one-component-is-both-consumer-and-provider","3. Migrating v-model: one component is both consumer and provider",[17,15289,15290,15291,7048,15293,6275,15296,7048,15299,7787,15302,6275,15305,15308,15309,2797,15312,1312],{},"The v-model contract changed completely from Vue 2 to 3: ",[100,15292,6428],{},[100,15294,15295],{},"@input",[100,15297,15298],{},"modelValue",[100,15300,15301],{},"update:modelValue",[100,15303,15304],{},".sync",[100,15306,15307],{},"v-model:x",". On top of that, Vant 4 changed Popup\u002FDialog visibility from ",[100,15310,15311],{},"v-model",[100,15313,15314],{},"v-model:show",[17,15316,15317,15318,15321,15322,15325,15326,15329],{},"The key point: our ",[100,15319,15320],{},"Dialog"," component is, ",[49,15323,15324],{},"on the inside",", a v-model consumer of van-dialog, and ",[49,15327,15328],{},"on the outside",", a v-model provider to the host. Both ends have to change together, with a watch in the middle passing values through in both directions:",[191,15331,15333],{"className":15209,"code":15332,"language":15211,"meta":15,"style":15},"\u003Cvan-dialog v-model:show=\"isShow\">…\u003C\u002Fvan-dialog>\n\u003Cscript>\nexport default {\n  props: { modelValue: { type: Boolean, default: false } },\n  emits: ['update:modelValue'],\n  watch: {\n    modelValue(v){ this.isShow = v },                                  \u002F\u002F host → internal\n    isShow(v){ if (v !== this.modelValue) this.$emit('update:modelValue', v) }, \u002F\u002F internal → host\n  },\n}\n\u003C\u002Fscript>\n",[100,15334,15335,15340,15345,15350,15355,15360,15365,15370,15375,15379,15383],{"__ignoreMap":15},[199,15336,15337],{"class":201,"line":202},[199,15338,15339],{},"\u003Cvan-dialog v-model:show=\"isShow\">…\u003C\u002Fvan-dialog>\n",[199,15341,15342],{"class":201,"line":25},[199,15343,15344],{},"\u003Cscript>\n",[199,15346,15347],{"class":201,"line":213},[199,15348,15349],{},"export default {\n",[199,15351,15352],{"class":201,"line":219},[199,15353,15354],{},"  props: { modelValue: { type: Boolean, default: false } },\n",[199,15356,15357],{"class":201,"line":225},[199,15358,15359],{},"  emits: ['update:modelValue'],\n",[199,15361,15362],{"class":201,"line":231},[199,15363,15364],{},"  watch: {\n",[199,15366,15367],{"class":201,"line":237},[199,15368,15369],{},"    modelValue(v){ this.isShow = v },                                  \u002F\u002F host → internal\n",[199,15371,15372],{"class":201,"line":243},[199,15373,15374],{},"    isShow(v){ if (v !== this.modelValue) this.$emit('update:modelValue', v) }, \u002F\u002F internal → host\n",[199,15376,15377],{"class":201,"line":249},[199,15378,3784],{},[199,15380,15381],{"class":201,"line":255},[199,15382,2502],{},[199,15384,15385],{"class":201,"line":261},[199,15386,15387],{},"\u003C\u002Fscript>\n",[17,15389,15390,15391,15394,15395,15397,15398,15400],{},"For popup-based components such as the cascader and date picker, I used a ",[100,15392,15393],{},"computed"," with get\u002Fset to pass the host's ",[100,15396,15298],{}," straight through to ",[100,15399,15314],{},", which is cleaner.",[58,15402,15404],{"id":15403},"_4-a-library-is-in-essence-an-anti-corruption-layer","4. A library is, in essence, an \"anti-corruption layer\"",[17,15406,15407,15409,15410,15413,15414,15417],{},[100,15408,15205],{}," illustrates this best. In Vant 4 its v-model data changed from a ",[100,15411,15412],{},"Date"," to an array of strings, ",[100,15415,15416],{},"['2024','06','30']",". If I passed that change through, every consumer would have to change too, and the library would become nothing more than \"a relay for upstream breaking changes\", with no value at all.",[17,15419,15420,15421,15424,15425,5248,15427,346],{},"So I had the component adapt to the new format ",[49,15422,15423],{},"internally",", while still accepting \u002F emitting ",[100,15426,15412],{},[49,15428,15429],{},"externally",[191,15431,15433],{"className":15209,"code":15432,"language":15211,"meta":15,"style":15},"\u002F\u002F In:  Date → ['Y','M','D'] fed to Vant 4\n\u002F\u002F Out: string[] from confirm → converted back to Date and emitted to the host\nconfirm({ selectedValues }){\n  const [y,m,d] = selectedValues\n  this.$emit('select', new Date(+y, +m - 1, +d))\n}\n",[100,15434,15435,15440,15445,15450,15455,15460],{"__ignoreMap":15},[199,15436,15437],{"class":201,"line":202},[199,15438,15439],{},"\u002F\u002F In:  Date → ['Y','M','D'] fed to Vant 4\n",[199,15441,15442],{"class":201,"line":25},[199,15443,15444],{},"\u002F\u002F Out: string[] from confirm → converted back to Date and emitted to the host\n",[199,15446,15447],{"class":201,"line":213},[199,15448,15449],{},"confirm({ selectedValues }){\n",[199,15451,15452],{"class":201,"line":219},[199,15453,15454],{},"  const [y,m,d] = selectedValues\n",[199,15456,15457],{"class":201,"line":225},[199,15458,15459],{},"  this.$emit('select', new Date(+y, +m - 1, +d))\n",[199,15461,15462],{"class":201,"line":231},[199,15463,2502],{},[424,15465,15466],{},[17,15467,15279,15468,15471],{},[49,15469,15470],{},"the value of a library = absorbing upstream churn internally and giving consumers a stable external contract."," This is what the anti-corruption layer that backend engineers talk about looks like in a frontend component library. Swap the internals as much as you like; the public API has to stay stable.",[58,15473,15475],{"id":15474},"_5-peerdependencies-and-the-two-vues-disaster","5. peerDependencies and the \"two Vues\" disaster",[17,15477,15478,15479,15482,15483],{},"Many people think vue \u002F vant go into ",[100,15480,15481],{},"peerDependencies"," \"to reduce bundle size\". That is only a side effect. ",[49,15484,15485],{},"The real reason is that the framework must be a singleton.",[17,15487,15488,15489,15492,15493,15496,15497,346],{},"If the library puts vue in ",[100,15490,15491],{},"dependencies"," and bundles it into its output, the host project ends up with ",[49,15494,15495],{},"two Vue runtimes",". The consequence is not \"wasted bytes\" but ",[49,15498,15499],{},"functional breakage",[348,15501,15502,15509,15515],{},[315,15503,15504,15505,15508],{},"There are two reactivity systems, and ",[100,15506,15507],{},"provide \u002F inject"," does not work across instances;",[315,15510,15511,15514],{},[100,15512,15513],{},"app.use(Vant)"," registers on the host's app instance, while your components run on the copy of Vue bundled with the library → components can't be found and injections come back empty;",[315,15516,15517,15518,15521],{},"In the React world this disease is called ",[100,15519,15520],{},"Invalid hook call",": multiple copies of react each have their own dispatcher, and hooks simply crash.",[17,15523,15524,15525,15532,15533,15536,15537,15540,15541,15544,15545,8836],{},"This is also why ",[49,15526,15527,15528,15531],{},"debugging a component library with ",[100,15529,15530],{},"npm link"," so often blows up",": the symlink makes the library resolve the Vue\u002FReact in its own ",[100,15534,15535],{},"node_modules",", and instantly you have two instances. The fix is peerDeps + marking them ",[100,15538,15539],{},"external"," at build time + letting the host provide the one and only copy (or, for local debugging, using ",[100,15542,15543],{},"yalc"," or configuring ",[100,15546,15547],{},"resolve.dedupe",[191,15549,15551],{"className":15209,"code":15550,"language":15211,"meta":15,"style":15},"\u002F\u002F vite.config: externalize the peers so the output never contains vue\u002Fvant\nrollupOptions: { external: ['vue', 'vant'] }\n",[100,15552,15553,15558],{"__ignoreMap":15},[199,15554,15555],{"class":201,"line":202},[199,15556,15557],{},"\u002F\u002F vite.config: externalize the peers so the output never contains vue\u002Fvant\n",[199,15559,15560],{"class":201,"line":25},[199,15561,15562],{},"rollupOptions: { external: ['vue', 'vant'] }\n",[58,15564,15566],{"id":15565},"_6-you-think-you-are-publishing-components-you-are-actually-publishing-a-contract","6. You think you are publishing components; you are actually publishing a \"contract\"",[17,15568,15569,15570,15572,15573,346],{},"Application projects almost never touch these ",[100,15571,7103],{}," fields, but for a library they are the ",[49,15574,15575],{},"public interface definition",[348,15577,15578,15607,15633],{},[315,15579,15580,15585,15586,5625,15589,15592,15593,15596,15597,15599,15600,15602,15603,15606],{},[49,15581,15582],{},[100,15583,15584],{},"exports",": the authoritative entry point for modern resolution, taking precedence over ",[100,15587,15588],{},"main",[100,15590,15591],{},"module",". It also has an underrated role, ",[49,15594,15595],{},"sealing off subpaths",": files not listed in ",[100,15598,15584],{}," simply cannot be ",[100,15601,11152],{},"ed by consumers, which effectively enforces the encapsulation boundary. (When writing a TS library, also note that the ",[100,15604,15605],{},"types"," condition must come first, otherwise type resolution falls through.)",[315,15608,15609,15614,15615,7223,15618,15621,15622,15625,15626,15629,15630,1312],{},[49,15610,15611],{},[100,15612,15613],{},"sideEffects",": declares which modules have side effects. In a component library, ",[100,15616,15617],{},"import '.\u002Fx.css'",[49,15619,15620],{},"side effect",". If you take the lazy route and write ",[100,15623,15624],{},"\"sideEffects\": false",", the bundler will decide that this CSS is \"unused\" and ",[49,15627,15628],{},"tree-shake it away",", and all your styles vanish. The correct form is ",[100,15631,15632],{},"\"sideEffects\": [\"**\u002F*.css\"]",[315,15634,15635,15640,15641,15644,15645,15648],{},[49,15636,15637],{},[100,15638,15639],{},"files",": the publish allowlist. Use an allowlist (",[100,15642,15643],{},"[\"dist\"]",") rather than a ",[100,15646,15647],{},".npmignore"," denylist: when you miss something, the consequence is \"a file was left out\" rather than \"source code \u002F secrets were published by mistake\".",[17,15650,15651,15652,15654],{},"Then there are assets: the local images referenced by ",[100,15653,15102],{}," have to travel with the package. Let Vite automatically inline small images (under 4KB) into the output as base64; otherwise what you ship is a runtime 404.",[58,15656,15658],{"id":15657},"_7-four-lines-of-defense-how-to-confirm-it-really-works","7. Four lines of defense: how to confirm it \"really works\"",[17,15660,15661],{},"Since \"the build is green\" can't be trusted, I verify in four layers, each catching a different kind of bug:",[191,15663,15665],{"className":6559,"code":15664,"language":6561,"meta":15,"style":15},"① npm run build                      → template \u002F syntax compile errors\n② check vant export names with node  → runtime component resolution errors (the build can't catch these)\n③ npm pack + tar -tf                 → missing \u002F accidentally published files\n④ install the .tgz in a fresh project, then build → whether the exports map and peerDeps actually install\n",[100,15666,15667,15672,15677,15682],{"__ignoreMap":15},[199,15668,15669],{"class":201,"line":202},[199,15670,15671],{},"① npm run build                      → template \u002F syntax compile errors\n",[199,15673,15674],{"class":201,"line":25},[199,15675,15676],{},"② check vant export names with node  → runtime component resolution errors (the build can't catch these)\n",[199,15678,15679],{"class":201,"line":213},[199,15680,15681],{},"③ npm pack + tar -tf                 → missing \u002F accidentally published files\n",[199,15683,15684],{"class":201,"line":219},[199,15685,15686],{},"④ install the .tgz in a fresh project, then build → whether the exports map and peerDeps actually install\n",[17,15688,15689,15690,15692,15693,15696,15697,15700,15701,15704],{},"Layer ④ is especially critical: it is the only way to verify that \"the ",[100,15691,15584],{}," field, the ",[100,15694,15695],{},"@scope\u002Fstyle.css"," subpath, and the peerDeps\" hold up from a ",[49,15698,15699],{},"real consumer's point of view",". The source projects are all Vue 2 and can't install this Vue 3 package, so I spun up a brand-new Vue 3 project specifically to install the ",[100,15702,15703],{},".tgz"," and get it running.",[58,15706,15708],{"id":15707},"_8-publishing-risk-free-practice-with-verdaccio","8. Publishing: risk-free practice with Verdaccio",[17,15710,15711,15712,15715,15716,15719,15720,15723,15724,15727],{},"An internal library should not be published to public npm (the code becomes public and is almost impossible to take back). I used ",[49,15713,15714],{},"Verdaccio"," to run a local private registry and walk through the whole flow: the ",[100,15717,15718],{},"@acme"," scope is routed to ",[100,15721,15722],{},"localhost:4873"," via ",[100,15725,15726],{},".npmrc",", while all other dependencies still go to the public registry.",[191,15729,15731],{"className":6559,"code":15730,"language":6561,"meta":15,"style":15},"@acme:registry=http:\u002F\u002Flocalhost:4873\u002F\n",[100,15732,15733],{"__ignoreMap":15},[199,15734,15735],{"class":201,"line":202},[199,15736,15730],{},[17,15738,15739],{},"Once that works, moving to the team's private registry (such as Azure Artifacts or Nexus) only means changing this one registry URL and the token; the commands are exactly the same. Verdaccio is a good choice for practice and for offline caching in CI.",[58,15741,15743],{"id":15742},"wrapping-up-a-transferable-methodology","Wrapping up: a transferable methodology",[17,15745,15746],{},"Looking back, none of what I really learned here is tied to Vant:",[312,15748,15749,15752,15755,15758,15761,15773],{},[315,15750,15751],{},"Extract based on coupling, not complexity, and decouple with dependency inversion;",[315,15753,15754],{},"Framework migrations have \"silent at compile time\" pitfalls, and a green build is the weakest guarantee;",[315,15756,15757],{},"A library is in essence an anti-corruption layer, and its external contract must be stable;",[315,15759,15760],{},"peerDeps exist for the framework singleton, not for smaller bundles;",[315,15762,15763,15765,15766,6499,15768,6499,15770,15772],{},[100,15764,7103],{}," is a public interface, and ",[100,15767,15584],{},[100,15769,15613],{},[100,15771,15639],{}," each deserve care;",[315,15774,15775],{},"Replace \"I think it's fine\" with layered verification.",[17,15777,15778,15779],{},"Component logic is the \"algorithm\"; these things are the \"engineering\". Swap in a React component library, or even wrap an LLM tool SDK as an npm package someday, and the playbook is exactly the same. ",[49,15780,15781],{},"This is what separates \"can write components\" from \"can deliver reusable assets\".",[1042,15783,1044],{},{"title":15,"searchDepth":25,"depth":25,"links":15785},[15786,15787,15788,15789,15790,15791,15792,15793,15794,15795],{"id":15091,"depth":25,"text":15092},{"id":15122,"depth":25,"text":15123},{"id":15191,"depth":25,"text":15192},{"id":15286,"depth":25,"text":15287},{"id":15403,"depth":25,"text":15404},{"id":15474,"depth":25,"text":15475},{"id":15565,"depth":25,"text":15566},{"id":15657,"depth":25,"text":15658},{"id":15707,"depth":25,"text":15708},{"id":15742,"depth":25,"text":15743},"2026-06-30","A retrospective on migrating components that were copy-pasted across several H5 projects to Vue 3 + Vant 4 and shipping them as an npm package. The component code is easy; the engineering contract around it is the hard part.","\u002Farticles\u002Fvue-component-library-npm.svg",{},"\u002Farticles\u002Fvue-component-library-npm","8",{"title":15078,"description":15797},{"loc":15800},"articles\u002Fvue-component-library-npm",[7011,12646],"CwquLWhXulxkDMpW6UdfkvaQiq4qy1Jxvoa5ip8FRU4",{"id":15808,"title":15809,"body":15810,"date":17500,"description":17501,"extension":28,"head":27,"image":17502,"meta":17503,"navigation":30,"ogImage":27,"path":17504,"rating":219,"readingTime":17505,"robots":27,"schemaOrg":27,"seo":17506,"sitemap":17507,"stem":17508,"tags":17509,"__hash__":17510},"articles_en\u002Farticles\u002Fwhatsapp-webhook-subscriptions.md","A WhatsApp Cloud API Gotcha: The Webhook Verifies, but No Messages Arrive",{"type":7,"value":15811,"toc":17466},[15812,15830,15834,15837,15866,15869,15875,15877,15881,15888,15976,15983,16032,16035,16063,16069,16073,16080,16082,16086,16101,16109,16120,16132,16134,16138,16148,16152,16176,16192,16196,16221,16234,16246,16248,16252,16259,16263,16282,16299,16313,16358,16367,16373,16379,16393,16396,16417,16432,16436,16453,16482,16489,16514,16521,16537,16541,16551,16576,16578,16582,16585,16589,16611,16615,16628,16637,16645,16652,16697,16708,16712,16728,16732,16743,16808,16810,16814,16821,16877,16880,16902,16905,16909,16918,16941,16945,16955,16957,16961,16964,17023,17027,17089,17099,17101,17105,17123,17452,17463],[43,15813,15814,15820],{},[17,15815,15816,15817,1312],{},"You followed the docs step by step and set up the WhatsApp Cloud API webhook. The Meta console plainly says \"verified\", and a message sent from a real phone shows ✓✓ (delivered). Yet your backend logs contain ",[49,15818,15819],{},"not a single inbound record",[17,15821,15822,15823,15825,15826,15829],{},"If this is where you are stuck, this post can save you a few hours. The cause is almost always one switch that the docs barely emphasize but that decides whether messages flow at all: ",[100,15824,4220],{},". I'll untangle the ",[49,15827,15828],{},"three things that are all called a \"subscription\" but are entirely different"," in the WhatsApp Cloud API, and give you a systematic debugging path that doesn't rely on guessing.",[58,15831,15833],{"id":15832},"_1-the-symptom-a-counterintuitive-delivered","1. The symptom: a counterintuitive \"delivered\"",[17,15835,15836],{},"After integrating the WhatsApp Cloud API and configuring the webhook per the official Quickstart, a common place to get stuck looks like this:",[348,15838,15839,15849,15859],{},[315,15840,15841,15842,15845,15846,1312],{},"You click ",[49,15843,15844],{},"Verify and save"," in the Meta developer console, and it reports the webhook as ",[49,15847,15848],{},"verified",[315,15850,15851,15852,15855,15856,1312],{},"You send ",[100,15853,15854],{},"hello"," from a real phone to your WhatsApp number, and the message shows ",[49,15857,15858],{},"✓✓ (delivered)",[315,15860,15861,15862,15865],{},"But your backend ",[49,15863,15864],{},"receives no POST callback at all",", and the inbound log is empty.",[17,15867,15868],{},"Verification succeeded, the message was delivered, and still no callback. At this point most people start suspecting the reverse proxy, or the signature check swallowing the message, or a missing payment method.",[17,15870,15871,15874],{},[49,15872,15873],{},"It is most likely none of those."," The real cause is that you missed the most important, and best hidden, of the three \"subscriptions\" in the WhatsApp Cloud API.",[1940,15876],{},[58,15878,15880],{"id":15879},"_2-the-core-idea-three-things-called-subscription-that-are-three-different-things","2. The core idea: three things called \"subscription\" that are three different things",[17,15882,15883,15884,15887],{},"For an inbound message to reach your backend, three conditions have to hold on Meta's side at the same time. The trap is that all three ",[49,15885,15886],{},"carry the word \"subscribe\""," in the docs and the console, so they are easy to conflate, and doing one feels like having done them all.",[105,15889,15890,15905],{},[108,15891,15892],{},[111,15893,15894,15896,15899,15902],{},[114,15895,6521],{},[114,15897,15898],{},"Name",[114,15900,15901],{},"Where you do it",[114,15903,15904],{},"What it actually does",[121,15906,15907,15932,15951],{},[111,15908,15909,15912,15922,15925],{},[126,15910,15911],{},"①",[126,15913,15914,15917,15918,15921],{},[49,15915,15916],{},"Webhook URL verification"," (the ",[100,15919,15920],{},"hub.mode=subscribe"," challenge)",[126,15923,15924],{},"Your code (a GET endpoint)",[126,15926,15927,15928,15931],{},"Proves the callback URL is reachable and the ",[100,15929,15930],{},"verify_token"," is correct",[111,15933,15934,15937,15945,15948],{},[126,15935,15936],{},"②",[126,15938,15939],{},[49,15940,15941,15942,15944],{},"App subscription to the ",[100,15943,4224],{}," field",[126,15946,15947],{},"Meta console → the App's Webhooks settings",[126,15949,15950],{},"The App declares which kinds of events it wants to receive",[111,15952,15953,15956,15963,15969],{},[126,15954,15955],{},"③",[126,15957,15958,3724,15961,5665],{},[49,15959,15960],{},"WABA → App subscription",[100,15962,4220],{},[126,15964,15965,15966,5665],{},"Meta platform API (",[49,15967,15968],{},"not a checkbox in the console",[126,15970,15971,15972,15975],{},"Routes ",[49,15973,15974],{},"the events of a specific WhatsApp Business Account"," to this App",[17,15977,15978,15979,15982],{},"The diagram below shows the three gates a message has to pass through to reach your backend. Without ③, Meta ",[49,15980,15981],{},"drops it silently",", and the sender notices nothing:",[191,15984,15986],{"className":193,"code":15985,"language":195,"meta":15,"style":15},"flowchart TD\n    U[\"User sends a message from a real phone\"] --> M[\"Meta Cloud API\"]\n    M --> G1{\"① Callback URL verified?\u003Cbr>(reachable + verify_token matches)\"}\n    G1 -->|No| X1[\"Callback verification fails\"]\n    G1 -->|Yes| G2{\"② App subscribed to the messages field?\"}\n    G2 -->|No| X2[\"App does not receive this event type\"]\n    G2 -->|Yes| G3{\"③ subscribed_apps:\u003Cbr>is the WABA subscribed to this App?\"}\n    G3 -->|No| X3[\"⚠ Meta silently does not deliver\u003Cbr>(the one most often missed)\"]\n    G3 -->|Yes| OK[\"✅ POST to your backend webhook\"]\n",[100,15987,15988,15992,15997,16002,16007,16012,16017,16022,16027],{"__ignoreMap":15},[199,15989,15990],{"class":201,"line":202},[199,15991,205],{},[199,15993,15994],{"class":201,"line":25},[199,15995,15996],{},"    U[\"User sends a message from a real phone\"] --> M[\"Meta Cloud API\"]\n",[199,15998,15999],{"class":201,"line":213},[199,16000,16001],{},"    M --> G1{\"① Callback URL verified?\u003Cbr>(reachable + verify_token matches)\"}\n",[199,16003,16004],{"class":201,"line":219},[199,16005,16006],{},"    G1 -->|No| X1[\"Callback verification fails\"]\n",[199,16008,16009],{"class":201,"line":225},[199,16010,16011],{},"    G1 -->|Yes| G2{\"② App subscribed to the messages field?\"}\n",[199,16013,16014],{"class":201,"line":231},[199,16015,16016],{},"    G2 -->|No| X2[\"App does not receive this event type\"]\n",[199,16018,16019],{"class":201,"line":237},[199,16020,16021],{},"    G2 -->|Yes| G3{\"③ subscribed_apps:\u003Cbr>is the WABA subscribed to this App?\"}\n",[199,16023,16024],{"class":201,"line":243},[199,16025,16026],{},"    G3 -->|No| X3[\"⚠ Meta silently does not deliver\u003Cbr>(the one most often missed)\"]\n",[199,16028,16029],{"class":201,"line":249},[199,16030,16031],{},"    G3 -->|Yes| OK[\"✅ POST to your backend webhook\"]\n",[17,16033,16034],{},"A mail analogy makes it clear:",[43,16036,16037,16042,16047,16056],{},[17,16038,16039,16041],{},[49,16040,15911],{}," = the post office confirms that your address really exists and can receive mail.",[17,16043,16044,16046],{},[49,16045,15936],{}," = you declare that you only want registered mail, not flyers.",[17,16048,16049,16051,16052,16055],{},[49,16050,15955],{}," = ",[49,16053,16054],{},"a specific sender"," is registered so that the mail they send gets delivered to your address.",[17,16057,16058,16059,16062],{},"Without ③, the address is verified and the mail type is declared, but ",[49,16060,16061],{},"no sender is registered to you",", so the mail never comes.",[17,16064,16065,16066,1312],{},"In the vast majority of \"verified but no messages\" cases, ① and ② are done and ",[49,16067,16068],{},"only ③ is missing",[2031,16070,16072],{"id":16071},"why-is-the-easiest-to-miss","Why is ③ the easiest to miss?",[17,16074,16075,16076,16079],{},"Because ① and ② both have prominent UI entry points in the console (enter the URL, click verify, tick the fields), and each ends with a success message. ③, on the other hand, ",[49,16077,16078],{},"often has no corresponding checkbox in the console","; you have to call the Graph API explicitly. In the docs it is usually a low-key section of the API Reference rather than part of the main Quickstart path, so it is very natural to skip.",[1940,16081],{},[58,16083,16085],{"id":16084},"_3-why-does-it-work-in-testing-and-break-the-moment-you-go-to-production","3. Why does it work in testing and break the moment you go to production?",[17,16087,16088,16089,16092,16093,16096,16097,16100],{},"This is another frequent source of confusion, and the key to understanding ③. Many people use the ",[49,16090,16091],{},"test number"," Meta provides during the ",[49,16094,16095],{},"testing phase",", and everything works. Then they switch to ",[49,16098,16099],{},"their own production number and their own WABA",", and messages stop arriving immediately.",[17,16102,16103,16104],{},"To understand this, remember one fact: ",[49,16105,16106,16108],{},[100,16107,4220],{}," is a WABA-level subscription. It binds one specific WABA to one specific App, and it does not carry over automatically when you change numbers or environments.",[17,16110,16111,16112,16115,16116,16119],{},"So why did it work in testing? ",[49,16113,16114],{},"This is exactly the place where you should not take things for granted."," That subscription may have been established at some earlier point: perhaps an onboarding flow did it as a side effect, or perhaps someone configured it by hand when setting up the test environment and never wrote it into the handover notes. Either way you can't see that it exists, so you assume things were simply fine all along. It is not in your code, and it may not be in anyone's operation log either. So ",[49,16117,16118],{},"don't try to work out why testing worked (often you can't), and check the production environment directly"," (see section 4).",[561,16121,16122],{},[17,16123,16124,16127,16128,16131],{},[49,16125,16126],{},"Conclusion",": a working test environment does not mean the chain is complete. For platform-side state such as subscriptions and registrations, which ",[49,16129,16130],{},"lives neither in your code nor in any step you explicitly performed",", you must confirm each item when you change environments. You cannot assume that production works because testing did.",[1940,16133],{},[58,16135,16137],{"id":16136},"_4-how-to-check-for-and-how-to-fix-it","4. How to check for ③, and how to fix it",[17,16139,16140,16141],{},"The rule of thumb in one line: ",[49,16142,16143,16144,16147],{},"WhatsApp webhook configured but no messages arriving → check ",[100,16145,16146],{},"GET \u002F{waba_id}\u002Fsubscribed_apps"," first.",[2031,16149,16151],{"id":16150},"_41-check-which-apps-is-this-waba-subscribed-to","4.1 Check: which Apps is this WABA subscribed to",[191,16153,16155],{"className":5351,"code":16154,"language":5353,"meta":15,"style":15},"curl -s \"https:\u002F\u002Fgraph.facebook.com\u002Fv17.0\u002F\u003CWABA_ID>\u002Fsubscribed_apps\" \\\n  -H \"Authorization: Bearer \u003CACCESS_TOKEN>\"\n",[100,16156,16157,16169],{"__ignoreMap":15},[199,16158,16159,16161,16164,16167],{"class":201,"line":202},[199,16160,5365],{"class":1619},[199,16162,16163],{"class":3645}," -s",[199,16165,16166],{"class":1633}," \"https:\u002F\u002Fgraph.facebook.com\u002Fv17.0\u002F\u003CWABA_ID>\u002Fsubscribed_apps\"",[199,16168,14091],{"class":3645},[199,16170,16171,16173],{"class":201,"line":25},[199,16172,14096],{"class":3645},[199,16174,16175],{"class":1633}," \"Authorization: Bearer \u003CACCESS_TOKEN>\"\n",[348,16177,16178,16189],{},[315,16179,16180,16181,16184,16185,16188],{},"It returns ",[100,16182,16183],{},"{\"data\": []}"," (an empty array) → ",[49,16186,16187],{},"this is it",". The WABA is not subscribed to any App, so of course nothing is delivered.",[315,16190,16191],{},"Your App is in the response → ③ is in place and the problem is elsewhere (go back and check signature verification, the reverse proxy, and the field subscription).",[2031,16193,16195],{"id":16194},"_42-fix-subscribe-the-waba-to-the-current-app","4.2 Fix: subscribe the WABA to the current App",[191,16197,16199],{"className":5351,"code":16198,"language":5353,"meta":15,"style":15},"curl -s -X POST \"https:\u002F\u002Fgraph.facebook.com\u002Fv17.0\u002F\u003CWABA_ID>\u002Fsubscribed_apps\" \\\n  -H \"Authorization: Bearer \u003CACCESS_TOKEN>\"\n",[100,16200,16201,16215],{"__ignoreMap":15},[199,16202,16203,16205,16207,16209,16211,16213],{"class":201,"line":202},[199,16204,5365],{"class":1619},[199,16206,16163],{"class":3645},[199,16208,14082],{"class":3645},[199,16210,14085],{"class":1633},[199,16212,16166],{"class":1633},[199,16214,14091],{"class":3645},[199,16216,16217,16219],{"class":201,"line":25},[199,16218,14096],{"class":3645},[199,16220,16175],{"class":1633},[17,16222,16223,16224,16227,16228,2625,16231],{},"The \"App\" being subscribed here is the one that ",[100,16225,16226],{},"\u003CACCESS_TOKEN>"," belongs to. Once it returns ",[100,16229,16230],{},"{\"success\": true}",[49,16232,16233],{},"send another message from a real phone, and the callback usually arrives right away.",[561,16235,16236],{},[17,16237,16238,16239,16241,16242,16245],{},"Make sure you use the right ",[100,16240,16226],{},". In production, use a ",[49,16243,16244],{},"permanent System User token"," (section 5.2 below shows how to verify that it really is permanent), not a temporary token that expires after 24 hours. Otherwise the subscription succeeds now and \"mysteriously\" stops working two days later.",[1940,16247],{},[58,16249,16251],{"id":16250},"_5-no-guessing-a-layered-debugging-method","5. No guessing: a layered debugging method",[17,16253,16254,16255,16258],{},"\"Check subscribed_apps first\" is the conclusion. But if you want to actually locate the problem rather than get lucky, I recommend walking through the path below: ",[49,16256,16257],{},"work in layers, and verify facts with tools",". Each layer verifies exactly one thing, and each step narrows the search. It applies to any \"third-party webhook isn't calling me back\" problem.",[2031,16260,16262],{"id":16261},"_51-layer-one-prove-your-app-and-reverse-proxy-are-fine-one-get-locally-one-against-the-public-url","5.1 Layer one: prove your app and reverse proxy are fine (one GET locally, one against the public URL)",[17,16264,16265,16266,2625,16268,3933,16271,16274,16275,16281],{},"WhatsApp's webhook verification is a GET request carrying ",[100,16267,15920],{},[100,16269,16270],{},"hub.verify_token",[100,16272,16273],{},"hub.challenge",", and it requires you to ",[49,16276,16277,16278,16280],{},"echo ",[100,16279,16273],{}," back unchanged",". Hit it locally first:",[191,16283,16285],{"className":5351,"code":16284,"language":5353,"meta":15,"style":15},"curl \"http:\u002F\u002F127.0.0.1:8000\u002Fwebhooks\u002Fwhatsapp?hub.mode=subscribe&hub.verify_token=\u003CYOUR_VERIFY_TOKEN>&hub.challenge=test123\"\n# Expected output: test123\n",[100,16286,16287,16294],{"__ignoreMap":15},[199,16288,16289,16291],{"class":201,"line":202},[199,16290,5365],{"class":1619},[199,16292,16293],{"class":1633}," \"http:\u002F\u002F127.0.0.1:8000\u002Fwebhooks\u002Fwhatsapp?hub.mode=subscribe&hub.verify_token=\u003CYOUR_VERIFY_TOKEN>&hub.challenge=test123\"\n",[199,16295,16296],{"class":201,"line":25},[199,16297,16298],{"class":2468},"# Expected output: test123\n",[17,16300,16301,16302,16305,16306,16309,16310,16312],{},"Then send the same request to your ",[49,16303,16304],{},"public domain",". If both echo the ",[100,16307,16308],{},"challenge",", you have proven that your application logic, your reverse proxy and your ",[100,16311,15930],{}," are all correct. The matching server-side implementation, using FastAPI as an example:",[191,16314,16316],{"className":384,"code":16315,"language":386,"meta":15,"style":15},"@router.get(\"\u002Fwebhooks\u002Fwhatsapp\")\nasync def verify_webhook(request: Request):\n    mode = request.query_params.get(\"hub.mode\")\n    token = request.query_params.get(\"hub.verify_token\")\n    challenge = request.query_params.get(\"hub.challenge\")\n    if mode == \"subscribe\" and token == EXPECTED_VERIFY_TOKEN:\n        return Response(content=challenge or \"\", media_type=\"text\u002Fplain\")\n    return Response(status_code=403)\n",[100,16317,16318,16323,16328,16333,16338,16343,16348,16353],{"__ignoreMap":15},[199,16319,16320],{"class":201,"line":202},[199,16321,16322],{},"@router.get(\"\u002Fwebhooks\u002Fwhatsapp\")\n",[199,16324,16325],{"class":201,"line":25},[199,16326,16327],{},"async def verify_webhook(request: Request):\n",[199,16329,16330],{"class":201,"line":213},[199,16331,16332],{},"    mode = request.query_params.get(\"hub.mode\")\n",[199,16334,16335],{"class":201,"line":219},[199,16336,16337],{},"    token = request.query_params.get(\"hub.verify_token\")\n",[199,16339,16340],{"class":201,"line":225},[199,16341,16342],{},"    challenge = request.query_params.get(\"hub.challenge\")\n",[199,16344,16345],{"class":201,"line":231},[199,16346,16347],{},"    if mode == \"subscribe\" and token == EXPECTED_VERIFY_TOKEN:\n",[199,16349,16350],{"class":201,"line":237},[199,16351,16352],{},"        return Response(content=challenge or \"\", media_type=\"text\u002Fplain\")\n",[199,16354,16355],{"class":201,"line":243},[199,16356,16357],{},"    return Response(status_code=403)\n",[43,16359,16360],{},[17,16361,16362,16363,16366],{},"Passing this layer is precisely what most easily convinces people that everything is set up. ",[49,16364,16365],{},"It only proves that the callback URL is valid; it says nothing about whether messages will come in."," Don't be fooled by the words \"subscription verified\".",[2031,16368,16370,16371],{"id":16369},"_52-layer-two-verify-your-access_token-with-debug_token","5.2 Layer two: verify your access_token with ",[100,16372,3913],{},[17,16374,16375,16376,16378],{},"A lot of \"intermittently can't receive or can't send\" problems are really a token of the wrong type or with the wrong lifetime. The Graph API's ",[100,16377,3913],{}," tells you at a glance:",[191,16380,16382],{"className":5351,"code":16381,"language":5353,"meta":15,"style":15},"curl -s \"https:\u002F\u002Fgraph.facebook.com\u002Fdebug_token?input_token=\u003CACCESS_TOKEN>&access_token=\u003CAPP_ID>|\u003CAPP_SECRET>\"\n",[100,16383,16384],{"__ignoreMap":15},[199,16385,16386,16388,16390],{"class":201,"line":202},[199,16387,5365],{"class":1619},[199,16389,16163],{"class":3645},[199,16391,16392],{"class":1633}," \"https:\u002F\u002Fgraph.facebook.com\u002Fdebug_token?input_token=\u003CACCESS_TOKEN>&access_token=\u003CAPP_ID>|\u003CAPP_SECRET>\"\n",[17,16394,16395],{},"Look at two fields in the response:",[348,16397,16398,16407],{},[315,16399,16400,16402,16403,16406],{},[100,16401,13735],{},": for production it should be ",[100,16404,16405],{},"SYSTEM_USER"," (a system user token, which can be made permanent).",[315,16408,16409,1630,16411,16416],{},[100,16410,3872],{},[49,16412,16413,16415],{},[100,16414,833],{}," means it never expires",". If it is a future timestamp, the token will expire, and production will break sooner or later.",[1036,16418,16419],{},[17,16420,16421,16422,16425,16426,16431],{},"A side benefit: this call uses ",[100,16423,16424],{},"\u003CAPP_ID>|\u003CAPP_SECRET>"," as the caller's credentials, so ",[49,16427,16428,16429,15931],{},"a successful response also proves that your ",[100,16430,4683],{}," (you need it for signature verification).",[2031,16433,16435],{"id":16434},"_53-layer-three-sign-your-own-webhook-post-to-verify-the-code-path","5.3 Layer three: sign your own webhook POST to verify the code path",[17,16437,16438,16439,16442,16443,16446,16447,16449,16450,16452],{},"To confirm that your code would handle a message correctly if one really came in, you can build a POST ",[49,16440,16441],{},"with a valid signature"," yourself and send it to your local webhook. WhatsApp computes an HMAC-SHA256 over the ",[49,16444,16445],{},"raw request body"," using ",[100,16448,4683],{}," and puts it in the ",[100,16451,4591],{}," header:",[191,16454,16456],{"className":384,"code":16455,"language":386,"meta":15,"style":15},"import hmac, hashlib\n\nraw_body = open(\"sample_inbound.json\", \"rb\").read()          # a sample inbound payload\nsig = \"sha256=\" + hmac.new(APP_SECRET.encode(), raw_body, hashlib.sha256).hexdigest()\n# Then use curl \u002F httpx to POST raw_body with this signature header to http:\u002F\u002F127.0.0.1:8000\u002Fwebhooks\u002Fwhatsapp\n",[100,16457,16458,16463,16467,16472,16477],{"__ignoreMap":15},[199,16459,16460],{"class":201,"line":202},[199,16461,16462],{},"import hmac, hashlib\n",[199,16464,16465],{"class":201,"line":25},[199,16466,461],{"emptyLinePlaceholder":30},[199,16468,16469],{"class":201,"line":213},[199,16470,16471],{},"raw_body = open(\"sample_inbound.json\", \"rb\").read()          # a sample inbound payload\n",[199,16473,16474],{"class":201,"line":219},[199,16475,16476],{},"sig = \"sha256=\" + hmac.new(APP_SECRET.encode(), raw_body, hashlib.sha256).hexdigest()\n",[199,16478,16479],{"class":201,"line":225},[199,16480,16481],{},"# Then use curl \u002F httpx to POST raw_body with this signature header to http:\u002F\u002F127.0.0.1:8000\u002Fwebhooks\u002Fwhatsapp\n",[17,16483,16484,16485,16488],{},"The standard way to verify the signature on the server (note the ",[49,16486,16487],{},"constant-time comparison",", which guards against timing side channels):",[191,16490,16492],{"className":384,"code":16491,"language":386,"meta":15,"style":15},"expected = \"sha256=\" + hmac.new(APP_SECRET.encode(), raw_body, hashlib.sha256).hexdigest()\nif not hmac.compare_digest(request_signature, expected):\n    logger.warning(\"Webhook signature verification failed\")\n    return {\"status\": \"ok\"}        # Note: return 200 even on failure, see section 6\n",[100,16493,16494,16499,16504,16509],{"__ignoreMap":15},[199,16495,16496],{"class":201,"line":202},[199,16497,16498],{},"expected = \"sha256=\" + hmac.new(APP_SECRET.encode(), raw_body, hashlib.sha256).hexdigest()\n",[199,16500,16501],{"class":201,"line":25},[199,16502,16503],{},"if not hmac.compare_digest(request_signature, expected):\n",[199,16505,16506],{"class":201,"line":213},[199,16507,16508],{},"    logger.warning(\"Webhook signature verification failed\")\n",[199,16510,16511],{"class":201,"line":219},[199,16512,16513],{},"    return {\"status\": \"ok\"}        # Note: return 200 even on failure, see section 6\n",[17,16515,16516,16517,16520],{},"If this self-signed POST gets your service to parse, process and reply normally, you have proven that ",[49,16518,16519],{},"the whole code path works",": signature check → parsing → business dispatch.",[699,16522,16523],{},[17,16524,16525,16528,16529,16532,16533,16536],{},[49,16526,16527],{},"There is a blind spot here that you must remember",": a self-signed simulated POST ",[49,16530,16531],{},"bypasses Meta",". It can prove that your code handles a message once it arrives, but it ",[49,16534,16535],{},"cannot prove that Meta will actually push the message to you",". The former is a problem in your code; the latter is a platform delivery problem, and ③ belongs to the latter.",[2031,16538,16540],{"id":16539},"_54-layer-four-a-real-device-test-which-you-cannot-skip","5.4 Layer four: a real-device test, which you cannot skip",[17,16542,16543,16544,16547,16548,16550],{},"Passing the first three layers only shows that the code and configuration on your side are correct. ",[49,16545,16546],{},"The only thing that verifies real delivery by Meta is sending a message from a real phone and seeing whether the callback arrives."," The missing ③ ",[100,16549,4220],{}," in this case could only be exposed by a real device, because it is a switch in the platform's delivery stage, and the first three layers (local GET, token check, self-signed POST) all bypass it.",[191,16552,16554],{"className":6559,"code":16553,"language":6561,"meta":15,"style":15},"Local GET echoes the challenge       → verifies: app + reverse proxy + verify_token\ndebug_token on the token             → verifies: access_token type\u002Fexpiry + app_secret\nSelf-signed HMAC simulated POST      → verifies: code path (signature → parsing → dispatch)\nReal-device message, watch callback  → verifies: real delivery by Meta (subscribed_apps and other platform state) ★ cannot be skipped\n",[100,16555,16556,16561,16566,16571],{"__ignoreMap":15},[199,16557,16558],{"class":201,"line":202},[199,16559,16560],{},"Local GET echoes the challenge       → verifies: app + reverse proxy + verify_token\n",[199,16562,16563],{"class":201,"line":25},[199,16564,16565],{},"debug_token on the token             → verifies: access_token type\u002Fexpiry + app_secret\n",[199,16567,16568],{"class":201,"line":213},[199,16569,16570],{},"Self-signed HMAC simulated POST      → verifies: code path (signature → parsing → dispatch)\n",[199,16572,16573],{"class":201,"line":219},[199,16574,16575],{},"Real-device message, watch callback  → verifies: real delivery by Meta (subscribed_apps and other platform state) ★ cannot be skipped\n",[1940,16577],{},[58,16579,16581],{"id":16580},"_6-a-few-side-traps-worth-clearing-up","6. A few side traps worth clearing up",[17,16583,16584],{},"While debugging this kind of problem, it is easy to be led astray by a few things that look related but aren't. Here they are in one place.",[2031,16586,16588],{"id":16587},"_61-why-return-200-even-when-signature-verification-fails-read-the-logs-not-the-status-code","6.1 Why return 200 even when signature verification fails? Read the logs, not the status code",[17,16590,16591,16592,16595,16596,16599,16600,16603,16604,16607,16608,1312],{},"Meta ",[49,16593,16594],{},"retries on any non-2xx response",". If you return 4xx\u002F5xx when signature verification fails, a bug in the verification logic itself will bring on a ",[49,16597,16598],{},"retry storm",". So the right approach is to ",[49,16601,16602],{},"return 200 whether verification succeeds or fails",", and to surface the anomaly through ",[49,16605,16606],{},"logs"," rather than the HTTP status code. That means that while debugging you ",[49,16609,16610],{},"cannot tell from the status code whether verification passed; you have to check the logs for a \"signature verification failed\" warning",[2031,16612,16614],{"id":16613},"_62-the-no-payment-method-configured-warning-is-not-why-you-arent-receiving-messages","6.2 The \"no payment method configured\" warning is not why you aren't receiving messages",[17,16616,16617,16618,16621,16622,9838,16625],{},"The Meta console often warns that a missing payment method may limit messaging features, which makes it easy to conclude that messages aren't arriving because no payment method is attached. In fact, ",[49,16619,16620],{},"replies inside the customer service window (within 24 hours of a user-initiated message) are free service messages and need no payment method."," A bot that only responds to users normally works entirely inside this window. A payment method is only needed for ",[49,16623,16624],{},"proactive pushes, template messages, or volume beyond the free tier",[49,16626,16627],{},"What actually blocks inbound messages is ③, not payment.",[1036,16629,16630],{},[17,16631,16632,16633,16636],{},"The lesson: the most prominent warning on a platform is not necessarily what is blocking you right now. Locate the problem from the ",[49,16634,16635],{},"symptoms"," (logs, real-device behavior) instead of following the most eye-catching notice to a conclusion.",[2031,16638,16640,16641,16644],{"id":16639},"_63-number-pending-review-or-not-registered-use-the-cloud-api-register-and-it-isnt-a-payment-problem-either","6.3 Number \"pending review\" or \"not registered\": use the Cloud API ",[100,16642,16643],{},"\u002Fregister",", and it isn't a payment problem either",[17,16646,16647,16648,16651],{},"If your number shows as \"not registered\" on ",[100,16649,16650],{},"wa.me",", or stays \"pending review\", the root cause is usually that it never went through Cloud API number registration:",[191,16653,16655],{"className":5351,"code":16654,"language":5353,"meta":15,"style":15},"curl -s -X POST \"https:\u002F\u002Fgraph.facebook.com\u002Fv17.0\u002F\u003CPHONE_NUMBER_ID>\u002Fregister\" \\\n  -H \"Authorization: Bearer \u003CACCESS_TOKEN>\" \\\n  -H \"Content-Type: application\u002Fjson\" \\\n  -d '{\"messaging_product\": \"whatsapp\", \"pin\": \"\u003CYOUR_6_DIGIT_PIN>\"}'\n",[100,16656,16657,16672,16681,16689],{"__ignoreMap":15},[199,16658,16659,16661,16663,16665,16667,16670],{"class":201,"line":202},[199,16660,5365],{"class":1619},[199,16662,16163],{"class":3645},[199,16664,14082],{"class":3645},[199,16666,14085],{"class":1633},[199,16668,16669],{"class":1633}," \"https:\u002F\u002Fgraph.facebook.com\u002Fv17.0\u002F\u003CPHONE_NUMBER_ID>\u002Fregister\"",[199,16671,14091],{"class":3645},[199,16673,16674,16676,16679],{"class":201,"line":25},[199,16675,14096],{"class":3645},[199,16677,16678],{"class":1633}," \"Authorization: Bearer \u003CACCESS_TOKEN>\"",[199,16680,14091],{"class":3645},[199,16682,16683,16685,16687],{"class":201,"line":213},[199,16684,14096],{"class":3645},[199,16686,14099],{"class":1633},[199,16688,14091],{"class":3645},[199,16690,16691,16694],{"class":201,"line":219},[199,16692,16693],{"class":3645},"  -d",[199,16695,16696],{"class":1633}," '{\"messaging_product\": \"whatsapp\", \"pin\": \"\u003CYOUR_6_DIGIT_PIN>\"}'\n",[17,16698,16699,16700,16703,16704,16707],{},"This ",[100,16701,16702],{},"pin"," is the number's two-step verification PIN. ",[49,16705,16706],{},"You set it yourself, and you must record it somewhere safe",": you will need it when changing devices, migrating, or re-registering.",[2031,16709,16711],{"id":16710},"_64-display-name-review-avoid-internal-or-technical-words","6.4 Display name review: avoid internal or technical words",[17,16713,16714,16715,2625,16718,12554,16720,16723,16724,16727],{},"When you submit the number's Display Name for review, names containing internal terms, technical terms, or overly generic words (such as ",[100,16716,16717],{},"Prod",[100,16719,14905],{},[100,16721,16722],{},"AI Bot",") tend to be rejected. ",[49,16725,16726],{},"A real, properly formed brand name"," usually passes quickly.",[2031,16729,16731],{"id":16730},"_65-the-webhook-must-return-200-within-5-seconds","6.5 The webhook must return 200 within 5 seconds",[17,16733,16734,16735,16738,16739,16742],{},"Meta requires the webhook to ",[49,16736,16737],{},"respond with 200 within 5 seconds","; otherwise it counts as a failure and is retried. So ",[49,16740,16741],{},"don't do slow work synchronously in the webhook"," (calling an LLM, querying the database, sending messages). The right pattern is to return 200 as soon as the payload is parsed and hand the slow work to a background task:",[191,16744,16746],{"className":384,"code":16745,"language":386,"meta":15,"style":15},"@router.post(\"\u002Fwebhooks\u002Fwhatsapp\")\nasync def webhook(request: Request):\n    body = await request.body()\n    # ... signature verification ...\n    payload = parse(body)\n    for msg in extract_messages(payload):\n        # Idempotent dedup: Meta may redeliver the same message_id\n        if already_processed(msg.id):\n            continue\n        mark_processed(msg.id, ttl=60)\n        asyncio.create_task(handle_message(msg))   # all slow work is async\n    return {\"status\": \"ok\"}                          # 200 immediately\n",[100,16747,16748,16753,16758,16763,16768,16773,16778,16783,16788,16793,16798,16803],{"__ignoreMap":15},[199,16749,16750],{"class":201,"line":202},[199,16751,16752],{},"@router.post(\"\u002Fwebhooks\u002Fwhatsapp\")\n",[199,16754,16755],{"class":201,"line":25},[199,16756,16757],{},"async def webhook(request: Request):\n",[199,16759,16760],{"class":201,"line":213},[199,16761,16762],{},"    body = await request.body()\n",[199,16764,16765],{"class":201,"line":219},[199,16766,16767],{},"    # ... signature verification ...\n",[199,16769,16770],{"class":201,"line":225},[199,16771,16772],{},"    payload = parse(body)\n",[199,16774,16775],{"class":201,"line":231},[199,16776,16777],{},"    for msg in extract_messages(payload):\n",[199,16779,16780],{"class":201,"line":237},[199,16781,16782],{},"        # Idempotent dedup: Meta may redeliver the same message_id\n",[199,16784,16785],{"class":201,"line":243},[199,16786,16787],{},"        if already_processed(msg.id):\n",[199,16789,16790],{"class":201,"line":249},[199,16791,16792],{},"            continue\n",[199,16794,16795],{"class":201,"line":255},[199,16796,16797],{},"        mark_processed(msg.id, ttl=60)\n",[199,16799,16800],{"class":201,"line":261},[199,16801,16802],{},"        asyncio.create_task(handle_message(msg))   # all slow work is async\n",[199,16804,16805],{"class":201,"line":267},[199,16806,16807],{},"    return {\"status\": \"ok\"}                          # 200 immediately\n",[1940,16809],{},[58,16811,16813],{"id":16812},"_7-going-further-resolving-the-tenant-from-the-webhook-payload-in-a-multi-tenant-setup","7. Going further: resolving the tenant from the webhook payload in a multi-tenant setup",[17,16815,16816,16817,16820],{},"Once messages are flowing, a multi-tenant system immediately hits the next question: ",[49,16818,16819],{},"which tenant does this message belong to?"," In my case I was adding WhatsApp to a multi-channel conversational assistant that already supported other IM channels, with one number serving one tenant and credentials isolated per tenant. That is when I noticed that, under the same \"channel\" abstraction, different channels resolve the tenant in different ways:",[105,16822,16823,16840],{},[108,16824,16825],{},[111,16826,16827,16830,16837],{},[114,16828,16829],{},"Channel",[114,16831,16832,16833,16836],{},"How the tenant (",[100,16834,16835],{},"tenant_id",") is determined",[114,16838,16839],{},"Needs a stored mapping?",[121,16841,16842,16856,16866],{},[111,16843,16844,16847,16854],{},[126,16845,16846],{},"WhatsApp (this post)",[126,16848,16849,16850,16853],{},"Look up the tenant config table by ",[100,16851,16852],{},"phone_number_id",", cache the result for 24 hours",[126,16855,9919],{},[111,16857,16858,16861,16864],{},[126,16859,16860],{},"Other IM channel A",[126,16862,16863],{},"Taken dynamically from the account's login session",[126,16865,5559],{},[111,16867,16868,16871,16874],{},[126,16869,16870],{},"Other IM channel B",[126,16872,16873],{},"Injected directly in the webhook URL path",[126,16875,16876],{},"No (the URL carries it)",[17,16878,16879],{},"Why the difference? It comes down to whether the inbound payload lets you locate the tenant directly:",[348,16881,16882,16896,16899],{},[315,16883,16884,16885,16887,16888,16891,16892,16895],{},"WhatsApp is one number per tenant, and the payload only carries ",[100,16886,16852],{}," (in ",[100,16889,16890],{},"value.metadata","), so you have to use it for a ",[49,16893,16894],{},"reverse lookup"," against a \"number → tenant\" mapping.",[315,16897,16898],{},"Some channels serve several tenants from a single account, and the tenant travels with the login session.",[315,16900,16901],{},"Some channels give each tenant its own webhook URL containing an ID, so the path itself is the answer.",[17,16903,16904],{},"None of the three is better than the others; it depends on what the platform puts in the payload. But the reverse lookup is the only one that requires you to maintain mapping data yourself, which adds two things to watch for around writes and caching.",[2031,16906,16908],{"id":16907},"_71-writes-pre-check-first-then-a-rollback-guarded-update","7.1 Writes: pre-check first, then a rollback-guarded update",[17,16910,16911,16912,7048,16914,16917],{},"Tenant-level credentials (",[100,16913,16852],{},[100,16915,16916],{},"access_token",") live in the database, not in code and not in the repository. When writing credentials for a tenant, I do it in two steps:",[312,16919,16920,16928],{},[315,16921,16922,16927],{},[49,16923,16924,16925],{},"Pre-check with a ",[100,16926,8824],{},": confirm the number is not already used by another tenant; the expected result is empty. One number per tenant is the premise the reverse lookup rests on, and once the mapping is duplicated, messages get routed to the wrong tenant.",[315,16929,16930,16936,16937,16940],{},[49,16931,16932,16933],{},"A rollback-guarded ",[100,16934,16935],{},"UPDATE",": run the update inside a transaction and ",[49,16938,16939],{},"commit only if exactly one row was affected","; otherwise roll back. With a wrong condition, zero affected rows means nothing changed and several affected rows is an incident, and neither should be committed.",[2031,16942,16944],{"id":16943},"_72-caching-clear-it-after-changing-the-database","7.2 Caching: clear it after changing the database",[17,16946,4203,16947,16950,16951,16954],{},[100,16948,16949],{},"phone_number_id → tenant_id"," lookup result is cached for 24 hours on a hit, so that not every message queries the database. The cost is that ",[49,16952,16953],{},"if you change the credentials in the database without clearing the cache, the new credentials can take up to 24 hours to take effect."," What you see is \"the database is clearly correct, but production still uses the old value\", which is easy to mistake for one of the platform-side problems above. So treat the database change and clearing the matching cache key as two steps of a single operation, and put them on the same runbook.",[1940,16956],{},[58,16958,16960],{"id":16959},"_8-summary-a-debugging-checklist","8. Summary: a debugging checklist",[17,16962,16963],{},"When you hit \"the WhatsApp Cloud API webhook verifies but no messages arrive\", go in this order:",[312,16965,16966,16978,16987,17005,17011,17014,17020],{},[315,16967,16968,16973,16974,16977],{},[49,16969,16970,16971,16147],{},"Check ",[100,16972,16146],{}," If it is empty, that is the cause; a ",[100,16975,16976],{},"POST"," fixes it immediately. (90% of cases end here.)",[315,16979,16980,16981,16983,16984,16986],{},"Don't assume that it is automatic for test numbers and only production numbers need it. The subscription is a WABA-level relationship; it does not carry across environments, and someone may have configured it for you without recording it. Run ",[100,16982,16146],{}," against the production WABA and ",[100,16985,16976],{}," if it is missing.",[315,16988,16989,16990,16992,16993,3933,16995,16997,16998,17000,17001,3933,17003,8836],{},"Use ",[100,16991,3913],{}," to check the ",[100,16994,13735],{},[100,16996,3872],{}," of your ",[100,16999,16916],{}," (production needs ",[100,17002,16405],{},[100,17004,833],{},[315,17006,17007,17008,17010],{},"Judge signature verification from the ",[49,17009,16606],{},", not the status code, since a failed verification also returns 200.",[315,17012,17013],{},"Don't be sidetracked by the payment method warning. Replies inside the customer service window are free and need no payment method.",[315,17015,17016,17017,17019],{},"For a number that is \"not registered\", use the Cloud API ",[100,17018,16643],{}," (and set a PIN).",[315,17021,17022],{},"Never skip the real-device test. It is the only way to verify real delivery by Meta.",[2031,17024,17026],{"id":17025},"keep-the-three-subscriptions-straight","Keep the three \"subscriptions\" straight",[105,17028,17029,17041],{},[108,17030,17031],{},[111,17032,17033,17036,17039],{},[114,17034,17035],{},"Subscription",[114,17037,17038],{},"What it verifies",[114,17040,15901],{},[121,17042,17043,17056,17070],{},[111,17044,17045,17048,17053],{},[126,17046,17047],{},"① Webhook URL verification",[126,17049,17050,17051],{},"Callback URL reachable + ",[100,17052,15930],{},[126,17054,17055],{},"Your GET endpoint",[111,17057,17058,17064,17067],{},[126,17059,17060,17061,17063],{},"② ",[100,17062,4224],{}," field subscription",[126,17065,17066],{},"Which events the App wants",[126,17068,17069],{},"Checkbox in the console",[111,17071,17072,17079,17084],{},[126,17073,17074,17075],{},"③ ",[49,17076,17077],{},[100,17078,4220],{},[126,17080,17081],{},[49,17082,17083],{},"Routes WABA events to the App",[126,17085,17086],{},[49,17087,17088],{},"Graph API (the one most often missed)",[1036,17090,17091],{},[17,17092,17093,17096,17097,1312],{},[49,17094,17095],{},"One closing line",": in the WhatsApp Cloud API, \"verified\" only checks the URL, and \"delivered\" only means the message reached the other person's phone. Neither one means the callback will reach your backend. The switch that actually makes messages flow into your service is called ",[100,17098,4220],{},[1940,17100],{},[58,17102,17104],{"id":17103},"appendix-a-minimal-fastapi-webhook-you-can-run-as-is","Appendix: a minimal FastAPI webhook you can run as-is",[17,17106,17107,17108,6357,17111,17114,17115,17118,17119,17122],{},"Run ",[100,17109,17110],{},"pip install fastapi uvicorn",[100,17112,17113],{},"uvicorn app:app --port 8000"," to start it. It takes two environment variables: ",[100,17116,17117],{},"WA_VERIFY_TOKEN"," (the string you chose when configuring the webhook in Meta) and ",[100,17120,17121],{},"WA_APP_SECRET"," (the Meta App's App Secret, used for HMAC signature verification). It ties the points above into a runnable skeleton: echo the challenge on GET, verify the signature on POST, deduplicate idempotently, and return 200 within 5 seconds while processing asynchronously.",[191,17124,17126],{"className":384,"code":17125,"language":386,"meta":15,"style":15},"\"\"\"Minimal runnable WhatsApp Cloud API webhook  ·  uvicorn app:app --port 8000\"\"\"\nimport os, hmac, hashlib, asyncio, time, json, logging\nfrom fastapi import FastAPI, Request, Response\n\nlogging.basicConfig(level=logging.INFO)\nlogger = logging.getLogger(\"wa\")\nVERIFY_TOKEN = os.environ.get(\"WA_VERIFY_TOKEN\", \"\")   # chosen when configuring the webhook in Meta\nAPP_SECRET   = os.environ.get(\"WA_APP_SECRET\", \"\")     # Meta App → App Secret\napp = FastAPI()\n\n_seen = {}  # in-memory dedup (use Redis with a 60s expiry in production)\ndef already_processed(msg_id, ttl=60):\n    now = time.time()\n    for k in [k for k, t in _seen.items() if now - t > ttl]:\n        _seen.pop(k, None)\n    if msg_id in _seen:\n        return True\n    _seen[msg_id] = now\n    return False\n\n\n@app.get(\"\u002Fwebhooks\u002Fwhatsapp\")\nasync def verify(request: Request):\n    p = request.query_params\n    if p.get(\"hub.mode\") == \"subscribe\" and p.get(\"hub.verify_token\") == VERIFY_TOKEN:\n        return Response(content=p.get(\"hub.challenge\", \"\"), media_type=\"text\u002Fplain\")\n    return Response(status_code=403)\n\n\n@app.post(\"\u002Fwebhooks\u002Fwhatsapp\")\nasync def receive(request: Request):\n    body = await request.body()\n    if APP_SECRET:  # HMAC check: return 200 even on failure to avoid a retry storm; rely on logs\n        expected = \"sha256=\" + hmac.new(APP_SECRET.encode(), body, hashlib.sha256).hexdigest()\n        if not hmac.compare_digest(request.headers.get(\"X-Hub-Signature-256\", \"\"), expected):\n            logger.warning(\"[WA] HMAC signature verification failed\")\n            return {\"status\": \"ok\"}\n    try:\n        payload = json.loads(body)\n    except Exception as e:\n        logger.error(f\"[WA] failed to parse payload: {e}\")\n        return {\"status\": \"ok\"}\n    for entry in payload.get(\"entry\", []):\n        for change in entry.get(\"changes\", []):\n            value = change.get(\"value\", {})\n            metadata = value.get(\"metadata\", {})            # contains phone_number_id (the basis for multi-tenant routing)\n            for msg in value.get(\"messages\", []) or []:\n                if already_processed(msg[\"id\"]):\n                    continue\n                asyncio.create_task(handle_message(msg, metadata))\n    return {\"status\": \"ok\"}                                  # 200 right away, within 5 seconds\n\n\nasync def handle_message(msg, metadata):\n    \"\"\"Slow business logic (LLM calls \u002F DB queries \u002F replies) goes here, outside the 5s window\"\"\"\n    try:\n        t = msg.get(\"type\")\n        text = msg.get(\"text\", {}).get(\"body\", \"\") if t == \"text\" else f\"\u003C{t}>\"\n        logger.info(f\"[WA] inbound from={msg.get('from')} type={t} text={text!r} \"\n                    f\"pnid={metadata.get('phone_number_id')}\")\n        # TODO: your business logic \u002F reply via the Graph API\n    except Exception:\n        logger.exception(\"[WA] error while handling message\")\n",[100,17127,17128,17133,17138,17143,17147,17152,17157,17162,17167,17172,17176,17181,17186,17191,17196,17201,17206,17210,17215,17220,17224,17228,17233,17238,17243,17248,17253,17257,17261,17265,17270,17275,17279,17284,17289,17294,17299,17304,17308,17313,17318,17323,17329,17335,17341,17347,17353,17359,17365,17371,17377,17383,17388,17393,17399,17405,17410,17416,17422,17428,17434,17440,17446],{"__ignoreMap":15},[199,17129,17130],{"class":201,"line":202},[199,17131,17132],{},"\"\"\"Minimal runnable WhatsApp Cloud API webhook  ·  uvicorn app:app --port 8000\"\"\"\n",[199,17134,17135],{"class":201,"line":25},[199,17136,17137],{},"import os, hmac, hashlib, asyncio, time, json, logging\n",[199,17139,17140],{"class":201,"line":213},[199,17141,17142],{},"from fastapi import FastAPI, Request, Response\n",[199,17144,17145],{"class":201,"line":219},[199,17146,461],{"emptyLinePlaceholder":30},[199,17148,17149],{"class":201,"line":225},[199,17150,17151],{},"logging.basicConfig(level=logging.INFO)\n",[199,17153,17154],{"class":201,"line":231},[199,17155,17156],{},"logger = logging.getLogger(\"wa\")\n",[199,17158,17159],{"class":201,"line":237},[199,17160,17161],{},"VERIFY_TOKEN = os.environ.get(\"WA_VERIFY_TOKEN\", \"\")   # chosen when configuring the webhook in Meta\n",[199,17163,17164],{"class":201,"line":243},[199,17165,17166],{},"APP_SECRET   = os.environ.get(\"WA_APP_SECRET\", \"\")     # Meta App → App Secret\n",[199,17168,17169],{"class":201,"line":249},[199,17170,17171],{},"app = FastAPI()\n",[199,17173,17174],{"class":201,"line":255},[199,17175,461],{"emptyLinePlaceholder":30},[199,17177,17178],{"class":201,"line":261},[199,17179,17180],{},"_seen = {}  # in-memory dedup (use Redis with a 60s expiry in production)\n",[199,17182,17183],{"class":201,"line":267},[199,17184,17185],{},"def already_processed(msg_id, ttl=60):\n",[199,17187,17188],{"class":201,"line":273},[199,17189,17190],{},"    now = time.time()\n",[199,17192,17193],{"class":201,"line":279},[199,17194,17195],{},"    for k in [k for k, t in _seen.items() if now - t > ttl]:\n",[199,17197,17198],{"class":201,"line":285},[199,17199,17200],{},"        _seen.pop(k, None)\n",[199,17202,17203],{"class":201,"line":651},[199,17204,17205],{},"    if msg_id in _seen:\n",[199,17207,17208],{"class":201,"line":970},[199,17209,4025],{},[199,17211,17212],{"class":201,"line":976},[199,17213,17214],{},"    _seen[msg_id] = now\n",[199,17216,17217],{"class":201,"line":982},[199,17218,17219],{},"    return False\n",[199,17221,17222],{"class":201,"line":988},[199,17223,461],{"emptyLinePlaceholder":30},[199,17225,17226],{"class":201,"line":994},[199,17227,461],{"emptyLinePlaceholder":30},[199,17229,17230],{"class":201,"line":2371},[199,17231,17232],{},"@app.get(\"\u002Fwebhooks\u002Fwhatsapp\")\n",[199,17234,17235],{"class":201,"line":2377},[199,17236,17237],{},"async def verify(request: Request):\n",[199,17239,17240],{"class":201,"line":2383},[199,17241,17242],{},"    p = request.query_params\n",[199,17244,17245],{"class":201,"line":2389},[199,17246,17247],{},"    if p.get(\"hub.mode\") == \"subscribe\" and p.get(\"hub.verify_token\") == VERIFY_TOKEN:\n",[199,17249,17250],{"class":201,"line":2395},[199,17251,17252],{},"        return Response(content=p.get(\"hub.challenge\", \"\"), media_type=\"text\u002Fplain\")\n",[199,17254,17255],{"class":201,"line":2401},[199,17256,16357],{},[199,17258,17259],{"class":201,"line":2407},[199,17260,461],{"emptyLinePlaceholder":30},[199,17262,17263],{"class":201,"line":3331},[199,17264,461],{"emptyLinePlaceholder":30},[199,17266,17267],{"class":201,"line":3337},[199,17268,17269],{},"@app.post(\"\u002Fwebhooks\u002Fwhatsapp\")\n",[199,17271,17272],{"class":201,"line":3343},[199,17273,17274],{},"async def receive(request: Request):\n",[199,17276,17277],{"class":201,"line":3349},[199,17278,16762],{},[199,17280,17281],{"class":201,"line":3355},[199,17282,17283],{},"    if APP_SECRET:  # HMAC check: return 200 even on failure to avoid a retry storm; rely on logs\n",[199,17285,17286],{"class":201,"line":3361},[199,17287,17288],{},"        expected = \"sha256=\" + hmac.new(APP_SECRET.encode(), body, hashlib.sha256).hexdigest()\n",[199,17290,17291],{"class":201,"line":3367},[199,17292,17293],{},"        if not hmac.compare_digest(request.headers.get(\"X-Hub-Signature-256\", \"\"), expected):\n",[199,17295,17296],{"class":201,"line":3373},[199,17297,17298],{},"            logger.warning(\"[WA] HMAC signature verification failed\")\n",[199,17300,17301],{"class":201,"line":3379},[199,17302,17303],{},"            return {\"status\": \"ok\"}\n",[199,17305,17306],{"class":201,"line":3385},[199,17307,4030],{},[199,17309,17310],{"class":201,"line":3391},[199,17311,17312],{},"        payload = json.loads(body)\n",[199,17314,17315],{"class":201,"line":3397},[199,17316,17317],{},"    except Exception as e:\n",[199,17319,17320],{"class":201,"line":3403},[199,17321,17322],{},"        logger.error(f\"[WA] failed to parse payload: {e}\")\n",[199,17324,17326],{"class":201,"line":17325},42,[199,17327,17328],{},"        return {\"status\": \"ok\"}\n",[199,17330,17332],{"class":201,"line":17331},43,[199,17333,17334],{},"    for entry in payload.get(\"entry\", []):\n",[199,17336,17338],{"class":201,"line":17337},44,[199,17339,17340],{},"        for change in entry.get(\"changes\", []):\n",[199,17342,17344],{"class":201,"line":17343},45,[199,17345,17346],{},"            value = change.get(\"value\", {})\n",[199,17348,17350],{"class":201,"line":17349},46,[199,17351,17352],{},"            metadata = value.get(\"metadata\", {})            # contains phone_number_id (the basis for multi-tenant routing)\n",[199,17354,17356],{"class":201,"line":17355},47,[199,17357,17358],{},"            for msg in value.get(\"messages\", []) or []:\n",[199,17360,17362],{"class":201,"line":17361},48,[199,17363,17364],{},"                if already_processed(msg[\"id\"]):\n",[199,17366,17368],{"class":201,"line":17367},49,[199,17369,17370],{},"                    continue\n",[199,17372,17374],{"class":201,"line":17373},50,[199,17375,17376],{},"                asyncio.create_task(handle_message(msg, metadata))\n",[199,17378,17380],{"class":201,"line":17379},51,[199,17381,17382],{},"    return {\"status\": \"ok\"}                                  # 200 right away, within 5 seconds\n",[199,17384,17386],{"class":201,"line":17385},52,[199,17387,461],{"emptyLinePlaceholder":30},[199,17389,17391],{"class":201,"line":17390},53,[199,17392,461],{"emptyLinePlaceholder":30},[199,17394,17396],{"class":201,"line":17395},54,[199,17397,17398],{},"async def handle_message(msg, metadata):\n",[199,17400,17402],{"class":201,"line":17401},55,[199,17403,17404],{},"    \"\"\"Slow business logic (LLM calls \u002F DB queries \u002F replies) goes here, outside the 5s window\"\"\"\n",[199,17406,17408],{"class":201,"line":17407},56,[199,17409,4030],{},[199,17411,17413],{"class":201,"line":17412},57,[199,17414,17415],{},"        t = msg.get(\"type\")\n",[199,17417,17419],{"class":201,"line":17418},58,[199,17420,17421],{},"        text = msg.get(\"text\", {}).get(\"body\", \"\") if t == \"text\" else f\"\u003C{t}>\"\n",[199,17423,17425],{"class":201,"line":17424},59,[199,17426,17427],{},"        logger.info(f\"[WA] inbound from={msg.get('from')} type={t} text={text!r} \"\n",[199,17429,17431],{"class":201,"line":17430},60,[199,17432,17433],{},"                    f\"pnid={metadata.get('phone_number_id')}\")\n",[199,17435,17437],{"class":201,"line":17436},61,[199,17438,17439],{},"        # TODO: your business logic \u002F reply via the Graph API\n",[199,17441,17443],{"class":201,"line":17442},62,[199,17444,17445],{},"    except Exception:\n",[199,17447,17449],{"class":201,"line":17448},63,[199,17450,17451],{},"        logger.exception(\"[WA] error while handling message\")\n",[43,17453,17454],{},[17,17455,17456,17457,6340,17459,17462],{},"Deduplication here uses an in-memory dict for demonstration; use Redis (with a 60s expiry) in production. The ",[100,17458,16852],{},[100,17460,17461],{},"metadata"," is the basis for multi-tenant routing: when one number serves one tenant, use it to look up which tenant the message belongs to (see section 7).",[1042,17464,17465],{},"html .light .shiki span {color: var(--shiki-light);background: var(--shiki-light-bg);font-style: var(--shiki-light-font-style);font-weight: var(--shiki-light-font-weight);text-decoration: var(--shiki-light-text-decoration);}html.light .shiki span {color: var(--shiki-light);background: var(--shiki-light-bg);font-style: var(--shiki-light-font-style);font-weight: var(--shiki-light-font-weight);text-decoration: var(--shiki-light-text-decoration);}html .default .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html.dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html pre.shiki code .shcOC, html code.shiki .shcOC{--shiki-light:#6F42C1;--shiki-default:#B392F0;--shiki-dark:#B392F0}html pre.shiki code .suiK_, html code.shiki .suiK_{--shiki-light:#005CC5;--shiki-default:#79B8FF;--shiki-dark:#79B8FF}html pre.shiki code .sfrk1, html code.shiki .sfrk1{--shiki-light:#032F62;--shiki-default:#9ECBFF;--shiki-dark:#9ECBFF}html pre.shiki code .sCsY4, html code.shiki .sCsY4{--shiki-light:#6A737D;--shiki-default:#6A737D;--shiki-dark:#6A737D}",{"title":15,"searchDepth":25,"depth":25,"links":17467},[17468,17469,17472,17473,17477,17484,17492,17496,17499],{"id":15832,"depth":25,"text":15833},{"id":15879,"depth":25,"text":15880,"children":17470},[17471],{"id":16071,"depth":213,"text":16072},{"id":16084,"depth":25,"text":16085},{"id":16136,"depth":25,"text":16137,"children":17474},[17475,17476],{"id":16150,"depth":213,"text":16151},{"id":16194,"depth":213,"text":16195},{"id":16250,"depth":25,"text":16251,"children":17478},[17479,17480,17482,17483],{"id":16261,"depth":213,"text":16262},{"id":16369,"depth":213,"text":17481},"5.2 Layer two: verify your access_token with debug_token",{"id":16434,"depth":213,"text":16435},{"id":16539,"depth":213,"text":16540},{"id":16580,"depth":25,"text":16581,"children":17485},[17486,17487,17488,17490,17491],{"id":16587,"depth":213,"text":16588},{"id":16613,"depth":213,"text":16614},{"id":16639,"depth":213,"text":17489},"6.3 Number \"pending review\" or \"not registered\": use the Cloud API \u002Fregister, and it isn't a payment problem either",{"id":16710,"depth":213,"text":16711},{"id":16730,"depth":213,"text":16731},{"id":16812,"depth":25,"text":16813,"children":17493},[17494,17495],{"id":16907,"depth":213,"text":16908},{"id":16943,"depth":213,"text":16944},{"id":16959,"depth":25,"text":16960,"children":17497},[17498],{"id":17025,"depth":213,"text":17026},{"id":17103,"depth":25,"text":17104},"2026-06-12","The Meta console says the webhook is verified and the test message shows as delivered, yet the backend never receives a callback. This post untangles three different things in the WhatsApp Cloud API that are all called a subscription, and lays out a layered way to debug without guessing.","\u002Farticles\u002Fwhatsapp-webhook-subscriptions.svg",{},"\u002Farticles\u002Fwhatsapp-webhook-subscriptions","15",{"title":15809,"description":17501},{"loc":17504},"articles\u002Fwhatsapp-webhook-subscriptions",[3049,7012],"LnMsobj49VI-YV9ApsO2WquzQa2WdOnlr8Ze9J5fLDQ",1795761649142]