diff --git a/docs/consultant-review/AUDIT-TRACKER.md b/docs/consultant-review/AUDIT-TRACKER.md index 5022899..f858dc0 100644 --- a/docs/consultant-review/AUDIT-TRACKER.md +++ b/docs/consultant-review/AUDIT-TRACKER.md @@ -1,7 +1,7 @@ # 全站文章顾问审阅状态总控台 (Audit Tracker) -> **最后同步时间**:2026-10-27 04:09:14 -> **全站总文章数**:91 篇 | **已审批完成**:29 篇 (31.9%) | **待审阅**:62 篇 +> **最后同步时间**:2026-10-27 04:23:31 +> **全站总文章数**:91 篇 | **已审批完成**:39 篇 (42.9%) | **待审阅**:52 篇 ## 一、操作命令速查 - `python scripts/manage_review.py list` — 查看待审与已审概览 @@ -29,16 +29,16 @@ | 15 | `case-studies` | `how-i-built-the-digikedai-telegram-bot` | 我是如何构建 DigiKedai Telegram AI 客服机器人的 | ⏳ 待审阅 | Batch-01 | - | | | 16 | `case-studies` | `how-i-host-this-blog` | 我是如何托管这个博客的:Astro、Gitea Actions 与自托管 CI/CD | ⏳ 待审阅 | Batch-01 | - | | | 17 | `case-studies` | `how-i-made-my-own-songs-with-suno-ai` | 我用 Suno AI 做出自己的歌 | ⏳ 待审阅 | Batch-01 | - | | -| 18 | `case-studies` | `how-i-vetted-20-vps-providers-with-parallel-subagents` | 如何用并行子代理在三小时内核查 20 家 VPS 服务商 | ⏳ 待审阅 | Batch-02 | - | | -| 19 | `case-studies` | `loop-engineering-without-a-coding-agent` | 没有 Coding Agent 的 Loop Engineering:撑起我这套基础设施的 11 个定时任务 | ⏳ 待审阅 | Batch-02 | - | | -| 20 | `case-studies` | `one-prometheus-for-unraid-synology-and-a-vps` | 用一个 Prometheus 监控 unRaid、群晖 NAS 和 VPS:我做错的四件事 | ⏳ 待审阅 | Batch-02 | - | | -| 21 | `case-studies` | `running-production-infrastructure-solo` | 一个人跑生产基础设施:三台主机、162 个容器 | ⏳ 待审阅 | Batch-02 | - | | -| 22 | `case-studies` | `self-healing-digital-goods-entitlements` | 数字商品的自愈式访问控制:NocoDB、n8n 与 AList | ⏳ 待审阅 | Batch-02 | - | | -| 23 | `case-studies` | `self-hosted-speech-to-text-api` | 自建语音转文字服务:打字速度的 3 倍以上,而且数据不出内网 | ⏳ 待审阅 | Batch-02 | - | | -| 24 | `case-studies` | `self-hosted-tts-cosyvoice2-n8n-gpu` | 从云端转本地:在 12GB 显卡与群晖 N8N 上搭建中英混读高保真 TTS 语音栈 | ⏳ 待审阅 | Batch-02 | - | | -| 25 | `case-studies` | `self-hosting-mem0-memory-stack` | 我如何在私有存储节点上自托管 Mem0 记忆栈(让 AI 助手拥有持久记忆) | ⏳ 待审阅 | Batch-02 | - | | -| 26 | `case-studies` | `shipping-an-ai-photo-editor-as-a-wordpress-plugin` | 把 AI 修图工具做成 WordPress 插件:22 个版本换来的经验 | ⏳ 待审阅 | Batch-02 | - | | -| 27 | `case-studies` | `syncing-a-self-improving-ai-agent-across-machines` | 在多台机器之间同步一个会自我学习的 AI Agent | ⏳ 待审阅 | Batch-02 | - | | +| 18 | `case-studies` | `how-i-vetted-20-vps-providers-with-parallel-subagents` | 如何用并行子代理在三小时内核查 20 家 VPS 服务商 | ✅ 已通过 | Batch-02 | 2026-10-27 04:22 | 外部顾问审阅完成,已采纳并落地全量修改意见(含数字矛盾/OPSEC脱敏/双语CTA/架构蓝图对齐/排版折叠) | +| 19 | `case-studies` | `loop-engineering-without-a-coding-agent` | 没有 Coding Agent 的 Loop Engineering:撑起我这套基础设施的 11 个定时任务 | ✅ 已通过 | Batch-02 | 2026-10-27 04:22 | 外部顾问审阅完成,已采纳并落地全量修改意见(含数字矛盾/OPSEC脱敏/双语CTA/架构蓝图对齐/排版折叠) | +| 20 | `case-studies` | `one-prometheus-for-unraid-synology-and-a-vps` | 用一个 Prometheus 监控 unRaid、群晖 NAS 和 VPS:我做错的四件事 | ✅ 已通过 | Batch-02 | 2026-10-27 04:22 | 外部顾问审阅完成,已采纳并落地全量修改意见(含数字矛盾/OPSEC脱敏/双语CTA/架构蓝图对齐/排版折叠) | +| 21 | `case-studies` | `running-production-infrastructure-solo` | 一个人跑生产基础设施:三台主机、162 个容器 | ✅ 已通过 | Batch-02 | 2026-10-27 04:22 | 外部顾问审阅完成,已采纳并落地全量修改意见(含数字矛盾/OPSEC脱敏/双语CTA/架构蓝图对齐/排版折叠) | +| 22 | `case-studies` | `self-healing-digital-goods-entitlements` | 数字商品的自愈式访问控制:NocoDB、n8n 与 AList | ✅ 已通过 | Batch-02 | 2026-10-27 04:22 | 外部顾问审阅完成,已采纳并落地全量修改意见(含数字矛盾/OPSEC脱敏/双语CTA/架构蓝图对齐/排版折叠) | +| 23 | `case-studies` | `self-hosted-speech-to-text-api` | 自建语音转文字服务:打字速度的 3 倍以上,而且数据不出内网 | ✅ 已通过 | Batch-02 | 2026-10-27 04:22 | 外部顾问审阅完成,已采纳并落地全量修改意见(含数字矛盾/OPSEC脱敏/双语CTA/架构蓝图对齐/排版折叠) | +| 24 | `case-studies` | `self-hosted-tts-cosyvoice2-n8n-gpu` | 从云端转本地:在 12GB 显卡与群晖 N8N 上搭建中英混读高保真 TTS 语音栈 | ✅ 已通过 | Batch-02 | 2026-10-27 04:22 | 外部顾问审阅完成,已采纳并落地全量修改意见(含数字矛盾/OPSEC脱敏/双语CTA/架构蓝图对齐/排版折叠) | +| 25 | `case-studies` | `self-hosting-mem0-memory-stack` | 我如何在私有存储节点上自托管 Mem0 记忆栈(让 AI 助手拥有持久记忆) | ✅ 已通过 | Batch-02 | 2026-10-27 04:22 | 外部顾问审阅完成,已采纳并落地全量修改意见(含数字矛盾/OPSEC脱敏/双语CTA/架构蓝图对齐/排版折叠) | +| 26 | `case-studies` | `shipping-an-ai-photo-editor-as-a-wordpress-plugin` | 把 AI 修图工具做成 WordPress 插件:22 个版本换来的经验 | ✅ 已通过 | Batch-02 | 2026-10-27 04:22 | 外部顾问审阅完成,已采纳并落地全量修改意见(含数字矛盾/OPSEC脱敏/双语CTA/架构蓝图对齐/排版折叠) | +| 27 | `case-studies` | `syncing-a-self-improving-ai-agent-across-machines` | 在多台机器之间同步一个会自我学习的 AI Agent | ✅ 已通过 | Batch-02 | 2026-10-27 04:22 | 外部顾问审阅完成,已采纳并落地全量修改意见(含数字矛盾/OPSEC脱敏/双语CTA/架构蓝图对齐/排版折叠) | | 28 | `case-studies` | `the-single-writer-rule-for-coding-agents` | 代码只让一个 AI 改:我是如何避开多 Agent 协同踩坑的「单写多审」架构 | ✅ 已通过 | Batch-03 | 2026-10-27 03:49 | 外部顾问审阅完成,已采纳并落地全量修改意见 | | 29 | `case-studies` | `when-to-give-your-agent-physical-clicks` | 什么时候该让 AI 操控物理鼠标(以及什么时候绝对不要用) | ✅ 已通过 | Batch-03 | 2026-10-27 03:49 | 外部顾问审阅完成,已采纳并落地全量修改意见 | | 30 | `case-studies` | `why-i-built-a-video-knowledge-base` | 为什么我要做视频精读知识库:把收藏夹吃灰的短视频变成可检索笔记 | ✅ 已通过 | Batch-03 | 2026-10-27 03:49 | 外部顾问审阅完成,已采纳并落地全量修改意见 | @@ -59,47 +59,47 @@ | 45 | `devops` | `putting-a-front-door-on-an-app-you-cant-modify` | 给自己改不了源码的应用装一扇前门 | ✅ 已通过 | Batch-04 | 2026-10-27 04:09 | 外部顾问审阅完成,已采纳并落地全量修改意见(含数字矛盾/OPSEC脱敏/双语CTA/技术细节修补) | | 46 | `devops` | `read-only-nocodb-dashboard-for-a-remote-database` | 给另一台机器上的数据库配一个 NocoDB 只读看板 | ✅ 已通过 | Batch-04 | 2026-10-27 04:09 | 外部顾问审阅完成,已采纳并落地全量修改意见(含数字矛盾/OPSEC脱敏/双语CTA/技术细节修补) | | 47 | `devops` | `replacing-rdpguard-with-ipban` | 用 IPBan 替换 RDPGuard:没人写出来的三个坑 | ✅ 已通过 | Batch-04 | 2026-10-27 04:09 | 外部顾问审阅完成,已采纳并落地全量修改意见(含数字矛盾/OPSEC脱敏/双语CTA/技术细节修补) | -| 48 | `devops` | `space-reclamation-wasnt-stuck-it-was-waiting` | 空间回收没卡住,它只是在等明天早上 09:29 | ⏳ 待审阅 | Batch-05 | - | | -| 49 | `devops` | `synology-spreadsheet-api-is-a-container` | Synology 电子表格 API 是一个容器,不是一个 API 端点 | ⏳ 待审阅 | Batch-05 | - | | -| 50 | `devops` | `that-dying-ssd-was-just-a-bad-sata-cable` | 我差点把这颗 SSD 送修——真正坏的是 SATA 数据线 | ⏳ 待审阅 | Batch-05 | - | | -| 51 | `devops` | `the-cause-was-trim-not-the-ssds` | 换了不同的硬盘,同样的损坏又来了——真凶是 TRIM,不是 SSD | ⏳ 待审阅 | Batch-05 | - | | -| 52 | `devops` | `the-upstream-was-deleted-then-came-back-rewritten` | 上游被删了,然后带着一个重写版回来 | ⏳ 待审阅 | Batch-05 | - | | -| 53 | `devops` | `unraid-stop-array-hangs-on-swapfile` | Unraid 停止阵列时卡死的真相:Swapfile 锁住挂载点 — 附修复方案 | ⏳ 待审阅 | Batch-05 | - | | -| 54 | `devops` | `uploading-large-videos-to-youtube-via-cdp` | 用 CDP 自动化上传百兆视频到 YouTube:跨越 DevTools 内存墙的 Docker 归档法 | ⏳ 待审阅 | Batch-05 | - | | -| 55 | `devops` | `vetting-an-open-source-dependency-before-you-bet-on-it` | 如何在押注前验证一个开源依赖:我用的六项检查 | ⏳ 待审阅 | Batch-05 | - | | -| 56 | `devops` | `when-smart-says-healthy-but-your-raid-is-corrupting-data` | SMART 显示健康,RAID 却在悄悄损坏数据 | ⏳ 待审阅 | Batch-05 | - | | -| 57 | `devops` | `why-chrome-forgets-its-tabs-in-a-container` | 为什么容器里的 Chrome 会忘记标签页 —— 以及我是怎么修好的 | ⏳ 待审阅 | Batch-05 | - | | -| 58 | `devops` | `why-telegram-bot-notifications-die` | Telegram 机器人通知为什么发不出去:IPv6、DNS 和一个折腾了一整天的 400 | ⏳ 待审阅 | Batch-05 | - | | -| 59 | `devops` | `why-your-cdp-clicks-silently-fail` | 为什么你的 CDP 点击会静默失效:平滑滚动、最小化窗口与 JS 派发事件 | ⏳ 待审阅 | Batch-06 | - | | -| 60 | `devops` | `why-your-grafana-dashboard-shows-no-data` | Prometheus 明明有数据,Grafana 面板却全是 No data 的原因 | ⏳ 待审阅 | Batch-06 | - | | -| 61 | `devops` | `your-disk-full-alert-is-lying` | 你的“磁盘将满”告警在说谎:别再按百分比告警 | ⏳ 待审阅 | Batch-06 | - | | -| 62 | `engineering` | `adding-english-mode-to-a-chinese-only-web-app` | 浏览器翻译没有 API:我给一个纯中文网页应用加上了英文模式 | ⏳ 待审阅 | Batch-06 | - | | -| 63 | `engineering` | `debugging-remotion-video-jitter` | 排查 Remotion 视频抽搐:为什么在背景图挂载音频低频 Scale 会毁了转场 | ⏳ 待审阅 | Batch-06 | - | | -| 64 | `engineering` | `embedding-fonts-so-a-pdf-looks-the-same-everywhere` | 把字体嵌进 PDF,让它在任何机器上都长一样 | ⏳ 待审阅 | Batch-06 | - | | -| 65 | `engineering` | `jpa-version-field-lost-update` | 那个把静默丢失更新变成 409 的 JPA 字段:@Version 乐观锁 | ⏳ 待审阅 | Batch-06 | - | | -| 66 | `engineering` | `migrating-codeigniter-iis-to-openlitespeed` | 把 CodeIgniter 4 应用从 IIS 迁移到 OpenLiteSpeed | ⏳ 待审阅 | Batch-06 | - | | -| 67 | `engineering` | `scraping-bot-walled-marketplace-warm-browser-session` | 用「热浏览器会话」爬取有反爬墙的电商网站 | ⏳ 待审阅 | Batch-06 | - | | -| 68 | `engineering` | `two-ways-a-javascript-file-stops-working-and-looks-fine` | JavaScript 文件静默失效的两种方式:而页面看上去一切正常 | ⏳ 待审阅 | Batch-06 | - | | -| 69 | `engineering` | `verifying-a-pdf-report-page-by-page` | 逐页验证一份 19 页的 PDF 报告 | ⏳ 待审阅 | Batch-06 | - | | -| 70 | `engineering` | `why-500000-lines-of-commit-churn-only-left-230000-in-production` | 30 天提交 51.8 万行,生产环境只留下 23.5 万行 | ⏳ 待审阅 | Batch-07 | - | | -| 71 | `notes` | `adding-a-domain-to-someone-elses-mail-server` | 给别人家的邮件服务器加一个域名 | ⏳ 待审阅 | Batch-07 | - | | -| 72 | `notes` | `hello-world` | 你好,世界 —— 关于这个博客 | ⏳ 待审阅 | Batch-07 | - | | -| 73 | `notes` | `my-backup-was-using-someone-elses-api-quota` | 我的备份爬得比爬虫还慢,因为我在用别人的 API 配额 | ⏳ 待审阅 | Batch-07 | - | | -| 74 | `notes` | `nocodb-sso-is-a-licensed-feature` | NocoDB SSO 是授权功能:环境变量不会告诉你的事 | ⏳ 待审阅 | Batch-07 | - | | -| 75 | `notes` | `reading-a-containers-own-api-docs` | 与其看供应商文档,不如直接读容器自带的 API 文档 | ⏳ 待审阅 | Batch-07 | - | | -| 76 | `notes` | `smartctl-exit-code-32-skips-the-disks-that-matter` | smartctl 退出码 32:专门跳过你最该看的硬盘的那个“错误” | ⏳ 待审阅 | Batch-07 | - | | -| 77 | `notes` | `stop-writing-agent-prompts-for-deterministic-work` | 确定性的活,别再用 Agent Prompt 去跑 | ⏳ 待审阅 | Batch-07 | - | | -| 78 | `notes` | `synology-api-401-with-the-correct-password` | 密码正确,Synology API 登录却返回 401,问题出在哪 | ⏳ 待审阅 | Batch-07 | - | | -| 79 | `notes` | `the-nocodb-attachment-that-wouldnt-update` | NocoDB 附件字段怎么改都不生效,和一个漏网的正则 | ⏳ 待审阅 | Batch-07 | - | | -| 80 | `notes` | `upgrading-codeigniter-46-to-47` | CodeIgniter 4.6 升级到 4.7:官方指南没说到的破坏性变更 | ⏳ 待审阅 | Batch-07 | - | | -| 81 | `notes` | `why-is-my-tts-model-repeating-percent` | 为什么本地语音合成一直在念 “Percent”?语音管线里的 URL 编码与沙盒避坑记 | ⏳ 待审阅 | Batch-07 | - | | -| 82 | `notes` | `why-multi-agent-coding-fails` | 为什么多个 AI 一起写代码总会烂尾?传话失真与隐式决策困境 | ⏳ 待审阅 | Batch-07 | - | | -| 83 | `notes` | `why-your-windows-mcp-calls-silently-fail` | 为什么你的 Windows 桌面 MCP 调用会静默失败:攻破 10 秒空闲门禁与避坑实录 | ⏳ 待审阅 | Batch-07 | - | | -| 84 | `tutorials` | `calibrating-intel-quick-sync-hevc-quality` | 校准 Intel Quick Sync HEVC:28 与 30 之间的悬崖,和一个毫无作用的 preset | ⏳ 待审阅 | Batch-07 | - | | -| 85 | `tutorials` | `does-hevc-actually-shrink-your-files` | 转成 HEVC 到底会不会让文件变小?我实测了 | ⏳ 待审阅 | Batch-07 | - | | -| 86 | `tutorials` | `generating-full-length-songs-with-yue2-comfyui` | 用 YuE2 BF16 生成完整长歌:突破时长限制与音频硬截断 | ⏳ 待审阅 | Batch-09 | - | | -| 87 | `tutorials` | `generating-subtitles-for-songs-without-timestamps` | 给没有时间戳的歌曲自动生成字幕 | ⏳ 待审阅 | Batch-10 | - | | -| 88 | `tutorials` | `how-to-verify-a-hosting-provider-before-you-buy` | 购买主机前,如何核实一家服务商的真实情况 | ⏳ 待审阅 | Batch-10 | - | | -| 89 | `web3` | `chainlink-vrf-v2-lottery-contract` | 一个基于 Chainlink VRF v2.5 与 Automation 的自动化彩票合约 | ⏳ 待审阅 | Batch-10 | - | | -| 90 | `web3` | `fully-on-chain-svg-nfts` | 全链上 SVG NFT:把艺术作品放进合约里 | ⏳ 待审阅 | Batch-10 | - | | -| 91 | `web3` | `why-my-on-chain-nft-art-changed-on-windows` | 为什么在 Windows 上克隆后,我的链上 NFT 图像变了 | ⏳ 待审阅 | Batch-10 | - | | +| 48 | `devops` | `space-reclamation-wasnt-stuck-it-was-waiting` | 空间回收没卡住,它只是在等明天早上 09:29 | ⏳ 待审阅 | Batch-02 | - | | +| 49 | `devops` | `synology-spreadsheet-api-is-a-container` | Synology 电子表格 API 是一个容器,不是一个 API 端点 | ⏳ 待审阅 | Batch-02 | - | | +| 50 | `devops` | `that-dying-ssd-was-just-a-bad-sata-cable` | 我差点把这颗 SSD 送修——真正坏的是 SATA 数据线 | ⏳ 待审阅 | Batch-02 | - | | +| 51 | `devops` | `the-cause-was-trim-not-the-ssds` | 换了不同的硬盘,同样的损坏又来了——真凶是 TRIM,不是 SSD | ⏳ 待审阅 | Batch-02 | - | | +| 52 | `devops` | `the-upstream-was-deleted-then-came-back-rewritten` | 上游被删了,然后带着一个重写版回来 | ⏳ 待审阅 | Batch-02 | - | | +| 53 | `devops` | `unraid-stop-array-hangs-on-swapfile` | Unraid 停止阵列时卡死的真相:Swapfile 锁住挂载点 — 附修复方案 | ⏳ 待审阅 | Batch-02 | - | | +| 54 | `devops` | `uploading-large-videos-to-youtube-via-cdp` | 用 CDP 自动化上传百兆视频到 YouTube:跨越 DevTools 内存墙的 Docker 归档法 | ⏳ 待审阅 | Batch-02 | - | | +| 55 | `devops` | `vetting-an-open-source-dependency-before-you-bet-on-it` | 如何在押注前验证一个开源依赖:我用的六项检查 | ⏳ 待审阅 | Batch-02 | - | | +| 56 | `devops` | `when-smart-says-healthy-but-your-raid-is-corrupting-data` | SMART 显示健康,RAID 却在悄悄损坏数据 | ⏳ 待审阅 | Batch-02 | - | | +| 57 | `devops` | `why-chrome-forgets-its-tabs-in-a-container` | 为什么容器里的 Chrome 会忘记标签页 —— 以及我是怎么修好的 | ⏳ 待审阅 | Batch-02 | - | | +| 58 | `devops` | `why-telegram-bot-notifications-die` | Telegram 机器人通知为什么发不出去:IPv6、DNS 和一个折腾了一整天的 400 | ⏳ 待审阅 | Batch-02 | - | | +| 59 | `devops` | `why-your-cdp-clicks-silently-fail` | 为什么你的 CDP 点击会静默失效:平滑滚动、最小化窗口与 JS 派发事件 | ⏳ 待审阅 | Batch-03 | - | | +| 60 | `devops` | `why-your-grafana-dashboard-shows-no-data` | Prometheus 明明有数据,Grafana 面板却全是 No data 的原因 | ⏳ 待审阅 | Batch-03 | - | | +| 61 | `devops` | `your-disk-full-alert-is-lying` | 你的“磁盘将满”告警在说谎:别再按百分比告警 | ⏳ 待审阅 | Batch-03 | - | | +| 62 | `engineering` | `adding-english-mode-to-a-chinese-only-web-app` | 浏览器翻译没有 API:我给一个纯中文网页应用加上了英文模式 | ⏳ 待审阅 | Batch-03 | - | | +| 63 | `engineering` | `debugging-remotion-video-jitter` | 排查 Remotion 视频抽搐:为什么在背景图挂载音频低频 Scale 会毁了转场 | ⏳ 待审阅 | Batch-03 | - | | +| 64 | `engineering` | `embedding-fonts-so-a-pdf-looks-the-same-everywhere` | 把字体嵌进 PDF,让它在任何机器上都长一样 | ⏳ 待审阅 | Batch-03 | - | | +| 65 | `engineering` | `jpa-version-field-lost-update` | 那个把静默丢失更新变成 409 的 JPA 字段:@Version 乐观锁 | ⏳ 待审阅 | Batch-03 | - | | +| 66 | `engineering` | `migrating-codeigniter-iis-to-openlitespeed` | 把 CodeIgniter 4 应用从 IIS 迁移到 OpenLiteSpeed | ⏳ 待审阅 | Batch-03 | - | | +| 67 | `engineering` | `scraping-bot-walled-marketplace-warm-browser-session` | 用「热浏览器会话」爬取有反爬墙的电商网站 | ⏳ 待审阅 | Batch-03 | - | | +| 68 | `engineering` | `two-ways-a-javascript-file-stops-working-and-looks-fine` | JavaScript 文件静默失效的两种方式:而页面看上去一切正常 | ⏳ 待审阅 | Batch-03 | - | | +| 69 | `engineering` | `verifying-a-pdf-report-page-by-page` | 逐页验证一份 19 页的 PDF 报告 | ⏳ 待审阅 | Batch-03 | - | | +| 70 | `engineering` | `why-500000-lines-of-commit-churn-only-left-230000-in-production` | 30 天提交 51.8 万行,生产环境只留下 23.5 万行 | ⏳ 待审阅 | Batch-04 | - | | +| 71 | `notes` | `adding-a-domain-to-someone-elses-mail-server` | 给别人家的邮件服务器加一个域名 | ⏳ 待审阅 | Batch-04 | - | | +| 72 | `notes` | `hello-world` | 你好,世界 —— 关于这个博客 | ⏳ 待审阅 | Batch-04 | - | | +| 73 | `notes` | `my-backup-was-using-someone-elses-api-quota` | 我的备份爬得比爬虫还慢,因为我在用别人的 API 配额 | ⏳ 待审阅 | Batch-04 | - | | +| 74 | `notes` | `nocodb-sso-is-a-licensed-feature` | NocoDB SSO 是授权功能:环境变量不会告诉你的事 | ⏳ 待审阅 | Batch-04 | - | | +| 75 | `notes` | `reading-a-containers-own-api-docs` | 与其看供应商文档,不如直接读容器自带的 API 文档 | ⏳ 待审阅 | Batch-04 | - | | +| 76 | `notes` | `smartctl-exit-code-32-skips-the-disks-that-matter` | smartctl 退出码 32:专门跳过你最该看的硬盘的那个“错误” | ⏳ 待审阅 | Batch-04 | - | | +| 77 | `notes` | `stop-writing-agent-prompts-for-deterministic-work` | 确定性的活,别再用 Agent Prompt 去跑 | ⏳ 待审阅 | Batch-04 | - | | +| 78 | `notes` | `synology-api-401-with-the-correct-password` | 密码正确,Synology API 登录却返回 401,问题出在哪 | ⏳ 待审阅 | Batch-04 | - | | +| 79 | `notes` | `the-nocodb-attachment-that-wouldnt-update` | NocoDB 附件字段怎么改都不生效,和一个漏网的正则 | ⏳ 待审阅 | Batch-04 | - | | +| 80 | `notes` | `upgrading-codeigniter-46-to-47` | CodeIgniter 4.6 升级到 4.7:官方指南没说到的破坏性变更 | ⏳ 待审阅 | Batch-04 | - | | +| 81 | `notes` | `why-is-my-tts-model-repeating-percent` | 为什么本地语音合成一直在念 “Percent”?语音管线里的 URL 编码与沙盒避坑记 | ⏳ 待审阅 | Batch-04 | - | | +| 82 | `notes` | `why-multi-agent-coding-fails` | 为什么多个 AI 一起写代码总会烂尾?传话失真与隐式决策困境 | ⏳ 待审阅 | Batch-04 | - | | +| 83 | `notes` | `why-your-windows-mcp-calls-silently-fail` | 为什么你的 Windows 桌面 MCP 调用会静默失败:攻破 10 秒空闲门禁与避坑实录 | ⏳ 待审阅 | Batch-04 | - | | +| 84 | `tutorials` | `calibrating-intel-quick-sync-hevc-quality` | 校准 Intel Quick Sync HEVC:28 与 30 之间的悬崖,和一个毫无作用的 preset | ⏳ 待审阅 | Batch-04 | - | | +| 85 | `tutorials` | `does-hevc-actually-shrink-your-files` | 转成 HEVC 到底会不会让文件变小?我实测了 | ⏳ 待审阅 | Batch-04 | - | | +| 86 | `tutorials` | `generating-full-length-songs-with-yue2-comfyui` | 用 YuE2 BF16 生成完整长歌:突破时长限制与音频硬截断 | ⏳ 待审阅 | Batch-06 | - | | +| 87 | `tutorials` | `generating-subtitles-for-songs-without-timestamps` | 给没有时间戳的歌曲自动生成字幕 | ⏳ 待审阅 | Batch-07 | - | | +| 88 | `tutorials` | `how-to-verify-a-hosting-provider-before-you-buy` | 购买主机前,如何核实一家服务商的真实情况 | ⏳ 待审阅 | Batch-07 | - | | +| 89 | `web3` | `chainlink-vrf-v2-lottery-contract` | 一个基于 Chainlink VRF v2.5 与 Automation 的自动化彩票合约 | ⏳ 待审阅 | Batch-07 | - | | +| 90 | `web3` | `fully-on-chain-svg-nfts` | 全链上 SVG NFT:把艺术作品放进合约里 | ⏳ 待审阅 | Batch-07 | - | | +| 91 | `web3` | `why-my-on-chain-nft-art-changed-on-windows` | 为什么在 Windows 上克隆后,我的链上 NFT 图像变了 | ⏳ 待审阅 | Batch-07 | - | | diff --git a/docs/consultant-review/audit-tracker.json b/docs/consultant-review/audit-tracker.json index acb4bb9..d62dad8 100644 --- a/docs/consultant-review/audit-tracker.json +++ b/docs/consultant-review/audit-tracker.json @@ -6,7 +6,7 @@ "category": "notes", "pub_date": "2025-05-06", "status": "pending", - "batch_id": "Batch-07", + "batch_id": "Batch-04", "approved_at": null, "notes": "", "en_chars": 7375, @@ -19,7 +19,7 @@ "category": "engineering", "pub_date": "2025-06-11", "status": "pending", - "batch_id": "Batch-06", + "batch_id": "Batch-03", "approved_at": null, "notes": "", "en_chars": 11859, @@ -110,7 +110,7 @@ "category": "tutorials", "pub_date": "2026-10-14", "status": "pending", - "batch_id": "Batch-07", + "batch_id": "Batch-04", "approved_at": null, "notes": "", "en_chars": 10490, @@ -123,7 +123,7 @@ "category": "web3", "pub_date": "2024-12-10", "status": "pending", - "batch_id": "Batch-10", + "batch_id": "Batch-07", "approved_at": null, "notes": "", "en_chars": 15801, @@ -136,7 +136,7 @@ "category": "engineering", "pub_date": "2025-11-26", "status": "pending", - "batch_id": "Batch-06", + "batch_id": "Batch-03", "approved_at": null, "notes": "", "en_chars": 9584, @@ -162,7 +162,7 @@ "category": "tutorials", "pub_date": "2026-10-08", "status": "pending", - "batch_id": "Batch-07", + "batch_id": "Batch-04", "approved_at": null, "notes": "", "en_chars": 7417, @@ -175,7 +175,7 @@ "category": "engineering", "pub_date": "2025-01-22", "status": "pending", - "batch_id": "Batch-06", + "batch_id": "Batch-03", "approved_at": null, "notes": "", "en_chars": 8033, @@ -227,7 +227,7 @@ "category": "web3", "pub_date": "2024-10-08", "status": "pending", - "batch_id": "Batch-10", + "batch_id": "Batch-07", "approved_at": null, "notes": "", "en_chars": 14598, @@ -240,7 +240,7 @@ "category": "tutorials", "pub_date": "2026-10-26", "status": "pending", - "batch_id": "Batch-09", + "batch_id": "Batch-06", "approved_at": null, "notes": "", "en_chars": 131667, @@ -253,7 +253,7 @@ "category": "tutorials", "pub_date": "2026-10-20", "status": "pending", - "batch_id": "Batch-10", + "batch_id": "Batch-07", "approved_at": null, "notes": "", "en_chars": 46399, @@ -292,7 +292,7 @@ "category": "notes", "pub_date": "2024-09-24", "status": "pending", - "batch_id": "Batch-07", + "batch_id": "Batch-04", "approved_at": null, "notes": "", "en_chars": 1794, @@ -356,10 +356,10 @@ "zh_title": "如何用并行子代理在三小时内核查 20 家 VPS 服务商", "category": "case-studies", "pub_date": "2025-11-12", - "status": "pending", + "status": "approved", "batch_id": "Batch-02", - "approved_at": null, - "notes": "", + "approved_at": "2026-10-27 04:22", + "notes": "外部顾问审阅完成,已采纳并落地全量修改意见(含数字矛盾/OPSEC脱敏/双语CTA/架构蓝图对齐/排版折叠)", "en_chars": 8593, "zh_chars": 3613 }, @@ -370,7 +370,7 @@ "category": "tutorials", "pub_date": "2025-11-26", "status": "pending", - "batch_id": "Batch-10", + "batch_id": "Batch-07", "approved_at": null, "notes": "", "en_chars": 6743, @@ -409,7 +409,7 @@ "category": "engineering", "pub_date": "2026-08-19", "status": "pending", - "batch_id": "Batch-06", + "batch_id": "Batch-03", "approved_at": null, "notes": "", "en_chars": 12217, @@ -421,10 +421,10 @@ "zh_title": "没有 Coding Agent 的 Loop Engineering:撑起我这套基础设施的 11 个定时任务", "category": "case-studies", "pub_date": "2026-10-01", - "status": "pending", + "status": "approved", "batch_id": "Batch-02", - "approved_at": null, - "notes": "", + "approved_at": "2026-10-27 04:22", + "notes": "外部顾问审阅完成,已采纳并落地全量修改意见(含数字矛盾/OPSEC脱敏/双语CTA/架构蓝图对齐/排版折叠)", "en_chars": 14249, "zh_chars": 6609 }, @@ -435,7 +435,7 @@ "category": "engineering", "pub_date": "2026-09-27", "status": "pending", - "batch_id": "Batch-06", + "batch_id": "Batch-03", "approved_at": null, "notes": "", "en_chars": 14943, @@ -448,7 +448,7 @@ "category": "notes", "pub_date": "2026-10-15", "status": "pending", - "batch_id": "Batch-07", + "batch_id": "Batch-04", "approved_at": null, "notes": "", "en_chars": 8078, @@ -474,7 +474,7 @@ "category": "notes", "pub_date": "2026-09-29", "status": "pending", - "batch_id": "Batch-07", + "batch_id": "Batch-04", "approved_at": null, "notes": "", "en_chars": 9934, @@ -499,10 +499,10 @@ "zh_title": "用一个 Prometheus 监控 unRaid、群晖 NAS 和 VPS:我做错的四件事", "category": "case-studies", "pub_date": "2026-07-29", - "status": "pending", + "status": "approved", "batch_id": "Batch-02", - "approved_at": null, - "notes": "", + "approved_at": "2026-10-27 04:22", + "notes": "外部顾问审阅完成,已采纳并落地全量修改意见(含数字矛盾/OPSEC脱敏/双语CTA/架构蓝图对齐/排版折叠)", "en_chars": 8358, "zh_chars": 4690 }, @@ -591,7 +591,7 @@ "category": "notes", "pub_date": "2025-10-01", "status": "pending", - "batch_id": "Batch-07", + "batch_id": "Batch-04", "approved_at": null, "notes": "", "en_chars": 8382, @@ -629,10 +629,10 @@ "zh_title": "一个人跑生产基础设施:三台主机、162 个容器", "category": "case-studies", "pub_date": "2026-10-06", - "status": "pending", + "status": "approved", "batch_id": "Batch-02", - "approved_at": null, - "notes": "", + "approved_at": "2026-10-27 04:22", + "notes": "外部顾问审阅完成,已采纳并落地全量修改意见(含数字矛盾/OPSEC脱敏/双语CTA/架构蓝图对齐/排版折叠)", "en_chars": 7975, "zh_chars": 3722 }, @@ -656,7 +656,7 @@ "category": "engineering", "pub_date": "2026-09-13", "status": "pending", - "batch_id": "Batch-06", + "batch_id": "Batch-03", "approved_at": null, "notes": "", "en_chars": 11245, @@ -668,10 +668,10 @@ "zh_title": "数字商品的自愈式访问控制:NocoDB、n8n 与 AList", "category": "case-studies", "pub_date": "2026-09-18", - "status": "pending", + "status": "approved", "batch_id": "Batch-02", - "approved_at": null, - "notes": "", + "approved_at": "2026-10-27 04:22", + "notes": "外部顾问审阅完成,已采纳并落地全量修改意见(含数字矛盾/OPSEC脱敏/双语CTA/架构蓝图对齐/排版折叠)", "en_chars": 14765, "zh_chars": 6819 }, @@ -681,10 +681,10 @@ "zh_title": "自建语音转文字服务:打字速度的 3 倍以上,而且数据不出内网", "category": "case-studies", "pub_date": "2026-09-19", - "status": "pending", + "status": "approved", "batch_id": "Batch-02", - "approved_at": null, - "notes": "", + "approved_at": "2026-10-27 04:22", + "notes": "外部顾问审阅完成,已采纳并落地全量修改意见(含数字矛盾/OPSEC脱敏/双语CTA/架构蓝图对齐/排版折叠)", "en_chars": 14708, "zh_chars": 7794 }, @@ -694,10 +694,10 @@ "zh_title": "从云端转本地:在 12GB 显卡与群晖 N8N 上搭建中英混读高保真 TTS 语音栈", "category": "case-studies", "pub_date": "2026-10-22", - "status": "pending", + "status": "approved", "batch_id": "Batch-02", - "approved_at": null, - "notes": "", + "approved_at": "2026-10-27 04:22", + "notes": "外部顾问审阅完成,已采纳并落地全量修改意见(含数字矛盾/OPSEC脱敏/双语CTA/架构蓝图对齐/排版折叠)", "en_chars": 8913, "zh_chars": 4773 }, @@ -707,10 +707,10 @@ "zh_title": "我如何在私有存储节点上自托管 Mem0 记忆栈(让 AI 助手拥有持久记忆)", "category": "case-studies", "pub_date": "2026-09-16", - "status": "pending", + "status": "approved", "batch_id": "Batch-02", - "approved_at": null, - "notes": "", + "approved_at": "2026-10-27 04:22", + "notes": "外部顾问审阅完成,已采纳并落地全量修改意见(含数字矛盾/OPSEC脱敏/双语CTA/架构蓝图对齐/排版折叠)", "en_chars": 8057, "zh_chars": 4849 }, @@ -720,10 +720,10 @@ "zh_title": "把 AI 修图工具做成 WordPress 插件:22 个版本换来的经验", "category": "case-studies", "pub_date": "2026-09-18", - "status": "pending", + "status": "approved", "batch_id": "Batch-02", - "approved_at": null, - "notes": "", + "approved_at": "2026-10-27 04:22", + "notes": "外部顾问审阅完成,已采纳并落地全量修改意见(含数字矛盾/OPSEC脱敏/双语CTA/架构蓝图对齐/排版折叠)", "en_chars": 13879, "zh_chars": 6861 }, @@ -747,7 +747,7 @@ "category": "notes", "pub_date": "2026-04-14", "status": "pending", - "batch_id": "Batch-07", + "batch_id": "Batch-04", "approved_at": null, "notes": "", "en_chars": 5475, @@ -760,7 +760,7 @@ "category": "devops", "pub_date": "2026-10-14", "status": "pending", - "batch_id": "Batch-05", + "batch_id": "Batch-02", "approved_at": null, "notes": "", "en_chars": 5763, @@ -773,7 +773,7 @@ "category": "notes", "pub_date": "2026-10-01", "status": "pending", - "batch_id": "Batch-07", + "batch_id": "Batch-04", "approved_at": null, "notes": "", "en_chars": 4951, @@ -785,10 +785,10 @@ "zh_title": "在多台机器之间同步一个会自我学习的 AI Agent", "category": "case-studies", "pub_date": "2026-02-18", - "status": "pending", + "status": "approved", "batch_id": "Batch-02", - "approved_at": null, - "notes": "", + "approved_at": "2026-10-27 04:22", + "notes": "外部顾问审阅完成,已采纳并落地全量修改意见(含数字矛盾/OPSEC脱敏/双语CTA/架构蓝图对齐/排版折叠)", "en_chars": 8861, "zh_chars": 4541 }, @@ -799,7 +799,7 @@ "category": "notes", "pub_date": "2025-09-10", "status": "pending", - "batch_id": "Batch-07", + "batch_id": "Batch-04", "approved_at": null, "notes": "", "en_chars": 5053, @@ -812,7 +812,7 @@ "category": "devops", "pub_date": "2025-08-20", "status": "pending", - "batch_id": "Batch-05", + "batch_id": "Batch-02", "approved_at": null, "notes": "", "en_chars": 15944, @@ -825,7 +825,7 @@ "category": "devops", "pub_date": "2026-09-16", "status": "pending", - "batch_id": "Batch-05", + "batch_id": "Batch-02", "approved_at": null, "notes": "", "en_chars": 6484, @@ -838,7 +838,7 @@ "category": "devops", "pub_date": "2026-09-18", "status": "pending", - "batch_id": "Batch-05", + "batch_id": "Batch-02", "approved_at": null, "notes": "", "en_chars": 11452, @@ -851,7 +851,7 @@ "category": "notes", "pub_date": "2026-02-04", "status": "pending", - "batch_id": "Batch-07", + "batch_id": "Batch-04", "approved_at": null, "notes": "", "en_chars": 3570, @@ -877,7 +877,7 @@ "category": "devops", "pub_date": "2026-10-06", "status": "pending", - "batch_id": "Batch-05", + "batch_id": "Batch-02", "approved_at": null, "notes": "", "en_chars": 11536, @@ -890,7 +890,7 @@ "category": "engineering", "pub_date": "2025-02-20", "status": "pending", - "batch_id": "Batch-06", + "batch_id": "Batch-03", "approved_at": null, "notes": "", "en_chars": 7750, @@ -903,7 +903,7 @@ "category": "devops", "pub_date": "2026-09-15", "status": "pending", - "batch_id": "Batch-05", + "batch_id": "Batch-02", "approved_at": null, "notes": "", "en_chars": 10067, @@ -916,7 +916,7 @@ "category": "notes", "pub_date": "2026-09-27", "status": "pending", - "batch_id": "Batch-07", + "batch_id": "Batch-04", "approved_at": null, "notes": "", "en_chars": 9469, @@ -929,7 +929,7 @@ "category": "devops", "pub_date": "2025-08-22", "status": "pending", - "batch_id": "Batch-05", + "batch_id": "Batch-02", "approved_at": null, "notes": "", "en_chars": 10255, @@ -955,7 +955,7 @@ "category": "engineering", "pub_date": "2026-09-28", "status": "pending", - "batch_id": "Batch-06", + "batch_id": "Batch-03", "approved_at": null, "notes": "", "en_chars": 12525, @@ -968,7 +968,7 @@ "category": "devops", "pub_date": "2026-09-29", "status": "pending", - "batch_id": "Batch-05", + "batch_id": "Batch-02", "approved_at": null, "notes": "", "en_chars": 8459, @@ -981,7 +981,7 @@ "category": "devops", "pub_date": "2026-09-16", "status": "pending", - "batch_id": "Batch-05", + "batch_id": "Batch-02", "approved_at": null, "notes": "", "en_chars": 12365, @@ -1007,7 +1007,7 @@ "category": "engineering", "pub_date": "2026-10-18", "status": "pending", - "batch_id": "Batch-07", + "batch_id": "Batch-04", "approved_at": null, "notes": "", "en_chars": 8794, @@ -1020,7 +1020,7 @@ "category": "devops", "pub_date": "2026-09-29", "status": "pending", - "batch_id": "Batch-05", + "batch_id": "Batch-02", "approved_at": null, "notes": "", "en_chars": 14761, @@ -1059,7 +1059,7 @@ "category": "notes", "pub_date": "2026-10-22", "status": "pending", - "batch_id": "Batch-07", + "batch_id": "Batch-04", "approved_at": null, "notes": "", "en_chars": 7263, @@ -1072,7 +1072,7 @@ "category": "notes", "pub_date": "2025-07-29", "status": "pending", - "batch_id": "Batch-07", + "batch_id": "Batch-04", "approved_at": null, "notes": "", "en_chars": 5704, @@ -1085,7 +1085,7 @@ "category": "web3", "pub_date": "2026-08-19", "status": "pending", - "batch_id": "Batch-10", + "batch_id": "Batch-07", "approved_at": null, "notes": "", "en_chars": 7725, @@ -1098,7 +1098,7 @@ "category": "devops", "pub_date": "2026-03-25", "status": "pending", - "batch_id": "Batch-05", + "batch_id": "Batch-02", "approved_at": null, "notes": "", "en_chars": 8963, @@ -1111,7 +1111,7 @@ "category": "devops", "pub_date": "2025-03-19", "status": "pending", - "batch_id": "Batch-06", + "batch_id": "Batch-03", "approved_at": null, "notes": "", "en_chars": 8010, @@ -1124,7 +1124,7 @@ "category": "devops", "pub_date": "2026-05-17", "status": "pending", - "batch_id": "Batch-06", + "batch_id": "Batch-03", "approved_at": null, "notes": "", "en_chars": 7347, @@ -1150,7 +1150,7 @@ "category": "notes", "pub_date": "2026-03-12", "status": "pending", - "batch_id": "Batch-07", + "batch_id": "Batch-04", "approved_at": null, "notes": "", "en_chars": 5024, @@ -1163,7 +1163,7 @@ "category": "devops", "pub_date": "2026-06-24", "status": "pending", - "batch_id": "Batch-06", + "batch_id": "Batch-03", "approved_at": null, "notes": "", "en_chars": 5930, diff --git a/docs/consultant-review/batches/batch-01.md b/docs/consultant-review/batches/batch-01.md index 8c0f33c..587282a 100644 --- a/docs/consultant-review/batches/batch-01.md +++ b/docs/consultant-review/batches/batch-01.md @@ -2,9 +2,9 @@ > **批次编号**:`Batch-01` > **包含文章数**:8 篇 -> **本批次总字符量**:174,993 字(严格限制 < 200,000 字) +> **本批次总字符量**:174,959 字(严格限制 < 200,000 字) > **模式**:BILINGUAL -> **生成时间**:2026-10-27 03:02:03 +> **生成时间**:2026-10-27 04:23:31 # 外部顾问审阅前置须知与工程背景规范 @@ -41,7 +41,7 @@ 1. [ai] **Claude 和 GPT 明明更强,我为什么还是买了 GPU 跑本地 AI** (`why-i-still-bought-a-local-gpu`) — ~16,735 字符 2. [ai] **为什么我的 AI 歌曲总是丢结尾:在 12GB 显卡上跑 YuE2** (`yue2-on-a-12gb-gpu-songs-that-lost-their-endings`) — ~53,369 字符 -3. [case-studies] **我如何用 FLUX.1 Kontext 打造 AI 家具合成演示** (`ai-furniture-compositing-with-flux-kontext`) — ~19,783 字符 +3. [case-studies] **我如何用 FLUX.1 Kontext 打造 AI 家具合成演示** (`ai-furniture-compositing-with-flux-kontext`) — ~19,749 字符 4. [case-studies] **从一首歌到 4 分钟完整 MV:我如何用 Gemini、AI 生成与 Filmora 剪辑串起全流程实操** (`from-audio-to-a-4-minute-ai-music-video`) — ~16,195 字符 5. [case-studies] **我是如何用 Remotion 与 Docker CDP 打造全自动 MV 生成与多语种油管发布流的** (`how-i-built-an-automated-music-video-pipeline`) — ~14,196 字符 6. [case-studies] **我是如何构建 DigiKedai Telegram AI 客服机器人的** (`how-i-built-the-digikedai-telegram-bot`) — ~15,990 字符 @@ -2464,7 +2464,6 @@ pubDate: 2026-09-11 category: case-studies blueprint: sme-digital-suite blueprintLayer: L1-high-conversion-web -dynamicCta: true tags: [fal-ai, flux, ai-image, javascript, canvas, ecommerce] ogImage: /og/zh-ai-furniture-compositing-with-flux-kontext.jpg banner: /banners/ai-furniture-compositing-with-flux-kontext.jpg @@ -2654,7 +2653,6 @@ pubDate: 2026-09-11 category: case-studies blueprint: sme-digital-suite blueprintLayer: L1-high-conversion-web -dynamicCta: true tags: [fal-ai, flux, ai-image, javascript, canvas, ecommerce] ogImage: /og/ai-furniture-compositing-with-flux-kontext.jpg banner: /banners/ai-furniture-compositing-with-flux-kontext.jpg diff --git a/docs/consultant-review/batches/batch-02.md b/docs/consultant-review/batches/batch-02.md index 319a671..1ffce93 100644 --- a/docs/consultant-review/batches/batch-02.md +++ b/docs/consultant-review/batches/batch-02.md @@ -1,10 +1,10 @@ # 博客文章顾问审阅资料包 — Batch-02 > **批次编号**:`Batch-02` -> **包含文章数**:10 篇 -> **本批次总字符量**:160,519 字(严格限制 < 200,000 字) +> **包含文章数**:11 篇 +> **本批次总字符量**:179,502 字(严格限制 < 200,000 字) > **模式**:BILINGUAL -> **生成时间**:2026-10-27 03:02:03 +> **生成时间**:2026-10-27 04:23:31 # 外部顾问审阅前置须知与工程背景规范 @@ -39,24 +39,25 @@ ## 本批次文章目录索引 -1. [case-studies] **如何用并行子代理在三小时内核查 20 家 VPS 服务商** (`how-i-vetted-20-vps-providers-with-parallel-subagents`) — ~11,778 字符 -2. [case-studies] **没有 Coding Agent 的 Loop Engineering:撑起我这套基础设施的 11 个定时任务** (`loop-engineering-without-a-coding-agent`) — ~20,707 字符 -3. [case-studies] **用一个 Prometheus 监控 unRaid、群晖 NAS 和 VPS:我做错的四件事** (`one-prometheus-for-unraid-synology-and-a-vps`) — ~12,936 字符 -4. [case-studies] **一个人跑生产基础设施:三台主机、162 个容器** (`running-production-infrastructure-solo`) — ~11,669 字符 -5. [case-studies] **数字商品的自愈式访问控制:NocoDB、n8n 与 AList** (`self-healing-digital-goods-entitlements`) — ~21,593 字符 -6. [case-studies] **自建语音转文字服务:打字速度的五倍,而且数据不出内网** (`self-hosted-speech-to-text-api`) — ~22,254 字符 -7. [case-studies] **从云端转本地:在 12GB 显卡与群晖 N8N 上搭建中英混读高保真 TTS 语音栈** (`self-hosted-tts-cosyvoice2-n8n-gpu`) — ~12,885 字符 -8. [case-studies] **我如何在自家 NAS 上自托管 Mem0 记忆栈(让 AI 助手有记忆)** (`self-hosting-mem0-memory-stack`) — ~12,602 字符 -9. [case-studies] **把 AI 修图工具做成 WordPress 插件:22 个版本换来的经验** (`shipping-an-ai-photo-editor-as-a-wordpress-plugin`) — ~20,578 字符 -10. [case-studies] **在多台机器之间同步一个会自我学习的 AI Agent** (`syncing-a-self-improving-ai-agent-across-machines`) — ~13,517 字符 +1. [devops] **空间回收没卡住,它只是在等明天早上 09:29** (`space-reclamation-wasnt-stuck-it-was-waiting`) — ~8,795 字符 +2. [devops] **Synology 电子表格 API 是一个容器,不是一个 API 端点** (`synology-spreadsheet-api-is-a-container`) — ~25,049 字符 +3. [devops] **我差点把这颗 SSD 送修——真正坏的是 SATA 数据线** (`that-dying-ssd-was-just-a-bad-sata-cable`) — ~9,910 字符 +4. [devops] **换了不同的硬盘,同样的损坏又来了——真凶是 TRIM,不是 SSD** (`the-cause-was-trim-not-the-ssds`) — ~17,933 字符 +5. [devops] **上游被删了,然后带着一个重写版回来** (`the-upstream-was-deleted-then-came-back-rewritten`) — ~16,678 字符 +6. [devops] **Unraid 停止阵列时卡死的真相:Swapfile 锁住挂载点 — 附修复方案** (`unraid-stop-array-hangs-on-swapfile`) — ~16,184 字符 +7. [devops] **用 CDP 自动化上传百兆视频到 YouTube:跨越 DevTools 内存墙的 Docker 归档法** (`uploading-large-videos-to-youtube-via-cdp`) — ~16,824 字符 +8. [devops] **如何在押注前验证一个开源依赖:我用的六项检查** (`vetting-an-open-source-dependency-before-you-bet-on-it`) — ~12,623 字符 +9. [devops] **SMART 显示健康,RAID 却在悄悄损坏数据** (`when-smart-says-healthy-but-your-raid-is-corrupting-data`) — ~17,708 字符 +10. [devops] **为什么容器里的 Chrome 会忘记标签页 —— 以及我是怎么修好的** (`why-chrome-forgets-its-tabs-in-a-container`) — ~23,650 字符 +11. [devops] **Telegram 机器人通知为什么发不出去:IPv6、DNS 和一个折腾了一整天的 400** (`why-telegram-bot-notifications-die`) — ~14,148 字符 --- -## 文章 01 / 10:如何用并行子代理在三小时内核查 20 家 VPS 服务商 -- **Slug**: `how-i-vetted-20-vps-providers-with-parallel-subagents` -- **英文标题**: How I Vetted 20 VPS Providers in Three Hours with Parallel Subagents -- **分类**: `case-studies` | **发布日期**: 2025-11-12 -- **线上地址**: https://blog.hoelee.com/posts/how-i-vetted-20-vps-providers-with-parallel-subagents/ (EN) | https://blog.hoelee.com/posts/zh/how-i-vetted-20-vps-providers-with-parallel-subagents/ (ZH) +## 文章 01 / 11:空间回收没卡住,它只是在等明天早上 09:29 +- **Slug**: `space-reclamation-wasnt-stuck-it-was-waiting` +- **英文标题**: Space Reclamation Wasn't Stuck. It Was Waiting for Tomorrow at 09:29. +- **分类**: `devops` | **发布日期**: 2026-10-14 +- **线上地址**: https://blog.hoelee.com/posts/space-reclamation-wasnt-stuck-it-was-waiting/ (EN) | https://blog.hoelee.com/posts/zh/space-reclamation-wasnt-stuck-it-was-waiting/ (ZH) - **本篇审核状态**: ⏳ 待审核 (Pending) ### ✍️ 顾问审阅意见区 (Review Feedback) @@ -70,2490 +71,225 @@ ### 🇨🇳 中文版原文 (Chinese Markdown Twin) ````markdown --- -title: "如何用并行子代理在三小时内核查 20 家 VPS 服务商" -description: "一个关于编排并行 AI 子代理对 20 家主机服务商做尽职调查的案例研究——WHOIS、AUP 和口碑核查——把数小时的研究任务压缩成一份结构化、可追溯的供应商评分卡。" -pubDate: 2025-11-12 -updatedDate: 2026-09-09 -category: case-studies -blueprint: sme-digital-suite -blueprintLayer: L4-managed-ops-handover -tags: [ai-orchestration, subagents, due-diligence, hosting, devops] -ogImage: /og/zh-how-i-vetted-20-vps-providers-with-parallel-subagents.jpg -banner: /banners/how-i-vetted-20-vps-providers-with-parallel-subagents.jpg ---- - -## 为什么这很重要 - -选主机服务商,本质是用一张信用卡和一次 DNS 变更来下注。选错了,「保证在线率」 -会变成凌晨两点的封停邮件,「注重隐私」会变成一条你从没读过的日志留存条款。 - -问题不是信息不够,而是信息散落在每家服务商的十几个页面里(WHOIS 记录、可接受使用 -政策、隐私政策、价格页、第三方评测站),手工核查又慢又枯燥又容易出错。一家服务商 -就是五个标签页,二十家就是一百个标签页和一下午搭进去的时间。 - -这个故事讲的是我怎么把那一整个下午压到大约三小时——不是靠更快地干活,而是靠编排 -一支 AI 子代理小队并行跑完枯燥的部分,再用同一张清单给所有结果打分。 - -## 问题:我不能靠信仰去核实的那些声明 - -我要为一个有硬性要求的项目筛选服务商:具体的司法辖区、付款方式、流量条款。这些 -没有一样是首页上诚实地写出来的。它们诚实地写在那些无聊的文档里——WHOIS 记录显示 -域名才四个月、AUP 静悄悄地禁掉你正想跑的服务、隐私政策承认自己保留日志。 - -难就难在,核实一家服务商意味着读五份互相矛盾的文档。营销说「自 2012 年起」, -WHOIS 说「今年四月才注册」。特性页说「允许所有流量」,AUP 说「禁止 Tor 中继」。 -一家服务商就是一次事实核查,二十家就是一个研究项目。 - -## 第一次尝试:一个 agent,一个大循环 - -我最先想到的当然是显而易见的那个——单个助手从头到尾挨个处理这份名单,逐家抓取 -文档、记笔记、往下走。 - -它能跑。但它对这份工作的形状来说是错的工具。这活儿**天然可并行**:7 号服务商的 -WHOIS 查询和 3 号服务商的隐私政策毫无关系。串行跑意味着总耗时是每次抓取之和,而且 -——更重要的是——上下文窗口会被我已经翻过去的那几家的半成品笔记塞满。到第八九家 -的时候,早期的发现就被后面的挤掉了。 - -教训是:一个对独立条目做扁平循环的任务,不是推理问题,而是扇出(fan-out)问题。 -一个长长的上下文是装它的错误容器。 - -## 修复:用并行子代理扇出,然后统一打分 - -真正奏效的结构是三层: - -**1. 一张不在乎指向谁的清单。** 在派发任何东西之前,我先写下对每家服务商而言 -「已核实」具体意味着什么: - -- 域名注册日期 对比 那个「since」声明 -- 可接受使用政策(AUP),搜我关心的具体服务 -- 隐私政策,读留存条款 -- 第三方口碑(Trustpilot 看趋势,不看均值;社区提及) -- 流量条款(「防计量」还是一个计量上限) - -这张清单就是契约。每个子代理都拿到同一份,外加一份要套用的服务商名单。 - -**2. 并行子代理,每个负责一批服务商。** 我把名单拆成几簇,每簇交给一个子代理。 -每个子代理在隔离环境里工作,有自己的上下文、自己的一套抓取,最后为每家服务商 -返回一份结构化的事实清单——不是一段话,而是能直接丢进评分卡的字段。 - -关键是子代理彼此不知道对方。这正是要点:1 号服务商的任何内容都不必和 14 号服务商 -共享上下文空间,各自返回自洽的结果。 - -**3. 一次打分,由我来做,不派发。** 子代理产出发现,判断由我来下。一旦你让子代理 -既*收集*事实又*排序*服务商,你就丢了审计链——只会得到一个没有背后证据支撑的结论。 -把打分集中在自己手里,意味着我随时能说出*为什么*某个东西排到某个位置,并指出是哪条 -WHOIS 记录或哪行 AUP 驱动的。 - -这和我做任何代码审查或重构时用的是一个模式:并行化机械的收集,集中化决策。 - -### 编排实际长什么样 - -大致上,每一批: - -```text -子代理 → 「这是清单,这是你那 5 家服务商」 - → 逐家:抓 WHOIS、AUP、隐私政策、价格、评测 - → 返回 { 域名年龄, AUP红旗[], 留存条款, 口碑, 流量 } -我 → 合并进一张评分卡,套用清单,排序,写结论 -``` - -三个子代理并行跑。整轮——二十家服务商、每家五份文档、大约一百次抓取——在手工 -仔细做两三家服务商的时间里就完成了。 - -## 核查到底抓到了什么 - -评分卡暴露了首页永远不会告诉你的真问题: - -- **一家声称「自 2012 年起值得信赖」的服务商,域名比这晚得多。** WHOIS 显示域名是 - 同一年的某个月才注册的——一个「从业多年」的四位数声明,配一个才几个月的域名。 - 这要么是换了马甲的壳,要么就是撒谎,无论哪种,它页面上所有其他声明在我眼里都要 - 降级。 - -- **两家的 AUP 禁掉了我正想跑的那个服务。** 一家在禁止活动条款里列了「TOR 节点」和 - 「匿名化服务」;另一家禁了「反向代理」和「隧道」。两家的特性页却还宣传着相反的话。 - 在 AUP 上花十分钟 `Ctrl-F` 就排除了它们——但前提是*我知道该去查 AUP*,而不是 - 特性页。 - -- **一家原本看着很便宜的服务商,读了流量条款后不是了。** 一个带 1 TB 计量上限的 - 计划上写「无限」,只是营销。对于既要接收又要转发的节点,真实成本翻倍——「便宜」 - 的那个选项并不便宜。 - -它们所有的共同点是:致命信息从来都没藏起来。它是*公开*的,躺在服务商法律上有义务 -发布的文档里。这个技能不是秘密渠道,而是知道该读哪份文档,并拿它去对照营销话术。 - -## 我会怎么做不一样 - -子代理的交接能用,但太粗糙。下次我会提前给每个子代理*精确的返回字段*——一份严格的 -输出 schema——而不是一段我事后还得重新解析的散文。结构化输出意味着最后一个子代理 -返回时评分卡就已经建好了,不用再读一遍。 - -我也会更早钉死「这个声明能否独立验证?」这个测试。大多数红旗并不是服务商公然撒谎, -而是一条我无法对照任何公开记录去核实的声明。把「无法验证」本身当成一种信号,名单 -很快就能缩下来。 - -## 结果 - -大约 20 家服务商、大约 100 次文档抓取,三个子代理并行,耗时相当于手工仔细做两家 -服务商。最终评分卡里的每一项排名都能追溯到一条具体的公开记录——一个 WHOIS 日期、 -一行 AUP 条款、一条留存条款——而不是一种感觉。 - ---- - -## 想为你的企业做这件事吗? - -无论是 VPS、API 网关还是薪酬服务商,选供应商都是同一种问题:在签约*之前*,把你真正 -依赖的那些声明对照无法被营销篡改的公开记录核实一遍。如果你手里有一份候选供应商或 -工具的短名单,想在投入之前拿到一份结构化、有证据支撑的评估——我可以跑这轮尽职调查, -然后交给你一张评分卡,而不是一个猜测。 - -[WhatsApp 联系我](https://wa.me/60127972969) 或 [发邮件](mailto:me@hoelee.com?subject=Vendor%20due-diligence%20evaluation) 到 hoelee.com——我帮企业选对基础设施,并搭建配套的自动化。 -```` - -### 🇬🇧 英文版原文 (English Markdown Primary) -````markdown ---- -title: "How I Vetted 20 VPS Providers in Three Hours with Parallel Subagents" -description: "A case study in orchestrating parallel AI subagents to run due diligence on 20 hosting providers — WHOIS, AUP, and reputation checks — collapsing a multi-hour research task into a structured, verifiable vendor scorecard." -pubDate: 2025-11-12 -updatedDate: 2026-09-09 -category: case-studies -blueprint: sme-digital-suite -blueprintLayer: L4-managed-ops-handover -tags: [ai-orchestration, subagents, due-diligence, hosting, devops] -ogImage: /og/how-i-vetted-20-vps-providers-with-parallel-subagents.jpg -banner: /banners/how-i-vetted-20-vps-providers-with-parallel-subagents.jpg ---- - -## Why it matters - -Choosing a hosting provider is a bet you place with a credit card and a DNS -change. Get it wrong and "guaranteed uptime" becomes a suspension email at 2 AM, -or "privacy-friendly" becomes a log-retention clause you never read. - -The problem isn't a lack of information — it's that the information is scattered -across a dozen pages per provider (WHOIS records, acceptable-use policies, -privacy policies, pricing pages, and third-party review sites), and checking them -manually is slow, boring, and error-prone. One provider is five tabs. Twenty -providers is a hundred tabs and an afternoon you don't get back. - -This is the story of how I collapsed that afternoon into about three hours — not -by working faster, but by orchestrating a small team of AI subagents to run the -boring part in parallel, and scoring everything against one checklist. - -## The problem: verifying claims I couldn't take on faith - -I needed to shortlist providers for a project with hard requirements: specific -jurisdictions, payment methods, and traffic terms. None of those are written -honestly on a homepage. They're written honestly in the boring documents — the -WHOIS record that shows a domain is four months old, the AUP that quietly bans -the exact service you wanted to run, the privacy policy that admits to log -retention. - -The hard part is that verifying one provider means reading five documents that -disagree with each other. The marketing says "since 2012"; the WHOIS says "this -April." The features page says "all traffic allowed"; the AUP says "Tor relays -prohibited." One provider is a fact-checking exercise. Twenty is a research -project. - -## What I tried first: one agent, one big loop - -My first instinct was the obvious one — a single assistant that works through the -list, provider by provider, fetching each document, taking notes, moving on. - -It worked. It was also the wrong tool for the shape of the job. The work is -*embarrassingly parallel*: provider #7's WHOIS lookup has nothing to do with -provider #3's privacy policy. Running them one after another meant the total time -was the sum of every fetch, and — more importantly — the context window filled -with half-finished notes from providers I'd already moved past. By provider -eight or nine, early findings were getting crowded out by later ones. - -The lesson: a task that's a flat loop over independent items isn't a reasoning -problem, it's a fan-out problem. One long context is the wrong container for it. - -## The fix: fan out with parallel subagents, then score once - -The structure that worked was three layers: - -**1. A checklist that doesn't care which provider it's pointed at.** Before -spawning anything, I wrote down exactly what "verified" means per provider: - -- domain registration date vs. the "since" claim -- acceptable-use policy, searched for the specific service I cared about -- privacy policy, read for the retention clause -- third-party reputation (Trustpilot trend, not average; community mentions) -- traffic terms ("unmetered" vs. a metered cap) - -That checklist was the contract. Every subagent got the same one, plus a list of -providers to run it against. - -**2. Parallel subagents, one per batch of providers.** I split the pool into -clusters and handed each cluster to its own subagent. Each one worked in -isolation, with its own context and its own set of fetches, and returned a -structured fact sheet per provider — not a paragraph, but fields I could drop -straight into a scorecard. - -The key here is that the subagents don't know about each other. That's the -point: nothing from provider #1 has to share context space with provider #14. -Each returns a self-contained result. - -**3. A single scoring pass, done by me, not delegated.** The subagents produced -findings; I did the judgment. The moment you let a subagent both *gather* the -facts and *rank* the providers, you lose the audit trail — you get a verdict -without the evidence behind it. Keeping scoring central means I can always say -*why* something ranked where it did, and point at the exact WHOIS record or AUP -line that drove it. - -This mirrors a pattern I'd use for any code review or refactor: parallelize the -mechanical collection, centralize the decisions. - -### What the orchestration actually looked like - -Roughly, per batch: - -```text -subagent → "here's the checklist, here are your 5 providers" - → per provider: fetch WHOIS, AUP, privacy policy, pricing, reviews - → return { domain_age, aup_flags[], retention, reputations, traffic } -me → merge into one scorecard, apply the checklist, rank, write up -``` - -Three subagents ran side by side. The whole pass — twenty providers, five -documents each, one hundred-ish fetches — landed in the time it would have taken -me to do two or three providers carefully by hand. - -## What the verification actually caught - -The scorecard surfaced real problems that a homepage never would have: - -- **A provider whose "trusted since 2012" claim was younger than the domain.** - WHOIS said the domain was registered that same year — a four-figure "years in - business" claim on a domain months old. That's either a re-branded shell or a - lie, and either way it downgraded every other claim on the page in my eyes. - -- **Two providers whose AUP banned the exact service I wanted to run.** One - listed "TOR nodes" and "anonymizing services" in its prohibited-activity - clause; another banned "reverse proxies" and "tunnels." Both still advertised - the opposite on their features pages. Ten minutes of `Ctrl-F` on the AUP is all - it took to rule them out — but only once I *knew to check the AUP* instead of - the features page. - -- **A provider that looked cheap until I read the traffic terms.** "Unlimited" on - a plan with a metered 1 TB cap is marketing. For a relay that both receives and - forwards traffic, the real cost doubles — the "cheap" option wasn't. - -The pattern across all of them: the disqualifying information was never hidden. -It was *public*, sitting in a document the provider is legally required to -publish. The skill isn't secret access — it's knowing which document to read and -checking it against the marketing. - -## What I'd do differently - -The subagent hand-off worked, but it was blunt. Next time I'd give each subagent -the *exact* fields to return up front — a strict output schema — rather than a -prose summary I then have to re-parse. Structured output means the scorecard is -built by the time the last subagent returns, with no re-reading. - -I'd also pin the "is this claim independently verifiable?" test earlier. Most of -the red flags weren't a provider lying outright; they were a claim I couldn't -check against any public record. Treat "unverifiable" as its own signal, and the -shortlist shrinks fast. - -## The result - -~20 providers audited across ~100 document fetches, three subagents running in -parallel, in the time a careful manual pass would have spent on two providers. -Every ranking in the final scorecard traces back to a specific public record — -a WHOIS date, an AUP line, a retention clause — not a vibe. - ---- - -## Want this for your business? - -Choosing a vendor is the same shape of problem whether it's a VPS, an API -gateway, or a payroll provider: verify the claims you're relying on *before* you -sign, against public records that can't be edited by marketing. If you've got a -shortlist of vendors or tools and you want a structured, evidence-backed -evaluation before you commit — I can run the due-diligence pass and hand you a -scorecard, not a hunch. - -[WhatsApp me](https://wa.me/60127972969) or [email me](mailto:me@hoelee.com?subject=Vendor%20due-diligence%20evaluation) at hoelee.com — I help businesses pick the right infrastructure and build the automation around it. -```` - ---- - -## 文章 02 / 10:没有 Coding Agent 的 Loop Engineering:撑起我这套基础设施的 11 个定时任务 -- **Slug**: `loop-engineering-without-a-coding-agent` -- **英文标题**: Loop Engineering Without a Coding Agent: The 11 Cron Jobs That Run My Infrastructure -- **分类**: `case-studies` | **发布日期**: 2026-10-01 -- **线上地址**: https://blog.hoelee.com/posts/loop-engineering-without-a-coding-agent/ (EN) | https://blog.hoelee.com/posts/zh/loop-engineering-without-a-coding-agent/ (ZH) -- **本篇审核状态**: ⏳ 待审核 (Pending) - -### ✍️ 顾问审阅意见区 (Review Feedback) -```text -【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 -【事实与数字核对】: -【人设与用词卫生】: -【CRO与转化建议】: -``` - -### 🇨🇳 中文版原文 (Chinese Markdown Twin) -````markdown ---- -title: "没有 Coding Agent 的 Loop Engineering:撑起我这套基础设施的 11 个定时任务" -description: "Loop engineering 是 2026 年对「设计让 agent 自己反复跑的系统」的叫法。我把它用在自己的自托管基础设施上而不是代码库上:11 个 cron,其中 8 个完全没有 AI。" -pubDate: 2026-10-01 -category: case-studies -blueprint: self-hosted-infrastructure -blueprintLayer: L3-observability-self-healing -tags: ["loop-engineering", "ai-agents", "cron", "self-hosting", "automation", "monitoring"] -ogImage: "/og/zh-loop-engineering-without-a-coding-agent.jpg" -banner: "/banners/loop-engineering-without-a-coding-agent.jpg" +title: "空间回收没卡住,它只是在等明天早上 09:29" +description: "存储管理员那张卡整天写着 running,可用空间一动不动。其实 121 GiB 已经分两步回来了——然后下午又被写掉了 47 GiB。" +pubDate: 2026-10-14 +updatedDate: 2026-10-16 +category: devops +tags: ["synology", "btrfs", "snapshots", "storage", "nas"] +ogImage: /og/zh-space-reclamation-wasnt-stuck-it-was-waiting.jpg +banner: /banners/space-reclamation-wasnt-stuck-it-was-waiting.jpg draft: false --- -关于 loop engineering 的文章,几乎全都在讲 coding agent:Claude Code、Codex、`/goal`、`/loop`。例子永远是同一个形状——一个 agent 整晚替你重构某个代码仓库。 +## 我问错了问题 -我没有这个问题。我自己搭了一套自托管的基础设施——一台 NAS、两台服务器、邮件、反向代理、CI runner——我的循环维持的是**这套东西**,不是代码库。这台机器上跑着 11 个定时任务:每五分钟跳一次的端点看门狗、一天两次的邮件分诊、平台优惠券审计、磁盘损坏检查、域名到期提醒,以及一个专门发现「某次升级偷偷把我的代理头配置重置了」的守卫。 +我清掉几个文件夹,在 NAS 上点了空间回收,然后等。几个小时后,存储管理员那张卡还写着 **running**,可用空间看起来跟早上一样。我的问题是「它为什么什么都没回收」。 -这 11 个里面,有 8 个完全不含 AI。 +**它回收过了——两次**,而且其中一次比我删掉的东西大得多。测量回答的是另一个问题,而这才是这件事里最有意思的地方。 -## 为什么这件事比 agent 本身重要 +## 在相信任何东西之前,先给可用空间上定时采样 -凌晨两点挂掉的服务,只会一直挂到有人发现。域名到期,等于邮件在无声无息中停掉。SSD 损坏,等于我一个星期的工作没了。这些事都不会自己喊出来——它们只是静静地等,等到有人去看。 +我没有去看那张进度卡,而是给 `volume1` 的可用空间做了当天每五分钟一次的采样: -循环就是那个「有人」。它把「我该去看一下」变成「永远有东西在看,而且只在有事的时候才开口」。带来的好处不是什么魔法级自动化,而是我不再充当监控系统本身:真的出问题会有 Telegram 消息,没事的时候就是安静。 - -这就是全部的价值主张,值得说清楚,因为 2026 年围绕 loop 的炒作承诺的远不止这些。 - -## Loop engineering 到底是什么 - -这个说法是 2026 年 6 月出现的。Peter Steinberger 发帖说,你不该再去 prompt coding agent 了,应该去设计「prompt 这些 agent 的循环」。Anthropic 的 Claude Code 负责人 Boris Cherny 说得更短:*"I don't prompt Claude anymore. I have loops running that prompt Claude. My job is to write loops."* 随后 Addy Osmani 发表那篇给这个实践命名的文章,Anthropic 也在 6 月 30 日正式给了它一套四种循环类型的分类。 - -它是一条不断向外包一层的阶梯上最新的那圈:**prompt engineering**(2022–24,*我说清楚了吗?*)、**context engineering**(2025,*它看到对的东西了吗?*)、**harness engineering**(2026 年初,*它有没有一直做对?*)、**loop engineering**(2026,*它能不能不靠我在跑?*)。没有哪一层取代了前一层。我到现在还在写 prompt,只不过通常写在脚本里。 - -没人非得接受这个名词。The Register 在 6 月就管它叫最新一轮 buzzword,并且提了两点公允的批评:agent 本来就是循环;而最热衷推销「无人值守循环」的,恰恰是那些靠卖 token 赚钱的公司。有一份流传很广的报告声称某套常开的循环方案一个月烧了 130 万美元。连 Osmani 自己那篇文章的结尾都留了最重要的保留意见:*"The loop changes the work, it does not delete you from it."* - -我的循环几乎不花钱,原因就是下面第一条设计规则。 - -## 清单 - -| 任务 | 触发 | 凭什么算它干成了 | 用模型? | -|---|---|---|---| -| 端点看门狗(7 个目标,自愈) | 每 5 分钟 | HTTP/TCP 探测 + 控制探测 | 否——纯脚本 | -| 磁盘损坏看门狗 | 每天 10:00 | SMART 计数对比基线 | 否 | -| 域名到期提醒 | 每天 09:00 | 30 天 / 7 天阈值 | 否 | -| 邮件分诊(`me@hoelee.com`) | 09:30 + 18:30 | 未读邮件,按 message-id 去重 | **是** | -| 平台优惠券审计 | 每天 09:00 | 只读抓取后台 | **是** | -| Real-IP + 机器人拦截回归守卫 | 每小时 :20 | 配置不变量 + 日志比例 | 否 | -| unRaid SSD 看门狗 | 每天 10:00 | 计数增量 | 否 | -| 邮箱连通性健康检查 | 每月 | IMAP/SMTP 连接 | 否 | -| 记忆备份 | 每周 | 归档文件写出来了 | 否 | -| 软件版本检查 | 每天 09:00 | npm 最新版 vs 本地版 | 否 | -| 研究项目检查点提醒 | 每月 1、15 号 | 读项目状态,提醒我 | **是** | - -11 个循环,其中 8 个整条路径上没有任何模型。这个比例不是意外,也不是谦虚——它是我学到的最有用的一件事。 - -## 规则一:检查是确定性的,就别花模型去跑 - -我那个软件版本检查原本是 agent 任务。它跑了好几个星期,连续失败了 **29 次**,我才终于不再忽略那些通知。原因有点好笑:agent 模式的定时任务会记录创建时的模型,等我后来改了全局默认模型,这个任务不再悄悄改用新模型,而是干脆整个不跑,打印一行 `[drift_skip]` 就退出。连续 29 次。 - -任务本身其实极其简单:抓 `registry.npmjs.org//latest`,和本地版本比大小,只有远端更新才输出内容。这里面没有任何判断。所以我把它重写成 125 行 Python,每条分支都有明确出口,并把任务改成 `no-agent`——脚本的 stdout 直接作为通知内容,循环里没有 LLM。 - -从此一路全绿。Anthropic 自己的建议也是一句话:*"Use scripts for deterministic work — running a script is cheaper than reasoning through the steps."* 我想补一句更强的版本:如果停止条件是字符串比较,那么在这个循环里放一个模型,唯一的作用就是引入新的失败模式——而且它一定会在凌晨三点、无声无息地引入。 - -在我自己这套任务里的实测差异:11 个循环里有 8 个完全不花 token。用模型的 3 个,需要的都是我写不成代码的判断——这封邮件重不重要、这张券要不要人来处理、这个项目是不是卡住了。 - -## 规则二:验证器必须能大声说出「我自己坏了」 - -第二个我错了很久的地方:一个只在出事时才开口的看门狗,和一个已经死掉的看门狗,表现完全一样——都很安静。 - -所以这套脚本有一个统一契约:**退出码 0 表示「量过了,这是结果」,退出码 1 表示「我量不了」——而退出码 1 永远不静默。** 配置文件不存在、状态文件解析失败、状态目录写不进去、没预料到的异常,全都打印一行 `CANNOT MEASURE` 并退出 1。runner 又把 `main()` 整个包在一层兜底 handler 里,专门接住我没预料到的情况——因为唯一不能容忍的失败模式,是检查器自己悄悄死了。 - -端点看门狗走得更远,这也是整套东西里我最喜欢的一处设计。它在做任何判断之前,先探测一个**控制目标**——`https://one.one.one.one/`。如果这个也失败,那问题出在我自己的上行或 DNS,不是我的服务器,于是看门狗只报告、不动手。没有这道闸门,一次路由器重启看起来就和七个服务同时挂掉一模一样,而一个自动化循环会在这种情况下兴高采烈地去重启一台完全健康的虚拟机。 - -一个分不清「坏了」和「我看不见」的验证器,迟早会在某次网络故障中做出破坏性操作。我宁愿它知道区别。 - -这个循环里我最喜欢引用的数字:它已经连续跑了 **1,618 次**没有误报——因为要连续两次失败才会判定为 down,持续 down 的组会以很慢的节奏重复提醒而不是每个 tick 都喊一遍,恢复只播报一次并附带宕机时长。 - -## 规则三:给它「还能帮上忙」的最小权限 - -最诱人的设计是「让循环自己修好」。能活过生产的版本是三层,每个循环只属于其中一层: - -**第一层——只报告。** 我大部分循环在这里。它们只观察、只告诉我。它们做什么都不可能弄坏东西,所以我可以周五下午上线。 - -**第二层——提议,人确认。** 优惠券审计每天跑,而且按契约是**只读**的。即使脚本打印出一行建议,prompt 也禁止创建或编辑优惠券,因为那个平台的优惠券没有草稿态:确认就等于上线并冻结押金,背后是真金白银。这个循环的任务是递给我一个十秒钟就能做完的决定。 - -**第三层——按白名单动手。** 整套任务里只有一个循环会动手,条件收得很窄:只有在客户机**从宿主机都不可达**时(用宿主机 ping + ARP 验证过)才重启虚拟机;客户机活着但服务挂了的情况从不自动重启——那是要修的 bug,不是要重启的机器。三次运行的冷却期防住了重启循环。而控制探测失败时,它压根不会启动。 - -这个模式可以推广:**每上一层,都必须用一个我宁可相信它、也不相信 agent 的验证器来换。** 我能不能走开?只有当那个判定「做完了」的东西是我在复盘时也愿意相信的东西时,才行。 - -第三层的克制,也是这些循环另一端的平台要求的。一个会「好心」自己修掉发现问题的审计循环,是违反平台条款的问题,不是战果。 - -## 坑一:一个永远失败的循环,和一个无事可报的循环长得一模一样 - -「健康则静默」这条约定是这些循环能被忍受的原因——没有每日状态刷屏,只有真消息。但它同时也藏住了一个**连续失败 29 次**的任务,因为失败的运行和干净的运行,往我手机上推的都是空。 - -后来有两件事把它修好了,而且适用于任何无人值守的循环: - -- **一条独立的「我量不了」通路**(规则二)。它本该在第 1 次就暴露 drift,而不是拖到第 29 次。 -- **去看 runner 自己的执行历史,而不只是看收件箱。** 证据一直在那个任务的执行日志里,我却一直相信「没有通知」这件事本身。现在每加一个新循环,我会显式看它头几次的执行记录,而不是等它来告诉我。 - -如果你的循环「已经安静一阵子」了,先去翻它最近十次运行,再下结论。 - -## 坑二:一个会删生产数据的验证器 - -这一条我到现在还疼。我给一条交付流水线写过一个端到端测试脚本,它的清理步骤执行了一条无条件的 `DELETE FROM orders`。它本来是清理自己制造的数据,它也照做了——只是顺带把当时恰好在同一张表里的 7 张真实订单删了,连同生成好的 PDF,而且没有备份可还原。 - -教训不是「要在副本上测」(对,但当时我确实是),而是更窄、更硬的一条:**验证器是一个有权限的程序,它的写入路径需要和它要验证的东西接受同等程度的审视。** 一个我敢让它无人值守运行的循环,只能对自己的产物具有破坏性。现在这套里每个验证脚本都会把清理范围限定在自己造的、带标记的行上——`WHERE id IN ($MINE)` 或者 `WHERE recipient LIKE '%@example.com'`——其中有一个脚本正是因为这次事故被重写的。 - -Osmani 讲的 comprehension debt 就落在这里。循环跑得越顺,你越不会去读它的输出;而它出错的那天,没人在看。这些循环产生的 diff 我都在读。这个习惯就是剩下那部分工作的全部。 - -## 我刻意没有自动化的东西 - -这 11 个循环里有一个,唯一的工作就是提醒我:每半个月提醒我某个研究项目还在,以及下一步该跑哪些命令。它不抓任何东西、不写任何东西、不开浏览器。循环的职责是让**某个**循环继续转动——不一定是它自己那个。 - -这条边界值得说清楚。这 11 个任务买回的是注意力和早期发现。它们不会替我做任何我没有预先交给它们的决定,判断仍然来自我。真正的变化是:我一天当中再也不会花任何时间去想「是不是哪里坏了」。 - -## 我会做得不一样的地方 - -- **从「只报告」这一层开始,并且在里面多待一会儿。** 我在还没有控制探测和冷却期的时候就写过会动手的循环——那是一次靠运气躲过、而不是靠设计躲过的错误。 -- **每个脚本的第一版就带上「量不了」的出口。** 事后给 11 个任务补上花了我一个晚上;其实每个只要一段 `try/except`。 -- **第一天就去看 runner 的执行日志**,而不是等某条通知「感觉该来了」。 -- **在你需要之前就把状态文件写好。** 这里每个循环旁边都有一个小 JSON——第几次运行、上次的状态、什么时候开始 down。没有外部状态的循环,说不出它上一次知道什么,而「它恢复了吗」这件事,大部分答案都在那里。 - -## 结果 - -11 个循环,其中 8 个不带模型、因此也没有 token 账单,覆盖 7 个被监控的端点、一个邮箱、一个平台账号、一组 RAID 阵列,以及一组会被 CyberPanel 或 DSM 升级悄悄重置的代理不变量。端点看门狗已经连续完成 1,618 次 tick,并且把一台卡死的虚拟机从不可达自愈回健康状态,全程我没有碰它一下。整套任务里最贵的那个是每天一次、成本为零的版本检查——而如果我当时没有去读它的历史,它会一直失败下去。 - -如果你在跑任何必须一直活着的东西,那么「loop engineering」有用的那个版本不是一个 agent 舰队,而是:一个停止条件能被测试的 cron 任务、一个说得出「我看不见」的验证器、一条为没预料到的失败准备的出口,以及「允许它只做最小那件事」的权限。从你每周手动检查的那一件事开始,让它变成承重结构。 - -## 我目前的求职状态 - -我是全栈开发 / DevOps 工程师,正在找 remote 或 hybrid 的岗位——平台、基础设施、DevOps 或全栈方向。这个博客就是我的作品集:这里的每一篇,都是我真正做过、并且必须让它持续跑下去的东西,上面这 11 个循环是其中最不花哨、也最实用的部分。 - -**Email:[me@hoelee.com](mailto:me@hoelee.com) · [LinkedIn](https://www.linkedin.com/in/hoelee) · [GitHub](https://github.com/hoelee) · [hoelee.com](https://hoelee.com)** -```` - -### 🇬🇧 英文版原文 (English Markdown Primary) -````markdown ---- -title: "Loop Engineering Without a Coding Agent: The 11 Cron Jobs That Run My Infrastructure" -description: "Loop engineering is 2026's term for designing the system that prompts and checks an agent. I applied it to self-hosted infrastructure, not a codebase: 11 cron jobs, 8 with no AI at all." -pubDate: 2026-10-01 -category: case-studies -blueprint: self-hosted-infrastructure -blueprintLayer: L3-observability-self-healing -tags: ["loop-engineering", "ai-agents", "cron", "self-hosting", "automation", "monitoring"] -ogImage: "/og/loop-engineering-without-a-coding-agent.jpg" -banner: "/banners/loop-engineering-without-a-coding-agent.jpg" -draft: false ---- - -Every article about "loop engineering" is about a coding agent. Claude Code, -Codex, `/goal`, `/loop`. The examples are always the same shape: an agent -refactoring a repository overnight while you sleep. - -I don't have that problem. I run my own self-hosted infrastructure — a NAS, -a couple of servers, mail, a reverse proxy, a CI runner — and my loops keep -*that* alive, not a codebase. Eleven scheduled jobs run on this machine: an -endpoint watchdog that fires every five minutes, mail triage twice a day, a -marketplace voucher audit, a disk-corruption check, a domain-expiry -reminder, a guard that notices when an upgrade silently reset my proxy -headers. - -Eight of those eleven contain no AI at all. - -## Why this matters more than the agent does - -A service that is down at 2am stays down until someone notices. An expiring -domain is mail that silently stops arriving. A corrupt SSD is a week of my -work. None of these announce themselves; they all wait quietly until someone -looks. - -A loop is that someone. It turns "I should check on that" into "something -checks on that, forever, and only speaks when there is news." The payoff is -not magic autonomy — it is that I stopped being the monitoring system. I get -a Telegram message when something is actually wrong, and silence when it -isn't. - -That is the whole value proposition, and it is worth being precise about it, -because the 2026 hype around loops promises considerably more. - -## What loop engineering actually is - -The term arrived in June 2026. Peter Steinberger posted that you shouldn't -be prompting coding agents anymore — you should be designing the loops that -prompt them. Boris Cherny, who leads Claude Code at Anthropic, put it even -shorter: *"I don't prompt Claude anymore. I have loops running that prompt -Claude. My job is to write loops."* Addy Osmani published the essay that -gave the practice a name, and Anthropic made it official on June 30 with a -taxonomy of four loop types. - -It is the newest ring of a ladder that keeps wrapping itself: **prompt -engineering** (2022–24, *did I say it clearly?*), **context engineering** -(2025, *does it see the right thing?*), **harness engineering** (early 2026, -*does it keep doing it right?*), and **loop engineering** (2026, *does it -run without me?*). Nothing replaced anything. I still write prompts, usually -inside a script. - -Nobody has to adopt the word. The Register called it the latest buzzword in -June and made two fair points: agents have always been loops, and the -companies selling tokens are the companies most excited about loops that -spend tokens unattended. One widely-read report claimed a $1.3M monthly bill -for an always-on loop setup. Even Osmani's own essay ends with the caveat -that matters: *"The loop changes the work, it does not delete you from it."* - -My loops cost me almost nothing, and the reason is the first design rule -below. - -## The inventory - -| Job | Trigger | What proves it worked | Model? | -|---|---|---|---| -| Endpoint watchdog (7 targets, self-heal) | every 5 min | HTTP/TCP probe + control probe | no — script | -| Disk-corruption watchdog | daily 10:00 | SMART counters vs baseline | no | -| Domain-expiry reminder | daily 09:00 | 30-day / 7-day thresholds | no | -| Mail triage (`me@hoelee.com`) | 09:30 + 18:30 | unread mail, deduped | **yes** | -| Marketplace voucher audit | daily 09:00 | read-only portal scrape | **yes** | -| Real-IP + bot-block regression guard | hourly :20 | config invariants + log ratios | no | -| unRaid SSD watchdog | daily 10:00 | counter deltas | no | -| Mailbox health | monthly | IMAP/SMTP connect | no | -| Memory backup | weekly | archive written | no | -| Package version check | daily 09:00 | npm latest vs local | no | -| Research checkpoint reminder | 1st + 15th | reads project state, reminds me | **yes** | - -Eleven loops, eight of them with no model anywhere in the path. That ratio -is not an accident and it is not modesty — it is the single most useful -thing I learned. - -## Rule 1 — if the check is deterministic, do not spend a model on it - -My package version check used to be an agent job. It ran for weeks and -failed 29 times in a row before I stopped ignoring the notifications. The -cause was almost funny: an agent-mode job records the model it was created -with, and when my global default model later changed, the job refused to run -at all rather than silently adopt the new one. It printed `[drift_skip]` and -exited. Twenty-nine times. - -The task itself is trivial: fetch `registry.npmjs.org//latest`, compare -it with the local version, print something only if the remote is newer. -There is no judgment in that. So I rewrote it as 125 lines of Python with an -explicit exit path for every branch, and set the job to `no-agent` — the -script's stdout is delivered as the notification, no LLM in the loop. - -It has run green ever since. Anthropic's own guidance says the same thing in -one line: *"Use scripts for deterministic work — running a script is cheaper -than reasoning through the steps."* I'd add the stronger version: if the -stop condition is a string comparison, a model in that loop can only -introduce failure modes, and it will, at 3am, silently. - -The measured difference in my own fleet: 8 of 11 loops run with zero tokens. -The three that use a model all need judgment I cannot express as code — is -this email important, does this voucher need a human, is this project -stalled. - -## Rule 2 — the verifier must be able to fail loudly about itself - -The second thing I got wrong for a long time: a watchdog that only speaks -when something is broken is indistinguishable from a watchdog that has -stopped working. Both are silent. - -So every script in the fleet has one contract: **exit code 0 means -"measured, here is what I found" and exit code 1 means "I could not measure" -— and exit 1 is never silent.** A missing config file, an unparseable state -file, an unwritable state directory, an unexpected exception: all of them -print a `CANNOT MEASURE` line and exit 1. The runner wraps `main()` in a -blanket handler that catches anything I failed to anticipate, because the -one failure mode I cannot tolerate is a checker that has quietly died. - -The endpoint watchdog goes further, and this is my favourite piece of the -whole setup. Before it judges anything, it probes a **control target** — -`https://one.one.one.one/`. If that fails, the problem is my own uplink or -DNS, not my servers, and the watchdog reports instead of acting. Without -that gate, a router reboot would look exactly like seven simultaneous -outages, and an automated loop would have cheerfully restarted a perfectly -healthy VM in the middle of it. - -A verifier that cannot tell "broken" from "I can't see" will eventually take -a destructive action during a network outage. I would rather it know the -difference. - -The number I like quoting from this loop: it has ticked **1,618 times** -without a false alarm, because two consecutive failures are required before -anything is called down, a group that stays down is re-reported on a slow -cadence rather than every tick, and recovery is announced once with the -downtime window. - -## Rule 3 — give it the smallest autonomy that still helps - -The tempting design is "the loop fixes things." The design that survives -contact with production has three tiers, and each loop sits in exactly one: - -**Tier 1 — report only.** Most of my loops. They observe and tell me. Nothing they do can break anything, which means I can deploy them on a Friday. - -**Tier 2 — propose, human confirms.** The voucher audit runs daily and is *read-only by contract*. The prompt forbids creating or editing a voucher even if the script prints a proposal, because vouchers on that platform have no draft state: confirming means live and escrowed, with money attached. The loop's job is to hand me a decision I can make in ten seconds. - -**Tier 3 — act, within an allowlist.** Exactly one loop in the fleet acts, and the conditions are narrow: it restarts a VM only when the guest is *unreachable from the hypervisor* (verified by ping and ARP from the host), never when the guest is up but its service is failing — that is a bug to fix, not a machine to bounce. A three-run cooldown prevents a restart loop. And it never runs at all when the control probe failed. - -The pattern generalises: **each tier up must earn its right with a verifier -I trust more than the agent.** Am I allowed to walk away? Only if the thing -that decides "done" is something I would trust in a post-mortem. - -That restraint is also what the platform on the receiving end requires. An -audit that "helpfully" fixed its own findings would be a terms-of-service -problem, not a win. - -## Trap 1: a loop that fails forever looks exactly like a loop with nothing to report - -My silent-when-healthy convention is what makes these loops tolerable — no -daily status spam, only real news. It also hid a job that had failed **29 -consecutive times**, because a failed run and a clean run both delivered -nothing to my phone. - -Two things fixed it, and they apply to any unattended loop: - -- **A distinct "I could not measure" path** (Rule 2). It would have surfaced the drift on the first run instead of the twenty-ninth. -- **Check the runner's own history, not just the inbox.** The job's execution log had the evidence the whole time; I trusted the absence of a notification instead. Now, when I add a loop, I check its first few runs explicitly rather than waiting for it to tell me something. - -If your loop has ever been "quiet for a while", go look at its last ten runs -before you conclude it is working. - -## Trap 2: a verifier that deletes production data - -This one still stings. I had an end-to-end test script for a delivery -pipeline, and its cleanup step ran an unconditional `DELETE FROM orders`. It -was written to clean up after itself and it did — along with the seven real -orders that happened to be in the same table, and their generated PDFs, with -no backup to restore from. - -The lesson is not "test on a copy" (true, but I had). It is narrower and -harder: **a verifier is a program with permissions, and its write path needs -the same scrutiny as the thing it is verifying.** A loop I trust to run -unattended must only be destructive to what it created itself. Every -verification script in the fleet now scopes its cleanup to rows carrying its -own marker — `WHERE id IN ($MINE)` or `WHERE recipient LIKE '%@example.com'` -— and one of them did get rewritten after that incident for exactly this -reason. - -Osmani's point about comprehension debt lands here. The more smoothly the -loop runs, the less you read its output — and the day it is wrong, nobody -was watching. I read the diffs these loops produce. That habit is the entire -remaining job. - -## What I deliberately did not automate - -One of the eleven loops does nothing but remind me, twice a month, that a -research project exists and here are the commands to run next. It fetches -nothing, writes nothing, opens no browser. A loop's job is to keep *a* loop -turning — not necessarily its own. - -That is the honest boundary. These eleven jobs buy back attention and catch -failures early. They never make a decision I haven't already handed them, -and the judgement still comes from me. What changed is that I no longer -spend any part of my day wondering whether something is broken. - -## What I would do differently - -- **Start with the report-only tier and stay there longer.** I wrote one acting loop before I had the control probe and the cooldown, which is a mistake I got lucky on rather than deserved to avoid. -- **Add the "cannot measure" exit path to the first version of every script.** Retrofitting it across eleven jobs took an evening; it is one `try/except` in each. -- **Check the runner's execution log on day one**, not when a notification feels overdue. -- **Write the state file before you need it.** Every loop here keeps a small JSON next to it — tick number, last-known status, when something went down. A loop with no external state cannot tell you what it knew last time, which is most of what "did this recover?" means. - -## The result - -Eleven loops, eight of them running with no model and therefore no token -bill, covering seven monitored endpoints, a mailbox, a marketplace account, -a RAID array and a set of proxy invariants that a CyberPanel or DSM upgrade -can silently reset. The endpoint watchdog has completed 1,618 consecutive -ticks and has self-healed a hung VM from unreachable to healthy without me -touching it. The most expensive job in the fleet is a daily version check -that costs nothing and would have kept failing forever if I hadn't read its -history. - -If you are running anything you have to keep alive, the useful version of -"loop engineering" is not a fleet of agents. It is one cron job with a stop -condition you can test, a verifier that says when it cannot see, an exit -path for the failure you did not anticipate — and permission to do the -smallest thing that helps. Start with the one thing you check manually every -week, and make it load-bearing. - -## Open to work - -I'm a full-stack developer and DevOps engineer, and I'm open to remote or -hybrid roles — platform, infrastructure, DevOps, or full-stack. This blog is -the work sample: every post here is something I actually built and then had -to keep running, and the eleven loops above are the least glamorous and most -useful part of it. - -**Email: [me@hoelee.com](mailto:me@hoelee.com) · [LinkedIn](https://www.linkedin.com/in/hoelee) · [GitHub](https://github.com/hoelee) · [hoelee.com](https://hoelee.com)** -```` - ---- - -## 文章 03 / 10:用一个 Prometheus 监控 unRaid、群晖 NAS 和 VPS:我做错的四件事 -- **Slug**: `one-prometheus-for-unraid-synology-and-a-vps` -- **英文标题**: One Prometheus for unRaid, a Synology NAS, and a VPS: What I Got Wrong -- **分类**: `case-studies` | **发布日期**: 2026-07-29 -- **线上地址**: https://blog.hoelee.com/posts/one-prometheus-for-unraid-synology-and-a-vps/ (EN) | https://blog.hoelee.com/posts/zh/one-prometheus-for-unraid-synology-and-a-vps/ (ZH) -- **本篇审核状态**: ⏳ 待审核 (Pending) - -### ✍️ 顾问审阅意见区 (Review Feedback) -```text -【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 -【事实与数字核对】: -【人设与用词卫生】: -【CRO与转化建议】: -``` - -### 🇨🇳 中文版原文 (Chinese Markdown Twin) -````markdown ---- -title: "用一个 Prometheus 监控 unRaid、群晖 NAS 和 VPS:我做错的四件事" -description: "三台主机、一个 Prometheus、一个 Grafana:覆盖矩阵、把同一个 NAS 卷算成三次的\"总容量\",以及那台完全不导出 CPU 频率的虚拟机。" -pubDate: 2026-07-29 -updatedDate: 2026-09-29 -category: case-studies -blueprint: self-hosted-infrastructure -blueprintLayer: L3-observability-self-healing -tags: [prometheus, grafana, unraid, synology, dsm, cadvisor, monitoring, self-hosting] -ogImage: /og/zh-one-prometheus-for-unraid-synology-and-a-vps.jpg -banner: /banners/one-prometheus-for-unraid-synology-and-a-vps.jpg -draft: false ---- - -## 为什么这件事重要 - -当一套自托管基础设施在跑别人的网站、邮件和文件时,它就不是玩具了。糟糕的一周和糟糕的**一个月**之间,差别通常只是你多早发现:一块出现重分配扇区的盘、一个只剩 20 GB 的卷、一台被宿主机饿死的虚拟机、一个夜里重启四次的容器。 - -我有三台机器——unRaid(日常主力)、群晖 NAS(存储与服务)和 VPS(对外)——以及三套**各自**都不知道它们在干什么的方式。这篇文章讲它们如何变成一块屏,以及我路上做错的四件事——其中三个你也会踩。 - -## 架构 - -一个 Prometheus 加一个 Grafana,跑在永不关机的那台机器上。每台被监控主机跑两个 exporter: - -| 机器 | 主机指标 | 容器指标 | 抓取路径 | -|---|---|---|---| -| unRaid | node_exporter (`:9100`) | cAdvisor (`:8080`) | 直连 | -| 群晖 DSM | node_exporter (`:9100`) | cAdvisor (`:8082`) | 局域网 | -| ServerHosh VPS | node_exporter (`:9100`) | cAdvisor (`:8081`) | VPN 隧道 + `nginx` stream 中转 | - -**node_exporter 与 cAdvisor 不是替代关系——这是最容易搞错的一点。** node_exporter 看的是**主机**:CPU、内存、网络、磁盘、文件系统、温度;它对 cgroup 一无所知,说不出是哪个容器吃掉了内存。cAdvisor 只看**容器**。想要主机健康和按容器记账,两个都得跑;少一个,那个洞会在几个月后表现为一次无法解释的负载高峰。 - -## 错误一:cAdvisor 里那些\"不是容器的容器\" - -我的容器规则开始对不是容器的东西告警。cAdvisor 会为 **systemd slice** 和整机 cgroup 导出序列——其中一条没有名字的序列报告了约 58 GB 的\"内存使用\",却没有对应的容器。那就是整台主机,被描述成了一个容器。 - -修法是加一个过滤条件,但你得先知道要写它: - -```promql -# container metrics: anything with a name, and only that -container_memory_working_set_bytes{job=~"cadvisor.*", name!=""} -``` - -少了 `name!=""`,一条\"容器内存超过 10 GB\"的规则会对主机自己告警。 - -## 错误二:我的\"总容量\"是虚构的 - -聚合面板好看,但就是错的。原因:**同一个文件系统会在指标里出现多次。** - -- 在 NAS 上,主卷是 `/volume1`,而 `/opt` 是**同一个** btrfs 文件系统,只是换了个挂载点。 -- 在 unRaid 上,同一个 NAS 卷又以 CIFS 挂载成 `/mnt/remotes/_ActiveBackup`。 -- unRaid 的 `/var/lib/docker` 是那个池的子卷,而 `/mnt/ssd` 已经代表过同一个池——同样的字节,第二个身份。 - -所以朴素的 `sum(node_filesystem_size_bytes)` 报出了我并不存在的容量。诚实的写法是明确列出什么算数据存储: - -```promql -node_filesystem_size_bytes{ - mountpoint=~"/volume[0-9]+|/mnt/ssd|/mnt/disk[0-9]+", - fstype!~"fuse.*|tmpfs|rootfs" -} or node_filesystem_size_bytes{job="vps-host", mountpoint="/"} -``` - -还有两条应该写进面板说明的诚实备注,因为没人能解释的数字比没有数字更糟: - -- **校验盘对内核不可见。** unRaid 的奇偶校验盘没有文件系统,所以从不出现在指标里——这个和是可用容量,不是硬盘数量。 -- **镜像会虚增裸和。** 两块镜像 SSD 会各报一次自己的字节,和不是你能存的量。 - -还有那个以后一定会咬我的遗漏:unRaid 的 shfs 联合挂载(`/mnt/user`)报告 `avail=0`。把它算进\"剩余空间低于 X\"的规则里,就会产生一条永远无法解除的告警。 - -## 错误三:那台不导出 CPU 频率的虚拟机 - -为了算全家的\"总 CPU 频率\",我直接用 node_exporter 的 cpufreq collector。unRaid 和 NAS 都按核心报出了 `node_cpu_scaling_frequency_hertz`;VPS **什么都没有**——它是 KVM 客户机,而客户机没有 `/sys/devices/system/cpu/cpu0/cpufreq`。这个指标在那里无法存在。 - -修法是 textfile collector:一个小脚本读客户机**能**看到的东西(`/proc/cpuinfo`),把 Prometheus 格式指标写进 node_exporter 会抓取的目录: - -```sh -# /opt/node-exporter-textfile/cpu-mhz.sh — cron 每 5 分钟 -awk -F: ' - /^processor/ { c = $2; gsub(/[ \t]/, "", c) } - /^cpu MHz/ { f = $2; gsub(/[ \t]/, "", f); printf "node_cpu_mhz_current_hz{core=\"%s\"} %.0f\n", c, f * 1000000 } -' /proc/cpuinfo -``` - -配合: - -```yaml -command: - - '--collector.textfile.directory=/textfile' -volumes: - - /opt/node-exporter-textfile:/textfile:ro -``` - -两个刻意的决定:指标名**故意不同**于 node_exporter 自己的(用 `node_cpu_mhz_current_hz`,不用 `node_cpu_scaling_frequency_hertz`),这样万一以后宿主机暴露真实 cpufreq,不会出现重复序列冲突;仪表盘则显式合并两个来源: - -```promql -sum(node_cpu_scaling_frequency_hertz or node_cpu_mhz_current_hz) -``` - -## 错误四:exporter 把容器名当成了主机名 - -仪表盘的主机下拉框里出现了 `9f9afcccc962`。那是个容器 ID:node_exporter 的 `uname` collector 读到的是**进程自己的** UTS namespace,而容器的 hostname 默认就是它自己的 ID。指标没错,标签毫无意义。compose 里一行解决: - -```yaml -services: - node_exporter: - hostname: 2.hoelee.com # otherwise `nodename` = the container ID -``` - -## 我下次会怎么做 - -- **刻意把总览屏留到最后做。** \"总容量是多少\"这个问题会逼出全部去重工作;先做完三台主机面板再发现,就得在每个地方重做这个数字。 -- **一开始就给容器钉 hostname。** 一行成本,省掉一个让人困惑的下拉框。 -- **假设每个虚拟化或家电式主机都会藏掉一类指标。** NAS 可能限制你的容器监控(DSM 的 Docker API 版本把我的 cAdvisor 钉在 v0.53.0——更新的版本要更新的 Docker API);虚拟机藏掉 cpufreq;路由器藏掉自己的 CPU。找缺口的方法是**数你期待的东西**,而不是相信\"采集器成功了\"。 - -## 结果 - -三台主机、**7 个抓取目标、一个 Grafana、16 条告警规则**,以及一块屏:**47 个 CPU 核心 · 当前 158 GHz(标称上限 205 GHz)· 142 GB 内存 · 64 TB 存储 · 155 个运行中容器**,并且每台机器克隆同一套主机/容器面板布局,三台读起来完全一致。告警进 Telegram 和邮件,Prometheus 保留 30 天。 - -最有用的产出不是仪表盘,而是重写存储规则那天触发的一条告警:一个只剩 21 GB 的 NAS 卷——它一直藏在\"99% 满\"的百分比阈值背后,而那个巨物早已变成背景噪声。 - -## 需要为你的业务做这个吗? - -如果你有 NAS、VPS 和几台服务器,却没有一个地方能同时看它们,我可以帮你搭这样的自托管监控流水线——Prometheus + Grafana 覆盖你的机器,主机**与**容器指标,真正有意义的磁盘健康与容量规则,通知推到 Telegram 或邮件。 - -**WhatsApp:[+60 12-797 2969](https://wa.me/60127972969)** · **邮箱:[me@hoelee.com](mailto:me@hoelee.com?subject=Self-hosted%20monitoring%20setup)** · **[hoelee.com](https://hoelee.com)** - -网站设计与开发是我的主业;服务器加固与自托管基础设施是它的另一半。 -```` - -### 🇬🇧 英文版原文 (English Markdown Primary) -````markdown ---- -title: "One Prometheus for unRaid, a Synology NAS, and a VPS: What I Got Wrong" -description: "Three hosts, one Prometheus, one Grafana. The coverage matrix, the storage total that counted one NAS volume three times, and the VM that exports no CPU frequency at all." -pubDate: 2026-07-29 -updatedDate: 2026-09-29 -category: case-studies -blueprint: self-hosted-infrastructure -blueprintLayer: L3-observability-self-healing -tags: [prometheus, grafana, unraid, synology, dsm, cadvisor, monitoring, self-hosting] -ogImage: /og/one-prometheus-for-unraid-synology-and-a-vps.jpg -banner: /banners/one-prometheus-for-unraid-synology-and-a-vps.jpg -draft: false ---- - -## Why this matters - -Self-hosted infrastructure is not a toy when it's running other people's websites, mail and files. The -difference between a bad week and a bad *month* is usually how early you found out: a -disk with a reallocated sector, a volume with 20 GB left, a VM being starved of CPU by -its host, a container that restarted four times overnight while you slept. - -I had three machines — unRaid (the daily driver), a Synology NAS (the storage and -services box) and a VPS (the public-facing one) — and three separate ways of *not* -knowing what they were doing. This is how they became one screen, and the four things I -got wrong on the way, because three of them are traps you will hit too. - -## The architecture - -One Prometheus and one Grafana, running on the host that never sleeps. Every monitored -host runs two exporters: - -| Machine | Host metrics | Container metrics | Scrape path | -|---|---|---|---| -| unRaid | node_exporter (`:9100`) | cAdvisor (`:8080`) | direct | -| Synology DSM | node_exporter (`:9100`) | cAdvisor (`:8082`) | LAN | -| ServerHosh VPS | node_exporter (`:9100`) | cAdvisor (`:8081`) | VPN tunnel + `nginx` stream relay | - -**node_exporter and cAdvisor are not substitutes — this is the first thing people get -wrong.** node_exporter sees the *host*: CPU, memory, network, disks, filesystems, -temperatures. It is cgroup-blind: it cannot tell you which container is eating your RAM. -cAdvisor sees *containers only*. If you want both host health and per-container -accounting, you run both. Dropping either one leaves a hole that shows up months later -as an unexplained load spike. - -## Wrong #1: cAdvisor's "containers" that aren't containers - -My container rules started firing on things that were not containers. cAdvisor exports -cgroup series for **systemd slices** and for the machine-wide cgroup — including one -unnamed series that reported roughly 58 GB of "memory usage" with no container attached -to it. That is the whole host, described as a container. - -The fix is one filter, but you have to know to write it: - -```promql -# container metrics: anything with a name, and only that -container_memory_working_set_bytes{job=~"cadvisor.*", name!=""} -``` - -Without `name!=""`, a "container using more than 10 GB" rule alerts on the host itself. - -## Wrong #2: my "total storage" number was fiction - -The aggregate panel looked great and was simply wrong. The reason: **one filesystem -appears in the metrics more than once.** - -- On the NAS, the primary volume is `/volume1` — and `/opt` is the *same* btrfs - filesystem, exposed under a second mount point. -- On unRaid, that same NAS volume is mounted again over CIFS as - `/mnt/remotes/_ActiveBackup`. -- unRaid's `/var/lib/docker` is a subvolume of the pool that `/mnt/ssd` already - represents — same bytes, second identity. - -A naive `sum(node_filesystem_size_bytes)` therefore reported capacity for disks I don't -have. The honest selector names exactly what counts as data storage: - -```promql -node_filesystem_size_bytes{ - mountpoint=~"/volume[0-9]+|/mnt/ssd|/mnt/disk[0-9]+", - fstype!~"fuse.*|tmpfs|rootfs" -} or node_filesystem_size_bytes{job="vps-host", mountpoint="/"} -``` - -Two more honesty notes that belong *in the panel description*, because a number nobody -can interpret is worse than no number: - -- **Parity disks are invisible to the kernel.** unRaid's parity drive has no filesystem, - so it never appears — the sum is usable capacity, not raw spindle count. -- **A mirror inflates a raw sum.** Two mirrored SSDs report their bytes twice; the sum - is not what you can store. - -And the omission that would have bitten me later: unRaid's shfs union mount (`/mnt/user`) -reports `avail=0`. Including it in a "free space below X" rule produces an alert that -can never be resolved. - -## Wrong #3: the VM that exports no CPU frequency - -Wanting "total CPU frequency" across the lab, I reached for node_exporter's cpufreq -collector. unRaid and the NAS reported `node_cpu_scaling_frequency_hertz` per core. The -VPS reported **nothing at all** — it's a KVM guest, and a guest has no -`/sys/devices/system/cpu/cpu0/cpufreq`. The metric cannot exist there. - -The fix is the textfile collector: a small script that reads what the guest *can* see -(`/proc/cpuinfo`) and writes Prometheus-format metrics into a directory node_exporter -scrapes: - -```sh -# /opt/node-exporter-textfile/cpu-mhz.sh — run from cron every 5 minutes -awk -F: ' - /^processor/ { c = $2; gsub(/[ \t]/, "", c) } - /^cpu MHz/ { f = $2; gsub(/[ \t]/, "", f); printf "node_cpu_mhz_current_hz{core=\"%s\"} %.0f\n", c, f * 1000000 } -' /proc/cpuinfo -``` - -with - -```yaml -command: - - '--collector.textfile.directory=/textfile' -volumes: - - /opt/node-exporter-textfile:/textfile:ro -``` - -Two deliberate decisions: the metric is published under a **different name** than -node_exporter's own (`node_cpu_mhz_current_hz`, not `node_cpu_scaling_frequency_hertz`) -so that if the host ever exposes real cpufreq there is no duplicate-series conflict, and -the dashboards merge the two sources explicitly: - -```promql -sum(node_cpu_scaling_frequency_hertz or node_cpu_mhz_current_hz) -``` - -## Wrong #4: my exporter was reporting the container's name as the host's - -The host dropdown in the dashboard offered `9f9afcccc962` as a machine. That's a container -ID: node_exporter's `uname` collector reports the *process's* UTS namespace, and a -container's hostname defaults to its own ID. The metric was correct, the label was -meaningless. One line in compose fixes it: - -```yaml -services: - node_exporter: - hostname: 2.hoelee.com # otherwise `nodename` = the container ID -``` - -## What I'd do differently - -- **Build the aggregate/overview screen last, deliberately.** Deciding "what is total - storage?" is what forces the deduplication work — discovering it after building three - host dashboards means rebuilding the number everywhere. -- **Pin container `hostname` from the start.** It costs one line and saves a confusing - dropdown. -- **Assume every virtualised or appliance host hides one class of metric.** A NAS may - cap your container monitor (DSM's Docker API version pinned my cAdvisor to v0.53.0 — - newer releases need a newer Docker API); a VM hides cpufreq; a router hides its own - CPU. Find the gap by *counting what you expected* rather than trusting that the - collector succeeded. - -## The result - -Three hosts, **7 scrape targets, one Grafana, 16 alert rules**, and a single screen that -reads: **47 CPU cores · 158 GHz currently clocked (205 GHz nominal) · 142 GB RAM · 64 TB -storage · 155 running containers**, with the same host and container dashboard layout -cloned per machine so the three read identically. Alerts land in Telegram and email; -Prometheus keeps 30 days. - -The most useful outcome wasn't the dashboard. It was the alert that fired the day the -storage rule was rewritten: a NAS volume with 21 GB left, which had been hidden behind a -percentage threshold on a volume so large that "99% full" had become background noise. - -## Want this for your business? - -If you run a NAS, a VPS and a couple of servers and have no single place to see them, I -set up self-hosted monitoring pipelines like this one — Prometheus + Grafana across your -machines, host *and* container metrics, disk-health and capacity rules that mean -something, and alerts pushed to Telegram or email. - -**WhatsApp: [+60 12-797 2969](https://wa.me/60127972969)** · **Email: [me@hoelee.com](mailto:me@hoelee.com?subject=Self-hosted%20monitoring%20setup)** · **[hoelee.com](https://hoelee.com)** - -Website design and development is my main line of work; server hardening and -self-hosted infrastructure is the other half of it. -```` - ---- - -## 文章 04 / 10:一个人跑生产基础设施:三台主机、162 个容器 -- **Slug**: `running-production-infrastructure-solo` -- **英文标题**: Running Production Infrastructure Solo: 162 Containers Across Three Hosts -- **分类**: `case-studies` | **发布日期**: 2026-10-06 -- **线上地址**: https://blog.hoelee.com/posts/running-production-infrastructure-solo/ (EN) | https://blog.hoelee.com/posts/zh/running-production-infrastructure-solo/ (ZH) -- **本篇审核状态**: ⏳ 待审核 (Pending) - -### ✍️ 顾问审阅意见区 (Review Feedback) -```text -【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 -【事实与数字核对】: -【人设与用词卫生】: -【CRO与转化建议】: -``` - -### 🇨🇳 中文版原文 (Chinese Markdown Twin) -````markdown ---- -title: "一个人跑生产基础设施:三台主机、162 个容器" -description: "一个人、三台主机、78 个 compose stack 里的 162 个容器——Traefik、SSO、监控、邮件、CI/CD 与备份,以及两次改变了我「怎么核对数字」的故障。" -pubDate: 2026-10-06 -category: case-studies -blueprint: self-hosted-infrastructure -blueprintLayer: L1-compute-storage-network -tags: [docker, traefik, monitoring, infrastructure, devops] -ogImage: /og/zh-running-production-infrastructure-solo.jpg -banner: /banners/running-production-infrastructure-solo.jpg -draft: false ---- - -## 为什么这件事重要 - -卖软件的公司其实同时需要两样东西:一个能干活的应用,以及底下那套让它随时可达、有备份、够安全的机器。大多数情况是这两件事被拆开——开发的人看不见服务器,托管公司又读不懂代码。 - -我两件都做。也就是说,写这个应用的人,也是在 TLS 自动续期挂掉时被叫醒的人,而且能直接修应用,而不是把问题推给平台。 - -这是我自己的生产环境:三台自管的 Docker 主机,162 个容器分布在 78 个 compose stack 上,跑着真正对外的服务——客户网站、邮件平台、CI/CD、工作流自动化、访问统计,以及这个博客。没有云平台把它粘在一起,也没有团队在运维。下面是这套架构,以及两次改变了我「怎么检查自己的工作」的故障。 - -## 它的样子 - -| 主机 | 承担什么 | 容器 | Compose stack | -|---|---|---|---| -| Synology DSM | 存储、SSO、大部分内部服务 | 86 | 44 | -| unRaid | CI runner、媒体流水线、监控 | 37 | 21 | -| Ubuntu 24.04 VPS | 公网入口、邮件平台、客户站点 | 39 | 13 | - -这个划分是刻意的,不是历史遗留。VPS 承担的是「家里网断了也必须可达、必须快」的东西,因为公网流量和客户邮件都落在那里。Synology 承担需要磁盘和稳定文件系统的部分,以及所有其他服务都信任的身份源。unRaid 跑 CI runner 和那些又重又突发的批处理任务——否则它们会和服务抢内存。 - -## 让三台主机像一套系统的东西 - -**统一的入口模式。** 每台主机都跑一个 Traefik 反向代理,配自动化的 ACME 证书,所以证书自己续期,也没有哪个服务需要自己保管证书文件。后面是一套统一的路由和跳转约定,公网域名前面再套 Cloudflare。 - -**统一的身份源。** authentik 用 OIDC 和 proxy provider 做 SSO,所以新增一个内部服务是「在一个地方加一个应用」,而不是「在表格里再加一个密码」。对外的服务保持匿名可访问;其余的都从这里认证。 - -**统一的监控。** Prometheus、Grafana、cAdvisor 和 node-exporter 铺在三台主机上,收进同一个 Grafana 而不是三块面板——因为真正有意思的故障,都是跨主机的那种。 - -**统一的交付路径。** 自建的 Gitea Actions runner 负责构建和部署。这个博客就是走这条流水线:提交、runner 接单、容器重建、Cloudflare 把新构建送出去。 - -**经过验证、而不是假设的备份。** NAS 上的快照备份,加上 Duplicati 和 restic 任务,并把恢复步骤写下来——因为没验证过的备份只是一种感觉,不是备份。 - -## 失败一:仪表盘在骗我 - -搭监控的时候我选择相信 Grafana 显示的东西,结果有三块面板是错的。 - -cAdvisor 报出来的「容器」其实是 cgroup 的伪条目,把容器数量虚报了。我的「总容量」面板把一个 NAS 卷算了三遍,因为三个看起来差不多的挂载点被当成独立文件系统抓取了——这个数字看起来完全合理,而「看起来合理」正是它危险的地方。还有一台虚拟机根本不导出 CPU 频率,于是那块面板一直是空的,而我把它读成「暂时没数据」,而不是「这个 exporter 配错了」。 - -这三件事都没有弄坏任何服务。但三件事都会让我向客户报出一个假数字,因为仪表盘上的错数字和真数字长得一模一样。整个过程我写在 [One Prometheus for unRaid, a Synology NAS, and a VPS](https://blog.hoelee.com/posts/one-prometheus-for-unraid-synology-and-a-vps/) 里了。 - -## 失败二:少了一个配置文件,三种故障模式 - -我的团队密码管理器 Passbolt 开始返回 504,它的定时任务看起来卡住了。最后发现是三种不同的故障模式、同一个根因:一个只存在于运行中的容器里、从来没进 compose 文件的配置值。 - -空的 GPG fingerprint 让邮件发不出去,而发邮件这一步被放在定时任务里,于是整个任务挂住,UI 跟着一起挂。修好之后确实好了——直到容器被重建,配置被抹掉,原来的症状又回来了,看起来像问题自己复发。接着我为了追这两个问题引入的 `ssl.force`,在反向代理后面造成了跳转循环。 - -三个症状、三个晚上、一个教训:没有进版本控制的配置,就不算配置。完整的过程写在 [Passbolt UI Kept Hanging — Three Failure Modes From One Missing Config File](https://blog.hoelee.com/posts/passbolt-hang-three-failure-modes/)。 - -## 我怎么让数字保持诚实 - -简历上的数字会悄悄过期。我的数字是可以重新算出来的:一个小脚本通过 Portainer API 读活的 Docker 端点,逐台主机统计容器和 compose stack 的数量,所以「162 个容器、78 个 compose stack」是按需重新测量,而不是记住它曾经为真的那一天。同一个脚本还会打印出一份「绝不能出现在任何对客户材料里」的服务清单。 - -背后的规则很简单:一个无法被重新核对的数字,就是一个没人能在面试里、在报价里、在客户问「你怎么算出来的」那一通电话里守住的说法。凡是不能重新测量的数字,就不写进文档。 - -## 我会做得不一样的地方 - -**第一天就把每一个配置值放进 compose 文件**,包括那些感觉「属于机器而不是属于服务」的。Passbolt 那次复发,只因为一个修复活在容器里。 - -**对「没有数据」告警,而不是只对「坏数据」告警。** 一块空白的面板和一台健康服务,在仪表盘上长得一样。如果某个 exporter 十分钟没送来任何东西,那就是该告警的事件。 - -**用专门用来衡量可用性的东西去衡量可用性。** 指标流水线告诉你系统现在表现如何,它并不统计「成功请求 ÷ 总请求」。如果一个百分比要出现在客户面前,它需要一个按计划探测端点并记录结果的探针;否则诚实的回答是「有监控」,而不是一个数字。这个区别比数字本身更重要。 - -## 结果 - -三台主机、162 个容器、78 个 compose stack、一个人——加上自动化证书、统一 SSO、跨主机监控、经过验证的备份和自建 CI/CD。它同时跑过客户网站、一个邮件平台、一个 Telegram 客服 bot、排程自动化和这个博客;也正是它让我能把项目从「这是需求」做到「已经上线、有监控、有备份」,而不用把后半段交给别人。 - -## 想给你的生意也做一套? - -如果你需要一个既能写应用、又能跑它脚下那套基础设施的人——Docker 和 Traefik、自动化 TLS、SSO、监控、邮件、备份、CI/CD——我做的就是这个,而且我更想聊你的环境,而不是发一份宣传单。 - -**WhatsApp:[+60 12-797 2969](https://wa.me/60127972969)** · **Email:[me@hoelee.com](mailto:me@hoelee.com?subject=Infrastructure%20setup%20enquiry)** · **[hoelee.com](https://hoelee.com)** - -网站设计开发是我的主业;自托管基础设施、监控与自动化是它的另一半。 -```` - -### 🇬🇧 英文版原文 (English Markdown Primary) -````markdown ---- -title: "Running Production Infrastructure Solo: 162 Containers Across Three Hosts" -description: "One operator, three hosts, 162 containers in 78 compose stacks — Traefik, SSO, monitoring, mail, CI/CD and backups — and the two failures that changed how I verify my own numbers." -pubDate: 2026-10-06 -category: case-studies -blueprint: self-hosted-infrastructure -blueprintLayer: L1-compute-storage-network -tags: [docker, traefik, monitoring, infrastructure, devops] -ogImage: /og/running-production-infrastructure-solo.jpg -banner: /banners/running-production-infrastructure-solo.jpg -draft: false ---- - -## Why this matters - -A business that sells software needs two things at once: an application that -does the job, and the machinery underneath that keeps it reachable, backed -up and secure. Agencies usually split those two between a developer and a -hosting company, which is how you end up with a developer who cannot see the -server and a hosting company that cannot read the code. - -I run both. That means the person who wrote the application is also the -person who gets woken up when TLS renewal stops working, and who can fix the -application rather than blame the platform. - -This is my own production footprint: three self-managed Docker hosts running -162 containers across 78 compose stacks, serving live public services — -client websites, a mail platform, CI/CD, workflow automation, analytics and -this blog. No cloud platform holds it together, and no team operates it. -Here is the architecture, and the two failures that changed how I check my -own work. - -## The shape of it - -| Host | What it carries | Containers | Compose stacks | -|---|---|---|---| -| Synology DSM | storage, SSO, the bulk of internal services | 86 | 44 | -| unRaid | CI runner, media pipeline, monitoring | 37 | 21 | -| Ubuntu 24.04 VPS | public entry point, mail platform, client sites | 39 | 13 | - -The split is deliberate rather than historical. The VPS carries what must -stay reachable and fast when the home connection is not, because that is -where public traffic and client mail land. The Synology carries what needs -disk and a stable filesystem, plus the identity provider that every other -service trusts. unRaid runs the CI runner and the heavy, spiky batch work -that would otherwise compete with the services for RAM. - -## What makes three hosts one system - -**One ingress pattern.** Each host runs a Traefik reverse proxy with automated ACME TLS, so certificates renew themselves and no service owns a certificate file. Behind it there is one convention for routing and redirects, and Cloudflare sits in front of the public names. - -**One identity provider.** authentik handles SSO with OIDC and proxy providers, so a new internal service is a new application in one place instead of a new password in a spreadsheet. Public services stay anonymous; everything else authenticates through it. - -**One monitoring stack.** Prometheus, Grafana, cAdvisor and node-exporter across the hosts, in a single Grafana rather than three dashboards, because the interesting failures are the ones that cross host boundaries. - -**One delivery path.** Self-hosted Gitea Action runners build and deploy. This blog ships through that pipeline — commit, runner picks it up, container rebuilds, Cloudflare serves the new build. - -**Backups that are tested rather than assumed.** Snapshot-based backup on the NAS plus Duplicati and restic jobs, with restore procedures written down, because an untested backup is a feeling, not a backup. - -## Failure 1: the dashboard was lying to me - -When I built the monitoring stack I trusted what Grafana showed me, and -three of the panels were wrong. - -cAdvisor reported "containers" that were really cgroup pseudo-entries, which -inflated the container count. My total-storage panel counted one NAS volume -three times, because three near-identical mount points were being scraped as -separate filesystems — the number looked plausible, which is exactly what -made it dangerous. And one virtual machine exported no CPU frequency at all, -so its panel stayed empty and I read that as "no data yet" instead of "this -exporter is misconfigured". - -None of those broke a service. All three would have made me report something -false to a client, because a wrong number on a dashboard is -indistinguishable from a right one. I wrote the whole thing up in -[One Prometheus for unRaid, a Synology NAS, and a VPS](https://blog.hoelee.com/posts/one-prometheus-for-unraid-synology-and-a-vps/). - -## Failure 2: one missing config file, three failure modes - -Passbolt, my team password manager, started returning 504s and its cron job -appeared to hang. It turned out to be three separate failure modes with one -root cause: a configuration value that existed inside the running container -but never in the compose file. - -A null GPG fingerprint stalled mail delivery, and because the mail send sat -inside the scheduled job, the whole job hung and took the UI with it. The -fix worked — until the container was recreated, which wiped it and restored -the original symptom, so the problem appeared to come back on its own. Then -`ssl.force` behind a reverse proxy produced a redirect loop that I had -introduced myself while chasing the other two. - -Three symptoms, three sessions, one lesson: configuration that is not in -version control is not configuration. The full sequence is in -[Passbolt UI Kept Hanging — Three Failure Modes From One Missing Config File](https://blog.hoelee.com/posts/passbolt-hang-three-failure-modes/). - -## How I keep the numbers honest - -Numbers on a CV go stale quietly. Mine are re-derivable: a small script -reads the live Docker endpoints through the Portainer API and counts -containers and compose stacks per host, so "162 containers across 78+ -compose stacks" is re-measured on demand rather than remembered from the day -it was true. The same script prints the list of services that must never -appear in anything client-facing. - -The rule behind it is simple. A number that cannot be re-checked becomes a -claim nobody can defend — in an interview, in a proposal, or on a call when -a client asks how you got it. If I cannot re-measure a figure, it does not -go in the document. - -## What I would do differently - -**Every configuration value in the compose file from day one**, including the ones that feel like secrets of the machine rather than of the service. The Passbolt relapse existed only because a fix lived in a container. - -**Alert on the absence of data, not just on bad data.** A blank panel and a healthy service look identical on a dashboard. If nothing arrives from an exporter for ten minutes, that is the alert. - -**Measure availability with something built to measure availability.** A metrics pipeline tells you how a system is behaving; it does not count successful requests against total requests. If a percentage is going to appear in front of a client, it needs a probe checking endpoints on a schedule and recording the result — otherwise the honest answer is "monitored", not a number. That distinction matters more than the number. - -## The result - -Three hosts, 162 containers, 78 compose stacks, one operator — with -automated TLS, central SSO, cross-host monitoring, tested backups and -self-hosted CI/CD. It has run client websites, a mail platform, a Telegram -support bot, scheduling automation and this blog at the same time, and it is -the reason I can take a project from "here is the requirement" to "it is -live, monitored and backed up" without handing the second half to somebody -else. - -## Want this for your business? - -If you need someone who can build the application **and** run the -infrastructure it lives on — Docker and Traefik, automated TLS, SSO, -monitoring, mail, backups, CI/CD — I do exactly this, and I would rather -talk about your setup than send a brochure. - -- WhatsApp: [wa.me/60127972969](https://wa.me/60127972969) -- Email: [me@hoelee.com](mailto:me@hoelee.com?subject=Infrastructure%20setup%20enquiry) -- More: [hoelee.com](https://hoelee.com) -```` - ---- - -## 文章 05 / 10:数字商品的自愈式访问控制:NocoDB、n8n 与 AList -- **Slug**: `self-healing-digital-goods-entitlements` -- **英文标题**: Self-Healing Access Control for Digital Goods: NocoDB, n8n, and AList -- **分类**: `case-studies` | **发布日期**: 2026-09-18 -- **线上地址**: https://blog.hoelee.com/posts/self-healing-digital-goods-entitlements/ (EN) | https://blog.hoelee.com/posts/zh/self-healing-digital-goods-entitlements/ (ZH) -- **本篇审核状态**: ⏳ 待审核 (Pending) - -### ✍️ 顾问审阅意见区 (Review Feedback) -```text -【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 -【事实与数字核对】: -【人设与用词卫生】: -【CRO与转化建议】: -``` - -### 🇨🇳 中文版原文 (Chinese Markdown Twin) -````markdown ---- -title: "数字商品的自愈式访问控制:NocoDB、n8n 与 AList" -description: "我如何用五个工作流搭出一套权限系统,自动授予、到期失效并持续修复客户的文件访问——包括一个构建期代码共享技巧,以及一个设计上刻意不泄露任何信息的公开接口。" -pubDate: 2026-09-18 -category: case-studies -blueprint: sme-digital-suite -blueprintLayer: L3-entitlement-backoffice -tags: [n8n, nocodb, alist, access-control, docker, automation, digital-goods] -ogImage: /og/zh-self-healing-digital-goods-entitlements.jpg -banner: /banners/self-healing-digital-goods-entitlements.jpg ---- - -我卖数字产品——文件、美术素材、授权资源——并通过一个自建的文件门户交付。真正的难题从来不是存储,而是**授权**:确保客户在购买时拿到恰好他们买下的目录,拿到恰好他们付费的时长,并且在停止付费时访问权限真的被收回。 - -手工做这件事,前十个客户没问题。一百个就不行了,而且失败的方�式很具体、也很讨厌:静默失败。订阅到期而客户继续下载时,不会有任何报错。你只是一直在给一个几个月前就停止付费的人供文件。 - -所以我把它做成五个 n8n 工作流,把访问权限当作**派生状态**来处理——从我的业务数据库计算得出,应用到文件服务器上,并持续重新校验。下面是它的架构、让它可维护的代码共享技巧,以及那个公开接口背后的安全推理。 - -## 为什么这件事重要 - -对一个数字商品生意来说,访问控制*就是*产品本身。你保护的不是一座仓库,你保护的是你卖掉的那个东西。两种失败模式会真金白银地亏钱: - -- **授予不足**——付费客户拿不到他买的东西,而你是从愤怒的消息里而不是监控告警里知道的。 -- **授予过度**——已到期或已撤销的客户继续有访问权,而泄露会一直不可见,直到有人转卖你的目录。 - -手工管理最终会必然地导致这两种。解法是不要再把一次授权当成*你做的一件事*,而把它当成*你数据的一个函数*:给定客户当前的购买记录,他现在应该能访问什么?算出来、应用它,然后按计划证明它仍然成立。 - -## 系统的形状 - -五个工作流,每个只做一件事: - -| 工作流 | 触发器 | 职责 | +| 时间 | 可用 | 事件 | |---|---|---| -| **W1** — Customer Provision & Status Lifecycle | NocoDB webhook(客户行) | 创建/更新文件服务器用户;状态变更时启用或禁用 | -| **W2** — CustomerProduct Sync | NocoDB webhook(购买行) | 重新计算并应用该客户被允许的路径 | -| **W3** — Expiry Sync | Cron,每 5 分钟 | 扫描即将到期的授权;移除已失效的路径 | -| **W4** — Daily Full Reconciliation | Cron 03:00 + 手动 webhook | 对比全体客户的*期望*与*实际*;修复漂移;记录日志 | -| **W5** — Footer Purchase Check | 公开 GET webhook | 让门户展示客户自己的购买记录;只读 | +| 08:59 → 09:24 | 1134.1 GiB | 平——什么都没在回收 | +| **09:29** | **+69.0 GiB** | Class 快照 `…10.14-09.29.02` 轮转 | +| **09:34** | **+46.8 GiB** | Video 快照 `…10.14-09.30.35` 轮转 | +| **15:28:45** | — | DSM 日志:`Start to empty all recycle bins.` | +| **15:34** | **+5.0 GiB** | 清回收站结束——里面只有 5 GiB | +| 16:35 → 17:39 | **−39 GiB** | 新数据写入(一阵爆发) | +| 15:00 → 20:44 | **−47.2 GiB** | 净值:这个卷那天下午**丢**了空间 | -数据存在 **NocoDB**(一个自建的 Airtable 类数据库)里,包括 Customers、CustomerProducts、Products、Resources 和 AccessGrants 几张表。文件服务器是 **AList**,它为每个客户提供一个用户和一个角色,角色的 `permission_scopes` 就是一串路径。 +两次回收,合计约 121 GiB;然后 47 GiB 的新写入把下午吃掉了。「什么都没回来」是我这边的读法错误:我拿早上和晚上比,而晚上里面多了一整天的写入。 -至关重要的设计决策:**NocoDB 是业务真相来源,AList 只是执行状态。** 同步是单向的。在 AList 管理后台手动改一笔不算配置变更——那叫漂移,W4 会把它修复回去。 +我特意手动清空的回收站是 **5 GiB**;我压根没想到的快照是 **115.8 GiB**。这个比例就是全部故事。 -## 算法:这个客户*应该*有什么? - -一切都系于一个函数。客户的期望路径是两个来源的并集: - -1. 所有可从**有效的、未过期**购买记录到达的资源。 -2. 所有通过**有效的、未过期**手工授权直接授予的资源。 - -有意思的情况是:同一个资源可以通过*两个不同*产品到达。如果客户买了产品 A(30 天后到期)和产品 B(200 天后到期),而两者都包含同一个目录,那么正确的到期时间是**较晚**的那一个——多买一样东西永远不该缩短你对它的访问权。 - -```js -// 对每个产品的资源,按路径保留最大的 expires_at。 -for (const c of cps) { - if (c.status && c.status !== 'active') continue; - if (c.expires_at && String(c.expires_at) <= today) continue; // 已过期 - const pid = linkId(c.product); - if (!pid) continue; - const res = (await ncGet(ctx, - `/api/v2/tables/${T_PROD}/links/${LNK_PROD_RES}/records/${pid}`)).list || []; - const exp = c.expires_at; - for (const r of res) { - const p = resPath[r.Id]; - if (!p) continue; - const cur = desired[p]; - if (!cur || !cur.expires || (exp && exp > cur.expires)) { - desired[p] = { expires: exp || null, permission: cur?.permission ?? 0 }; - } - } -} -``` - -注意边界:`<= today`。**当天到期就算已过期。** 到期检查上的一个差一错误,就是订阅期与白送一天之间的区别;如果你不把它写明确,你一定会写错,而且会错在对客户有利的那一边。 - -## 问题所在:n8n 的 Code 节点无法共享代码 - -这个约束塑造了整个代码库。n8n 的 Code 节点是自包含的:没有 `require`、没有 `import`、也没有访问共享模块的文件系统权限。所以最自然的结构——一个授权算法,被 W1、W2、W3、W4 调用——恰恰是这个平台不让你做的事。 - -把那个函数复制粘贴进四个节点,注定是一场维护灾难。四份到期规则的拷贝,就是四次它们互相不一致的机会,而一个用四种方式计算访问权限的系统,比没有系统更糟。 - -解法是让共享发生在**构建期**而不是运行期: - -- `shared/effective-grants.js` 是唯一真相来源,而且它被写成自包含的:没有 `require`、没有 `process.exit`、函数外没有顶层 `return`。它通过一个 `ctx` 参数(`{ $env, helpers }`)接收配置,而不是去抓全局变量——这带来一个令人愉快的副作用:它**可以在 n8n 之外做单元测试**。 -- `gen_w1.js`、`gen_w2.js`、`gen_w3.js`、`gen_w4.js` 读取这个文件,把它内联进工作流的 Code 节点主体,并更新工作流。 - -结果是:一个算法、四个工作流、零运行期依赖——而且这个函数可以在碰到任何线上系统之前,用纯 Node 测试。代码在*产物*里重复,但在*源码*里从不重复,这和打包器做的是同一笔交易。 - -一个 n8n 特有的细节值得知道:**自定义环境变量只有在 Code 节点里通过 `$env` 才可靠可读——`process.env` 在那里不可靠。** 这就是为什么每个工作流都有一个显式的「Load Env」节点,把它需要的值提升到 item 上,而不是哪里方便就在哪里读配置。 - -## 让到期处理可以安全自动化 - -W3 每五分钟跑一次,对即将到期的授权做对账。有两个细节让一个 cron 任务可以安全地改动线上权限: - -**只有当访问权限真的用完时才禁用。** 一个天真的「如果没有期望路径就禁用用户」规则是危险的——它会乐于禁用一位只是还没被授予任何东西的新客户。守卫条件是显式的: - -```js -// 只在「曾经有权限、现在一个都没有」的客户身上禁用。 -// currentPaths.length > 0 避免干掉一个全新的、尚未授权的客户。 -const shouldDisable = AUTO_DISABLE && nowEmpty - && cust.status === 'active' && currentPaths.length > 0; -``` - -**它有 dry-run 模式。** 容器上的 `W3_DRY_RUN=true`(或 W4 手动 webhook 上的查询参数)会让扫描计算并报告它的计划,同时**执行零写入**。能在让一个计划任务动手之前先问「你会做什么?」,是我在任何自动化里加过的最有用的安全功能。 - -```js -const DRY_RUN = ($env.W3_DRY_RUN || '').toLowerCase() === 'true'; -``` - -## 每日修复:假定你一定会漂移 - -W4 是那个我会说才是真正产品的工作流。它在 03:00 运行,遍历每个客户,对比期望状态与实际状态——然后修复差异并**验证修复**。 - -它处理的漂移矩阵: - -- **应当是有效的** → 用户必须存在(**先用用户名查找**,以避免在存储的 ID 丢失时创建重复用户)、处于启用状态,并且恰好带有计算出的角色权限范围。 -- **应当是无效的** → 禁用,并清空权限范围。待处理客户完全不建用户——不自动创建。 -- **悬空引用** → 存储的用户或角色 ID 指向一个已不存在的记录。按名字查找,找到就收编,找不到就重建。 -- **用户名漂移** → 只检测并*记录日志*,绝不做破坏性迁移。 - -每一次修复之后都会重新读取文件服务器状态来验证。失败验证会被记为 `verify_failed` 而不是假定成功,而对账日志只接收**漂移、修复和错误三类记录**——健康客户不产生任何行。最后这个选择正是让日志可用的原因:如果它是空的,一切正常,你不必读着一千行「无变化」去找那一条重要的。 - -## 那个公开接口,以及为什么没有 HMAC - -W5 让文件门户的页脚能展示已登录客户自己的购买记录和到期日期。它是一个**公开** webhook,而它的安全推理是我最刻意对待的部分。 - -直觉是用 HMAC 给请求签名。我没这么做,理由值得直说:**密钥必须发到浏览器,所以签名只是表演。** 一个每个客户端都持有的共享密钥什么都保护不了——它只增加了一层仪式,让这个接口*看起来*经过验证。 - -所以这个接口依赖的是真正成立的东西: - -- **CORS 锁定单一来源。** 响应带有 - `Access-Control-Allow-Origin: https://drive.example.com`,所以只有门户自己的页面能在浏览器里读取响应。 -- **数据最小化是设计出来的。** 响应只返回产品名、到期日期、展示状态和公开目录路径。没有内部数据库 ID、没有客户个人信息、没有任何其他客户的信息。 -- **边缘限流**,通过请求路径上的一条 WAF 规则,削弱用户名枚举。 - -还有一个细微的架构选择:**用户名来自调用者自己的会话 token,在客户端解码**,而不是来自一个客户端可以自由设置的参数。这个接口从不向文件服务器认证,从而避开了一整类连接状态与设备注册副作用——否则每次页脚渲染都会引入这些副作用。 - -诚实的说法是:这个接口不是信任边界,我也不假装它是。它向客户展示的只是他们本来就知道的关于自己的信息,走的是一个对任何其他人无用的响应形状。 - -## 教会我最多的那个 bug:公网路径与级联故障 - -W5 最初是通过 NocoDB 的**公网**主机名——穿过一个 Cloudflare 隧道——去取数据的。测试中它工作良好。在真实负载下,它产生了这样一条链: - -1. 公网往返延迟在负载下超过 60 秒。 -2. nginx 上游超时触发 → **504**。 -3. 页脚客户端 fetch 的 8 秒超时**每秒重试一次**。 -4. 重试堆积了连接。 -5. 这些连接耗尽连接池 → 无关请求收到 **503**。 - -一个慢依赖变成了一次不同服务的级联故障。修法是停止跨过整个互联网去访问同一个 Docker 网络上的东西: - -```js -// n8n 与 NocoDB 同处 bridge_hoelee 网络;NocoDB 监听 :10380。 -// 走公网路由会引入 CF 隧道抖动,且可能超过代理超时。 -const NOCODB_URL = 'http://nocodb:10380'; -``` - -**内部约 30 ms,公网 300 ms 以上,且没有隧道抖动**——整条故障链消失了,因为触发条件(数秒级延迟)已不可能出现。 - -这个教训可以很好地泛化到这个技术栈之外:**当一个服务和它的依赖在同一个容器网络里时,用公网主机名就是一个等着负载来触发的 bug。** 而当你看到一个 503 出现在一个 504 的下游时,去找那个激进重试的客户端——重试循环通常才是放大器,而不是原始问题。 - -## 我会怎么做得不一样 - -1. **先做漂移修复,而不是最后做。** 我先写授权路径,然后到期扫描,最后才对账。回头看,对账才是让另外两个可以安全运行的东西,它应该从第一天就存在——因为「假定你一定会漂移」是一种设计立场,不是一个功能。 -2. **在任何工作流之前先写期望状态函数。** 它能待在 `shared/` 里、能在 n8n *之外*做单元测试,正是整个系统在四个工作流之间保持连贯的原因。如果我一开始就把逻辑粘贴进节点,我就会发布四份微妙的、彼此不同的到期规则。 -3. **永远不要在同一台主机的两个容器之间走公网。** 这条让我真的经历了一次故障,而它现在是我默认应用的规则,而不是每个集成都要重新发现一次。 -4. **从第一天就把 dry-run 开关放进去。** 事后加 `DRY_RUN` 很容易;而在没有它的情况下运行一个会改动权限的计划任务,是几周完全不必要的提心吊胆。 - -## 结果 - -五个工作流跑完整个授权生命周期:数据库里的一笔购买在几秒内变成可用访问,到期每五分钟扫一次,每夜的完整对账修复任何漂移并验证每次修复。一切健康时对账日志是空的——而大多数日子里,它说的就是这件事。 - -值得带走的设计原则,是让这件事变得可控的那一条:**别再「管理」访问权限,开始「断言」它。** 把客户应该拥有什么定义成业务数据的纯函数,在数据变化时应用这个函数,并按计划重新断言它以捕获其他所有情况。这样系统就不需要你小心翼翼——它只需要你在一个函数里,一次性地正确。 - ---- - -## 想让你的生意也用上这套? - -如果你卖数字产品,还在手工授予文件访问权限——或者你不确定上个月到期的客户是否真的已经失去访问权——我搭的正是这套东西:自建授权系统,访问权限从你的数据计算得出、自动到期、每夜自我修复。我熟悉 NocoDB、n8n、AList 和 Docker,并且会把文档一并交付,让你不用依赖我也能运维。 - -欢迎联系 [me@hoelee.com](mailto:me@hoelee.com?subject=%E6%95%B0%E5%AD%97%E5%95%86%E5%93%81%E8%AE%BF%E9%97%AE%E6%8E%A7%E5%88%B6) -或 WhatsApp [+60 12-797 2969](https://wa.me/60127972969),也可以看看我在 -[hoelee.com](https://hoelee.com) 做什么。 -```` - -### 🇬🇧 英文版原文 (English Markdown Primary) -````markdown ---- -title: "Self-Healing Access Control for Digital Goods: NocoDB, n8n, and AList" -description: "How I built a five-workflow entitlement system that grants, expires, and continuously repairs customer file access — with a build-time code-sharing trick and a public endpoint designed to leak nothing." -pubDate: 2026-09-18 -category: case-studies -blueprint: sme-digital-suite -blueprintLayer: L3-entitlement-backoffice -tags: [n8n, nocodb, alist, access-control, docker, automation, digital-goods] -ogImage: /og/self-healing-digital-goods-entitlements.jpg -banner: /banners/self-healing-digital-goods-entitlements.jpg ---- - -I sell digital products — files, artwork, licensed assets — and deliver them -through a self-hosted file portal. The hard problem was never storage. It was -**entitlement**: making sure that when someone buys, they get exactly the -folders they paid for, for exactly as long as they paid for, and that when -they stop paying, the access actually goes away. - -Doing that by hand works for the first ten customers. It does not work for a -hundred, and it fails in a specific and nasty way: silently. Nothing errors -when a subscription expires and the customer keeps downloading. You just keep -serving files to someone who stopped paying months ago. - -So I built it as five n8n workflows that treat access as **derived state** — -computed from my business database, applied to the file server, and -continuously re-verified. Here's the architecture, the code-sharing trick that -makes it maintainable, and the security reasoning behind the one public -endpoint. - -## Why it matters - -For a digital-goods business, access control *is* the product. You're not -protecting a warehouse; you're protecting the thing you sold. Two failure modes -cost real money: - -- **Under-granting** — a paying customer can't reach what they bought, and you - find out from an angry message rather than a monitoring alert. -- **Over-granting** — expired or revoked customers keep access, and the leak - is invisible until someone resells your catalog. - -Manual administration guarantees both, eventually. The fix is to stop treating -a grant as a *thing you do* and start treating it as a *function of your data*: -given the customer's current purchases, what should they be able to reach right -now? Compute it, apply it, and then prove it's still true on a schedule. - -## The shape of the system - -Five workflows, each with one job: - -| Workflow | Trigger | Responsibility | -|---|---|---| -| **W1** — Customer Provision & Status Lifecycle | NocoDB webhook (customer row) | Create/update the file-server user; enable or disable on status change | -| **W2** — CustomerProduct Sync | NocoDB webhook (purchase row) | Recompute and apply that customer's allowed paths | -| **W3** — Expiry Sync | Cron, every 5 minutes | Sweep expiring entitlements; deselect paths that lapsed | -| **W4** — Daily Full Reconciliation | Cron, 03:00 + manual webhook | Compare *desired* vs *actual* for everyone; repair drift; log | -| **W5** — Footer Purchase Check | Public GET webhook | Let the portal show a customer their own purchases; read-only | - -The data lives in **NocoDB** (a self-hosted Airtable-style database) as -Customers, CustomerProducts, Products, Resources, and AccessGrants. The file -server is **AList**, which gives each customer a user and a role whose -`permission_scopes` is a list of paths. - -The crucial design decision: **NocoDB is the business source of truth. AList is -only enforcement state.** Sync runs one way. A manual tweak in the AList admin -UI is not a configuration change — it's drift, and W4 repairs it back. - -## The algorithm: what *should* this customer have? - -Everything hinges on one function. Desired paths for a customer is the union of -two sources: - -1. Every resource reachable from an **active, not-yet-expired** purchase. -2. Every resource granted directly via an **active, not-yet-expired** manual grant. - -The interesting case is a resource reachable through *two* different products. -If a customer bought Product A (expires in 30 days) and Product B (expires in -200 days) and both include the same folder, the correct expiry is the **latest** -one — buying more of something should never shorten your access to it. - -```js -// For each product's resources, keep the MAX expiry per path. -for (const c of cps) { - if (c.status && c.status !== 'active') continue; - if (c.expires_at && String(c.expires_at) <= today) continue; // expired - const pid = linkId(c.product); - if (!pid) continue; - const res = (await ncGet(ctx, - `/api/v2/tables/${T_PROD}/links/${LNK_PROD_RES}/records/${pid}`)).list || []; - const exp = c.expires_at; - for (const r of res) { - const p = resPath[r.Id]; - if (!p) continue; - const cur = desired[p]; - if (!cur || !cur.expires || (exp && exp > cur.expires)) { - desired[p] = { expires: exp || null, permission: cur?.permission ?? 0 }; - } - } -} -``` - -Note the boundary: `<= today`. **Expiring today counts as expired.** Off-by-one -on an expiry check is the difference between a subscription period and a free -extra day, and if you're not explicit about it you'll get it wrong in the -customer's favour. - -## The problem: n8n Code nodes can't share code - -Here's the constraint that shaped the whole codebase. n8n Code nodes are -self-contained: there's no `require`, no `import`, no filesystem access to a -shared module. So the obvious structure — one grants algorithm, called by W1, -W2, W3, and W4 — is exactly what the platform prevents. - -Copy-pasting that function into four nodes would have been a guaranteed -maintenance disaster. Four copies of an expiry rule is four chances for them to -disagree, and a system that computes access four different ways is worse than -no system. - -The fix was to make the sharing happen at **build time** instead of run time: - -- `shared/effective-grants.js` is the single source of truth, and it's written - to be self-contained: no `require`, no `process.exit`, no top-level `return` - outside a function. It also takes its config through a `ctx` argument - (`{ $env, helpers }`) rather than reaching for globals — which has the happy - side effect that it's **unit-testable outside n8n entirely**. -- `gen_w1.js`, `gen_w2.js`, `gen_w3.js`, `gen_w4.js` read that file, inline it - into the workflow's Code node body, and update the workflow. - -The result is one algorithm, four workflows, zero runtime dependencies — and a -version of the function that I can test with plain Node before it ever touches -a live system. The code is duplicated in *artifacts* but never in *sources*, -which is the same tradeoff a bundler makes. - -One n8n-specific wrinkle worth knowing: **custom environment variables are only -reliably readable via `$env` inside a Code node — `process.env` is not -dependable there.** That's why every workflow has an explicit "Load Env" node -that lifts the values it needs onto the item, rather than reading config -wherever it's convenient. - -## Making expiry safe to automate - -W3 runs every five minutes and reconciles expiring entitlements. Two details -make it safe to let a cron job modify live access: - -**It only disables when access genuinely ran out.** A naive "if no desired -paths, disable the user" rule is dangerous — it will happily disable a -brand-new customer who simply hasn't been granted anything yet. The guard is -explicit: - -```js -// Only disable when a customer that HAD scopes now has none. -// currentPaths.length > 0 avoids killing a fresh, not-yet-granted customer. -const shouldDisable = AUTO_DISABLE && nowEmpty - && cust.status === 'active' && currentPaths.length > 0; -``` - -**It has a dry-run mode.** `W3_DRY_RUN=true` on the container (or a query -parameter on the manual webhook for W4) makes the sweep compute and report its -plan while performing **zero writes**. Being able to ask "what would you do?" -before letting a schedule do it is the single most useful safety feature I've -added to any automation. - -```js -const DRY_RUN = ($env.W3_DRY_RUN || '').toLowerCase() === 'true'; -``` - -## The daily repair: assuming you'll drift - -W4 is the workflow I'd argue is the real product. It runs at 03:00, walks every -customer, and compares desired state against actual state — then repairs the -difference and **verifies the repair**. - -The drift matrix it handles: - -- **Should be active** → user must exist (looked up *by username first*, to - avoid creating duplicates if a stored ID was lost), be enabled, and carry - exactly the computed role scopes. -- **Should be inactive** → disabled, with scopes emptied. Pending customers - stay without a user entirely — no auto-creation. -- **Dangling references** → a stored user or role ID points at a record that no - longer exists. Look it up by name, adopt it if found, recreate if not. -- **Username drift** → detected and *logged*, never destructive-migrated. - -Every repair is verified by re-reading the file server's state afterwards. A -failed verification is logged as `verify_failed` rather than assumed successful, -and the reconciliation log only receives **drift, repair, and error rows** — -healthy customers produce nothing. That last choice is what makes the log -usable: if it's empty, everything is fine, and you don't have to read past a -thousand "no change" lines to find the one that matters. - -## The public endpoint, and why there's no HMAC - -W5 lets the file portal's footer show a signed-in customer their own purchases -and expiry dates. It's a **public** webhook, and the security reasoning is the -part I'm most deliberate about. - -The obvious instinct is to sign requests with an HMAC. I didn't, and the reason -is worth stating plainly: **the key would have to ship to the browser, so the -signature would be theatre.** A shared secret that every client holds protects -nothing — it just adds ceremony that makes the endpoint *look* verified. - -So the endpoint relies on things that actually hold: - -- **CORS locked to one origin.** The response carries - `Access-Control-Allow-Origin: https://drive.example.com`, so only the portal's - own pages can read the response in a browser. -- **Minimal data by design.** The response returns product name, expiry date, - display state, and public folder paths. No internal database IDs, no customer - PII, nothing about other customers. -- **Rate limiting at the edge,** via a WAF rule on the request path, to blunt - username enumeration. - -And one subtle architectural choice: **the username comes from the caller's own -session token, decoded client-side**, rather than from a parameter the client -can set freely. The endpoint never authenticates to the file server, which -avoids a whole class of connection state and device-registration side effects -that a server-side login would introduce on every footer render. - -The honest framing: this endpoint is not a trust boundary, and I don't pretend -it is. It shows a customer what they already know about themselves, over a -response shape that's useless to anyone else. - -## The bug that taught me the most: public path, cascading failure - -W5 originally fetched data by calling NocoDB at its **public** hostname — -through a Cloudflare tunnel. It worked in testing. Under real load it produced -this chain: - -1. Public round-trip latency exceeded 60 seconds under load. -2. nginx upstream timeout fired → **504**. -3. The footer's client-side fetch had an 8-second timeout and retried **every - second**. -4. Retries piled up connections. -5. Those connections exhausted the pool → **503** for unrelated requests. - -A slow dependency became a cascading outage of a different service. The fix -was to stop crossing the internet to reach something on the same Docker -network: - -```js -// n8n and NocoDB share the `bridge_hoelee` network; NocoDB listens on :10380. -// The public route added CF-tunnel jitter and could exceed the proxy timeout. -const NOCODB_URL = 'http://nocodb:10380'; -``` - -**~30 ms internal versus 300 ms+ public, with no tunnel variance** — and the -entire failure chain disappeared, because the trigger condition (multi-second -latency) can no longer occur. - -The lesson generalises well beyond this stack: **when a service and its -dependency are in the same container network, the public hostname is a bug -waiting for load.** And when you see a 503 downstream of a 504, look for a -client that retries aggressively — the retry loop is usually the amplifier, not -the original problem. - -## What I'd do differently - -1. **Build the drift repair first, not last.** I wrote the grant path, then the - expiry sweep, then the reconciliation. In retrospect the reconciliation is - what makes the other two safe to operate, and it should have existed from - day one — because "assume you will drift" is a design stance, not a feature. -2. **Write the desired-state function before any workflow.** Having it live in - `shared/` and be unit-testable *outside* n8n is why the whole system stayed - coherent across four workflows. If I'd started by pasting logic into nodes, - I'd have shipped four subtly different expiry rules. -3. **Never cross the public internet between two containers on the same host.** - This one cost me a genuine outage, and it's a rule I now apply by default - rather than discovering per-integration. -4. **Put the dry-run switch in from the beginning.** Adding `DRY_RUN` after the - fact was easy; operating a scheduled job that mutates access *without* one - was an unnecessary few weeks of nerves. - -## The result - -Five workflows run the full entitlement lifecycle: a purchase in the database -becomes usable access within seconds, expiries sweep every five minutes, and a -nightly full reconciliation repairs any drift and verifies each repair. The -reconciliation log is empty when everything is healthy — which, most days, is -what it says. - -The design principle worth taking away is the one that made it tractable: -**stop administrating access, and start asserting it.** Define what a customer -should have as a pure function of your business data, apply that function -whenever the data changes, and re-assert it on a schedule to catch everything -else. Then the system doesn't need you to be careful — it just needs you to be -correct once, in one function. - ---- - -## Want this for your business? - -If you sell digital products and you're still granting file access by hand — -or you're not certain that expired customers lost access last month — I build -exactly this: self-hosted entitlement systems where access is computed from -your data, expires on its own, and repairs itself nightly. I work with -NocoDB, n8n, AList, and Docker, and I hand it back documented so you can -operate it without me. - -Reach me at [me@hoelee.com](mailto:me@hoelee.com?subject=Access%20control%20for%20digital%20goods) -or WhatsApp [+60 12-797 2969](https://wa.me/60127972969), or see what I do at -[hoelee.com](https://hoelee.com). -```` - ---- - -## 文章 06 / 10:自建语音转文字服务:打字速度的五倍,而且数据不出内网 -- **Slug**: `self-hosted-speech-to-text-api` -- **英文标题**: Your Own Speech-to-Text Server: Faster Than Typing, Private by Default -- **分类**: `case-studies` | **发布日期**: 2026-09-19 -- **线上地址**: https://blog.hoelee.com/posts/self-hosted-speech-to-text-api/ (EN) | https://blog.hoelee.com/posts/zh/self-hosted-speech-to-text-api/ (ZH) -- **本篇审核状态**: ⏳ 待审核 (Pending) - -### ✍️ 顾问审阅意见区 (Review Feedback) -```text -【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 -【事实与数字核对】: -【人设与用词卫生】: -【CRO与转化建议】: -``` - -### 🇨🇳 中文版原文 (Chinese Markdown Twin) -````markdown ---- -title: "自建语音转文字服务:打字速度的五倍,而且数据不出内网" -description: "我用一台带 GPU 的电脑自建了语音转文字 API。Windows、iPhone、iPad、Android 都能语音输入——私密、不限量,速度是打字的大约 5 倍。" -pubDate: 2026-09-19 -category: case-studies -tags: [whisper, cuda, stt, n8n, nginx, self-hosting, ai] -ogImage: /og/zh-self-hosted-speech-to-text-api.jpg -banner: /banners/self-hosted-speech-to-text-api.jpg ---- - -打字的办公效率里面,它是最慢的一环。一般人打字速度约每分钟 40 个字,但 -**说话是 130 字**。每一封邮件、每一份报价、每一份报告、每一次客服回复、每一 -条聊天消息,公司都在为这个差距付税——而付税的人通常是键盘打得最快的那个。 - -语音转文字可以把这个税省掉。但多数人采用的那套方案有两个问题:按人头收月费, -而且把你的声音——内部讨论、客户姓名、报价、合约内容——全部送到别人的云端。 - -所以我做了另一个版本:**一台办公室里的普通电脑,用它自己的 GPU,跑起一套 -语音转文字 API。**我的开发电脑、iPhone、iPad、Android 手机都通过它来语音输入。 -比打字快,不限量,而且没有任何数据离开我的内网。 - -以下是怎么做的——包括花掉我大半天时间的四个坑。 - -## 为什么值得做 - -语音转文字是办公自动化里杠杆最高、却又最不花哨的一环。具体来说,自建方案能给 -你这些东西: - -- **大约是打字的 5 倍吞吐量。**说话 130 wpm 对比打字约 40 wpm,口述一封 500 字 - 的邮件大约是说 4 分钟,而不是打 12 分钟。一天写 10 封邮件的人,每天省下一 - 小时。 -- **成本跟着硬件走,不跟人头走。**云端听写是按用户按月收费,而且一直收。这套 - 跑在你自己买的机器上。加到第 10 个员工,边际成本是零。 -- **不限长度,没有额度的焦虑。**没有分钟数上限,不会在星期五下午四点跳出来 - 说"你已用完本月额度"。 -- **你的音频还是你的。**医疗记录、法律草稿、人事对话、客户报价——语音天生 - 就是敏感数据。自建意味着转写内容不会离开公司。 -- **在任何已经获得焦点的程序里都能用。**不是那种"先转写、再复制粘贴"的网页 - 工具,而是可以直接在 Outlook、WhatsApp Web、CRM 或你自家内部系统里用的 - 输入键盘。 - -如果你公司里有一群人整天在写字,这件事的意义跟当年从拨号换到宽带是同一个 -量级——而且它花的只是一张你可能早就有的显卡。 - -## 需要准备什么 - -| 部件 | 我用的是 | 说明 | -|---|---|---| -| GPU 电脑 | RTX 3060(12 GB)的台式机 | 任何显存 ≥6 GB 的 NVIDIA 显卡都行,可以就是一台普通办公电脑 | -| 转写引擎 | `whisper.cpp` + CUDA | 开源免费 | -| 模型 | `large-v3`(约 2.9 GB) | 准确率最好;小模型占显存更少 | -| 分发层 | n8n + nginx 网关 | 加上认证,端点才能安全共享 | -| 客户端 | 桌面程序、iPhone、iPad、Android | 任何支持 OpenAI 转写 API 的客户端 | - -这台电脑不必专用。我的同时还在做开发、跑本地大模型推理和图像生成——模型在 -有请求时加载、空闲时卸载,所以它不会长期占着显存。 - -## 整体架构 - -最重要的设计决定是:**手机从来不直接连 GPU。**中间有一个看门人负责认证,GPU -本身一直待在私有网络里。 +## 为什么那张卡写着 running,却什么都不代表 ```text - iPhone / iPad / Android / 办公电脑 - │ - │ HTTPS + 每台设备独立的 API key - ▼ - ┌───────────────────────────┐ - │ https://stt.example.com │ 公网 HTTPS 入口 - │ reverse proxy │ - └─────────────┬─────────────┘ - ▼ - ┌───────────────────────────┐ - │ nginx 网关容器 │ 转发认证头,固定路由 - └─────────────┬─────────────┘ - ▼ - ┌───────────────────────────┐ - │ n8n 工作流 │ 校验 key,不符返回 401/403 - │ (音频永不落库) │ - └─────────────┬─────────────┘ - ▼ - ┌───────────────────────────┐ - │ PC 上的 whisper.cpp │ GPU 转写 - │ :20129 → {"text": …} │ - └───────────────────────────┘ +$ synostgreclaim --get-all-status --verbose +{"state":"running","num_subvolume_remain":1,"now_runnable":true} + schedule_table: 168 × 1 + run_time_option: run_all_time ``` -四层,每层只做一件事:代理终结 TLS,网关修好路由,n8n 负责授权,whisper 负责 -转写。最终对外是 `POST /v1/audio/transcriptions`——跟 OpenAI 同一个形状,所以 -任何 OpenAI 兼容的客户端都能零改动接上。 +`state: running` 加上 168 个 1 的调度表和 `run_all_time`,意思是这个任务被配置成**按设计 24×7 都处于 running**。它是调度状态,不是进度指示器——所以在某天完全无事可排的日子,这张卡照样这么写。而当时那台机器上**没有** `synostgreclaim` 进程、没有 btrfs balance、md2/dm-3 的 I/O 基本为零。那一刻没有任何东西在被回收,也没有任何东西卡住。 -## 开始动手 +然后是日志,而 DSM 上它们大多是红鲱鱼: -whisper 需要 CUDA 和 CMake 工具链。在 Windows 上就是装三样东西然后编译: +- 回收任务本身什么都不记; +- `/var/log/space_operation.log` 是 LUKS 和卷列表的噪音; +- `/var/log/synorecycle.log` 是 `synounlinkd` 的路径噪音; +- 当天的 Log Center 里只有我自己那条清回收站的记录,外加几条 UPS 断电/来电的提示。 -```bash -git clone https://github.com/ggerganov/whisper.cpp -cd whisper.cpp -cmake -B build -DGGML_CUDA=ON -DCMAKE_CUDA_ARCHITECTURES=86 -cmake --build build --config Release -j -``` +一个永远为真的 UI 状态字段,加上三个永远不会给出答案的日志文件:唯一剩下的仪器,就是**随时间变化的可用空间**。 -然后取模型并启动: +## 没人告诉你的那个机制 -```bash -# large-v3, ~2.9 GB -cd models && sh ./download-ggml-model.sh large-v3 && cd .. -./build/bin/Release/whisper-server.exe \ - -m models/ggml-large-v3.bin \ - --host 0.0.0.0 --port 20129 \ - --convert -``` +空间回收释放的是**已删除的 btrfs 子卷**。它释放不了仍然被快照钉住的数据。那两个共享文件夹的保留策略是 **retention 1**(各留一代),所以**我删掉的任何东西,都要等到第二天的轮转、大约 09:29 / 09:30 才会变成可用空间**,一次跳几十 GB,然后安静 24 小时。 -`--convert` 比看上去重要:有了它,服务可以接受 MP3 等压缩格式(内部调用 -ffmpeg 转码),而不是逼每个客户端都发原始 WAV。多数手机 App 发的都是压缩音频。 - -到这里服务已经是一个可以用的转写 API 了。后面所有的工作,都是让它能够安全地 -从手机访问。 - -## 坑一:CUDA Toolkit 装了一个不完整的编译器 - -CUDA Toolkit 安装程序的默认组件里包含 `nvcc`——但**不包含 `nvcc` 真正编译时 -需要的那些部件**。我前两次 CMake 都因为缺头文件失败,而错误信息指向的是我的 -编译配置,不是一个残缺的工具链。 - -解决办法是把三个组件显式勾上: - -```text -crt_13.x → C 运行时头文件(缺的就是 ) -nvvm_13.x → 里面有 cicc,才是真正的 CUDA 编译器后端 -cublas_13.x → cuBLAS,运行时链接需要 -``` - -要留意的症状:`nvcc --version` 能正常输出,但编译立刻因为缺头文件挂掉。 -**能跑的 nvcc 不等于装好的工具链。** - -## 坑二:它只监听 localhost,防火墙是无辜的 - -whisper 默认绑定 `127.0.0.1`——只有本机回环。不管防火墙怎么设,网络上的其他 -设备都到不了。 - -我在这里浪费了不少时间,因为我认定是防火墙问题,反复测防火墙(甚至整个关掉), -而真正的原因在绑定地址上。loopback-only **在定义上**就拒绝所有其他网卡。 - -```bash -# 端口活着但没对外暴露时,长这样 -netstat -an | grep 20129 -# TCP 127.0.0.1:20129 0.0.0.0:0 LISTENING ← 只有你能连 -``` - -改掉绑定,情况就不一样了: - -```bash ---host 0.0.0.0 -``` - -```text - TCP 0.0.0.0:20129 0.0.0.0:0 LISTENING ← 网络能连了 -``` - -**先看绑定,再去碰防火墙。**这两种故障的表现完全一样——连接超时——而只有其中 -一种真的是防火墙问题。 - -还有一个相关的小坑:Windows 防火墙的配置文件状态会自动恢复。一条限定 -`Private,Domain` 的规则,在 Windows 把这个网络重新归类成 *Public* 之后就会 -静默失效;某次更新把配置文件重新打开也有同样效果。规则要按网段限定,而不是按 -配置文件名称: - -```powershell -New-NetFirewallRule -DisplayName 'Whisper STT' -Direction Inbound -Action Allow ` - -Protocol TCP -LocalPort 20129 -Profile Any -RemoteAddress LocalSubnet -``` - -`-RemoteAddress LocalSubnet` 让它在内网可用、在公网不可达——即使前面已经有 -认证,这也才是正确的姿势。 - -## 坑三:n8n 会把你的音频丢掉(两次) - -把 n8n 放在链路里是刻意的——API key 校验就住在那里——但它有两个行为会静默地 -把代理弄坏。 - -**第一:Code 节点会丢弃二进制数据。**我的流程是 Webhook → Code(校验 key)→ -HTTP Request(转发音频)。Code 节点返回的是 JSON,而 n8n 的二进制负载——也就 -是音频本身——根本没穿过它。随后报错:*"Make sure that the previous node -outputs a binary file."* - -n8n 的 Webhook 节点会接收 multipart 上传并存为二进制。要在校验 key 的同时把 -它保住,Code 节点必须显式把二进制引用传下去,而不只是返回 JSON。而那个 key 的 -名字,你绝对猜不到: - -```text -┌──────────────┬────────────────────────────┐ -│ 上传的字段名 │ n8n 里的 binary key │ -├──────────────┼────────────────────────────┤ -│ file │ data0 │ -│ (第二个) │ data1 │ -└──────────────┴────────────────────────────┘ -``` - -multipart 字段叫 `file`,但 n8n 把它索引成 `data0`。转发 `$binary.data` 会失败, -`$binary.data0` 才行。 - -**第二:执行记录会把音频存下来。**n8n 默认保留执行数据——包括二进制负载——也 -就是说每一次口述都会被写进工作流数据库。对音频来说这是不可接受的。关掉它: - -```json -"settings": { "saveDataSuccessExecution": "none" } -``` - -⚠ **这是最有杀伤力的一个坑。**如果你通过 n8n API 改工作流而漏掉了 `settings` -对象,这次更新会**静默重置它**,于是你又开始记录音频了。系统不会有任何提示。 -每次改完工作流都要验证: - -```bash -curl -s -H "X-N8N-API-KEY: $KEY" \ - http://localhost:5678/api/v1/workflows/ \ - | jq '.settings' -``` - -## 坑四:nginx 自带的默认配置劫持了 80 端口 - -我的网关是一个 nginx 容器。它对那些明明配置好的路径一直返回 404——因为自带的 -`default.conf` 同样在 80 端口声明了一个 server 块,而它作为默认 server 抢走了 -流量。我的配置加载正常、内容正确,只是根本收不到请求。 - -```dockerfile -# 启动前删掉自带配置 -command: > - sh -c "rm -f /etc/nginx/conf.d/default.conf && nginx -g 'daemon off;'" -``` - -同一个构建里还有两个小经验,部署到 NAS 之前值得先知道: - -- **不能挂载一个还不存在的配置文件**——部署会失败,报 *"Bind mount failed: - ... does not exist."* 在 DSM 上,从另一个容器里把文件写出来这个常见绕法也不行, - 因为容器只看得见自己的挂载,看不见真正的主机文件系统。我最后把配置 base64 - 内嵌进 compose 的 `command`,启动时再写出来——完全不需要碰主机文件系统。 -- **容器能看到的 `/volume1` 挂载是只读的**,所以那些看上去能写的路径都是封的。 - -## 授权模型,说实话 - -两层,值得讲清楚每一层到底买到了什么。 - -**每台设备独立的 API key。**每台设备有自己的 key,所以挂失一台手机不影响其他 -设备: - -```json -{ - "iphone": "stt_", - "ipad": "stt_", - "laptop": "stt_" -} -``` - -n8n 工作流拿 `Authorization` 头去比对这份名单,不匹配就返回真正的 403。有个 -细节:API key 放在 URL 查询串里会落进代理日志和浏览器历史——始终放在请求头。 - -**这层保护了什么。**它阻止别人白用你的 GPU,也让这个端点不至于变成互联网上一个 -人人可用的转写服务。它**不**负责加密音频——那是代理层的 TLS,这也是公网入口 -只走 HTTPS 的原因。 - -这是**一个私有服务的访问控制**,不是一个加固过的公开 API。目前没有限流,也没有 -按 key 的配额。对于几台已知设备的内网办公部署,这个比例是合适的;如果要开放给 -第三方,那就得再加上限流、日志和轮换。 +那两次跳变正是这个。它也就意味着,对于「我删了 50 GB 却什么都没发生」这个问题,在这台机器上的诚实答案是:「等明天早上再看」——而如果删掉的数据本来就在某个快照里面,答案是「等那个快照过期,之前不会释放」。 ## 如果重来一次 -1. **先验证绑定地址,而不是防火墙。**两个小时花在测错误的层上,而这件事 - `netstat` 一行就能回答。两种故障都表现为"连接超时",而我本该知道 - loopback-only 不管防火墙什么状态都会拒绝一切。 -2. **确认安装程序到底装了什么。**我把 `nvcc --version` 当成了工具链可用的证据。 - 一个能跑、但找不到自己头文件的编译器,并不算装好了——而它的报错不会告诉你 - 这一点。 -3. **在搭管线之前就定好日志策略,而不是搭完之后。**我是在构建过程中设上 - `saveDataSuccessExecution: none` 的,但同一次修改如果走 API 就会静默地把 - 音频留存重新打开,毫无提示。能被无关操作重置的隐私设置,需要一个验证步骤。 +1. **采样那个数字,不要采样状态。** 每五分钟量一次可用空间,比任何任务卡都更能回答「现在有没有事情在发生」,而且它同时让「回长」变得可见。 +2. **读调度字段,不读状态字段。** `run_all_time` 解释了那个永久 running,而且不需要任何 bug 存在。 +3. **搞清楚每个共享文件夹的保留策略。** 它是决定「删除何时变成可用空间」的那口钟;不知道它,每一次删除都会看起来坏掉一整天。 +4. **把两本账分开。** 回收站(5 GiB)和快照(115.8 GiB)行为完全不同,也是两套心理模型。 +5. **重新检查分母。** 这个卷平时就在以约 1.5 GiB/时 的速度被正常写入吃掉;回收回来 121 GiB、当天又花掉 47 GiB,只要你只比同一个数字的两个快照,这两件事看起来完全一样。 -## 结果 +## 测量真正告诉我的,是这台机器的趋势 -四类设备——一台 Windows 开发电脑、iPhone、iPad、Android——都在通过我自己网络上 -的一张 GPU 做语音输入。短句转写通常远低于一秒,穿过四层之后的完整请求大约 -2 秒返回真实文本。 +我本来是去修一个卡住的任务,结果带回来的是一条存储趋势: -最值得说的量化收益是显存。因为模型空闲时会卸载,一个开关就能把 GPU 占用从 -**4,906 MiB 降到 1,321 MiB**——回收约 3.6 GB——机器可以回去做开发、本地大模型 -推理或图像生成,下一次口述时再把模型加载回来。 +```text +volume1 42 TB 已用 98% 剩 1.2 TB 近来约 -1.5 GiB/时(8 天 -344 GiB) +volume2 16 TB 已用 100% 剩 70 GB 约 -19 GiB / 2 天 +健康 两个卷 btrfs corruption_errs 均为 0 + 所有 md 阵列 [UUUU] / [UU],没有在跑 balance + read/write_io_errs 与九月基线一致 +``` -关于速度,说句公道话:**大约比打字快 5 倍**这个数字对散文体(说话 130 wpm -对比打字约 40 wpm)是成立的。写代码就没这么夸张,因为那更多是在思考而不是在 -打字。收益最大的是办公室真正被淹没的那部分工作——邮件、文档、笔记、合约、 -客服回复。 - -## 这套东西能用在你的公司吗? - -部件都不花哨,回报却很直接:一台带 GPU 的机器、开源软件,再加一层负责认证的 -分发层。没有按人头的月费,没有分钟数配额,没有音频离开你的场地——全公司从打字 -切换到语音输入。 - -我做的就是这类内部基础设施:带正规认证的自建服务、能合理共享硬件的 GPU 负载, -以及让它们在员工手上已有的设备里真正可用的集成层。如果你想让语音转文字(或者 -其他内部 API)跑在你自己的硬件上——哪怕是公司现成的一台工作站——这正是我在做 -的事。 - -联系我:[me@hoelee.com](mailto:me@hoelee.com?subject=自建语音转文字服务) -或 WhatsApp [+60 12-797 2969](https://wa.me/60127972969),也可以看看我在做什么: -[hoelee.com](https://hoelee.com)。 +所以有用的结论不是「回收是好的」。而是:**相对于写入速率,回收只是一个舍入误差**;在保留策略为 1 的前提下,删除并不是我以为的那根杠杆;而该拿来做告警的是趋势,不是那张任务卡。这跟[《你的磁盘快满告警在撒谎》](/posts/your-disk-full-alert-is-lying/)是同一课,只是从另一个方向来的:对**后果**告警(随时间变化的可用字节),因为机制自己的状态不是证据。 ```` ### 🇬🇧 英文版原文 (English Markdown Primary) ````markdown --- -title: "Your Own Speech-to-Text Server: Faster Than Typing, Private by Default" -description: "I run a self-hosted speech-to-text API on a single GPU PC. Dictation works from Windows, iPhone, iPad and Android — private, unlimited, and about 5x faster than typing." -pubDate: 2026-09-19 -category: case-studies -tags: [whisper, cuda, stt, n8n, nginx, self-hosting, ai] -ogImage: /og/self-hosted-speech-to-text-api.jpg -banner: /banners/self-hosted-speech-to-text-api.jpg +title: "Space Reclamation Wasn't Stuck. It Was Waiting for Tomorrow at 09:29." +description: "The Storage Manager card said 'running' all day and free space hadn't moved. 121 GiB had come back in two steps — and the afternoon ate 47 GiB of it." +pubDate: 2026-10-14 +updatedDate: 2026-10-16 +category: devops +tags: ["synology", "btrfs", "snapshots", "storage", "nas"] +ogImage: /og/space-reclamation-wasnt-stuck-it-was-waiting.jpg +banner: /banners/space-reclamation-wasnt-stuck-it-was-waiting.jpg +draft: false --- -Typing is the slowest thing most offices do all day. An average person types -40 words per minute; they *speak* 130. Every email, quotation, report, support -reply and chat message in your business pays that tax — and the tax is usually -paid by whoever is fastest at the keyboard. +## The question I asked was the wrong question -Speech-to-text removes it. But the version most people adopt has two problems: -it costs a monthly subscription per seat, and it ships your voice — your -internal discussions, customer names, pricing, contracts — to someone else's -cloud. +I emptied a few folders, kicked off Space Reclamation on the NAS, and +waited. Hours later the Storage Manager card still read **running**, and +free space looked the way it had looked in the morning. My question was "why +didn't it reclaim anything". -So I built the other version: **one speech-to-text API running on a single -desktop PC in my office, with my own GPU doing the work.** My development PC, -my iPhone, an iPad and Android phones all dictate through it. It's faster than -typing, it's unlimited, and nothing leaves my network. +It had reclaimed — twice — and one of those reclaims was larger than +anything I had deleted. The measurement answered a different question than +the one I asked, which is the interesting part. -This is how it works — including the four traps that cost me most of a day. +## Sample free space on a timer before believing anything -## Why this matters +I sampled `volume1` free space every five minutes for the day instead of +looking at a progress card: -Speech-to-text is the highest-leverage office automation that isn't an AI -chatbot. Concretely, what a self-hosted setup buys you: - -- **Roughly 5x the throughput of typing.** At 130 wpm spoken versus ~40 wpm - typed, dictating a 500-word email is about 4 minutes of talking instead of - 12 minutes of typing. Someone who writes 10 emails a day gets an hour back — - every day. -- **Cost scales with hardware, not headcount.** Cloud dictation is priced per - user per month, forever. This one runs on hardware you own. Add the tenth - employee and the marginal cost is zero. -- **Unlimited length, no quota anxiety.** No minute caps, no "you've reached - your monthly limit" at 4pm on a Friday. -- **Your audio stays yours.** Medical notes, legal drafts, HR conversations, - customer pricing — voice is sensitive by default. Self-hosted means the - transcription never leaves the building. -- **It works in whatever app already has focus.** Not a separate transcribe-then- - paste website — a keyboard you use inside Outlook, WhatsApp Web, your CRM, - or your own internal tools. - -If you run an office where people write all day, this is the same class of win -as moving from dial-up to broadband, and it costs a GPU you may already own. - -## What you need - -| Piece | What I used | Notes | +| time | free | event | |---|---|---| -| GPU machine | Desktop PC with an RTX 3060 (12 GB) | Any NVIDIA card with ≥6 GB VRAM works; it can be a normal work PC | -| Whisper build | `whisper.cpp` with CUDA | Free, open source | -| Model | `large-v3` (~2.9 GB) | Best accuracy; smaller models use less VRAM | -| Delivery layer | n8n + nginx gateway | Adds auth, so the endpoint can be shared safely | -| Clients | Desktop app, iPhone, iPad, Android | Any client that speaks OpenAI's transcription API | +| 08:59 → 09:24 | 1134.1 GiB | flat — nothing reclaiming | +| **09:29** | **+69.0 GiB** | Class snapshot `…10.14-09.29.02` rotated | +| **09:34** | **+46.8 GiB** | Video snapshot `…10.14-09.30.35` rotated | +| **15:28:45** | — | DSM log: `Start to empty all recycle bins.` | +| **15:34** | **+5.0 GiB** | recycle-bin empty finished — only 5 GiB was in there | +| 16:35 → 17:39 | **−39 GiB** | new data written (a burst) | +| 15:00 → 20:44 | **−47.2 GiB** | net: the volume *lost* space that afternoon | -The PC doesn't have to be dedicated. Mine also runs development work, -local LLM inference and image generation — the model loads when a request -arrives and unloads when idle, so it isn't permanently holding VRAM. +Two reclaims, ~121 GiB in total, and then 47 GiB of new writes swallowed the +afternoon. "Nothing came back" was a reading error on my side: I compared +the morning to the evening, and the evening had a day of writing in it. -## The architecture +The recycle bin — the thing I had bothered to empty by hand — was **5 GiB**. +The snapshots, which I had not thought about at all, were **115.8 GiB**. +That ratio is the whole story. -The important design decision is that **the phones never talk to the GPU -directly.** There's a gatekeeper in between that handles authentication, -so the GPU itself stays on a private network. +## Why the card said "running" and meant nothing ```text - iPhone / iPad / Android / Work PCs - │ - │ HTTPS + per-device API key - ▼ - ┌───────────────────────────┐ - │ https://stt.example.com │ public HTTPS entry - │ reverse proxy │ - └─────────────┬─────────────┘ - ▼ - ┌───────────────────────────┐ - │ nginx gateway container │ strips/forwards auth, fixed routes - └─────────────┬─────────────┘ - ▼ - ┌───────────────────────────┐ - │ n8n workflow │ validates the key → 401/403 if wrong - │ (no audio ever logged) │ - └─────────────┬─────────────┘ - ▼ - ┌───────────────────────────┐ - │ whisper.cpp on the PC │ GPU transcription - │ :20129 → {"text": …} │ - └───────────────────────────┘ +$ synostgreclaim --get-all-status --verbose +{"state":"running","num_subvolume_remain":1,"now_runnable":true} + schedule_table: 168 × 1 + run_time_option: run_all_time ``` -Four layers, each doing one job: the proxy terminates TLS, the gateway fixes -routing, n8n authorises, whisper transcribes. The result is -`POST /v1/audio/transcriptions` — the same shape OpenAI uses, which means any -OpenAI-compatible client works with zero custom code. +`state: running` with a schedule table of 168 ones and `run_all_time` means +the task is configured to be "running" **24×7, by design**. It is a +schedule, not a progress indicator — so the card will read the same thing on +a day when nothing is scheduled to happen at all. Meanwhile the machine had +no `synostgreclaim` process, no btrfs balance, and md2/dm-3 I/O of roughly +zero. Nothing was being reclaimed at that moment, and nothing was stuck +either. -## The build +Then the logs, which are mostly red herrings on DSM: -Whisper needs CUDA and a CMake toolchain. On Windows that's three installs and -a build: +- the reclaim task itself logs nothing; +- `/var/log/space_operation.log` is LUKS and volume-list spam; +- `/var/log/synorecycle.log` is `synounlinkd` path noise; +- Log Center for the day contained only my own recycle-bin line and a few + UPS on-battery/back-online blips. -```bash -git clone https://github.com/ggerganov/whisper.cpp -cd whisper.cpp -cmake -B build -DGGML_CUDA=ON -DCMAKE_CUDA_ARCHITECTURES=86 -cmake --build build --config Release -j -``` +A UI state field that is always true and three log files that never contain +the answer: the only instrument left is free space over time. -Then fetch the model and run it: +## The mechanism nobody tells you about -```bash -# large-v3, ~2.9 GB -cd models && sh ./download-ggml-model.sh large-v3 && cd .. -./build/bin/Release/whisper-server.exe \ - -m models/ggml-large-v3.bin \ - --host 0.0.0.0 --port 20129 \ - --convert -``` +Space Reclamation frees **deleted btrfs subvolumes**. It cannot free data +that a snapshot is still pinning. Those two shares keep **retention 1** — +one generation each — so anything I delete becomes free space only at the +**next day's rotation, around 09:29 / 09:30**, in a step of tens of +gigabytes, and then it is silent for 24 hours. -`--convert` matters more than it looks: it lets the server accept MP3 and -other compressed formats by shelling out to ffmpeg, instead of forcing every -client to send raw WAV. Most mobile apps send compressed audio. +That is exactly what the two jumps were. It also means the honest answer to +"I deleted 50 GB and nothing happened" on this box is: "wait for tomorrow +morning, then check again" — and if the deleted data lived inside a +snapshot, the answer is "it frees when that snapshot expires, and not +before". -The server is now a working transcription API. Everything after this point -is about making it safe to reach from a phone. +## What I would do differently -## Trap 1: CUDA Toolkit installs an incomplete compiler +1. **Sample the number, not the status.** A five-minute timer on free space + answers "is anything happening" in a way no task card can, and it made + the regrowth visible at the same time. +2. **Read the schedule field, not the state field.** `run_all_time` explains + a permanent "running" without any bug existing. +3. **Know each share's retention.** It is the clock that decides when a + delete becomes free space; without it, every deletion looks broken for a + day. +4. **Separate the two ledgers.** Recycle bin (5 GiB) and snapshots (115.8 + GiB) behave nothing alike and are two different mental models. +5. **Re-check the denominator.** The volume was losing ~1.5 GiB/h to normal + writes; a reclaim that returns 121 GiB and a day that consumes 47 GiB + look identical if you only compare two snapshots of the same number. -The CUDA Toolkit installer's default component selection includes `nvcc` — but -*not* the pieces `nvcc` needs to actually compile. My first two CMake runs both -failed on missing headers, and the errors pointed at my build config rather -than at a partial toolchain. +## What the measurement actually says about the machine -The fix is to add three components explicitly: +I went in expecting to fix a stuck job and came out with a storage trend +instead: ```text -crt_13.x → C runtime headers (the missing ) -nvvm_13.x → contains cicc, the actual CUDA compiler backend -cublas_13.x → cuBLAS, required to link at runtime +volume1 42 TB 98% used 1.2 TB free ~-1.5 GiB/h lately (-344 GiB over 8 days) +volume2 16 TB 100% used 70 GB free ~-19 GiB / 2 days +health btrfs corruption_errs 0 on both volumes + all md arrays [UUUU] / [UU], no balance running + read/write_io_errs identical to the September baseline ``` -Symptom to watch for: `nvcc --version` succeeds, but the build fails immediately -with a missing-header error. A working `nvcc` is not a working toolkit. - -## Trap 2: it listens on localhost, so your firewall is innocent - -Whisper's default bind is `127.0.0.1` — loopback only. Nothing else on the -network can reach it, no matter what your firewall says. - -I lost real time here, because I assumed a firewall problem and tested the -firewall repeatedly (including turning it off entirely) while the actual cause -was the bind address. Loopback-only is *defined* to refuse every other -interface. - -```bash -# what it looks like when the port is live but not exposed -netstat -an | grep 20129 -# TCP 127.0.0.1:20129 0.0.0.0:0 LISTENING ← only you can reach it -``` - -Change the bind, and the picture changes: - -```bash ---host 0.0.0.0 -``` - -```text - TCP 0.0.0.0:20129 0.0.0.0:0 LISTENING ← the network can reach it -``` - -**Check the bind before you touch the firewall.** The two failures present -identically — a connection that times out — and only one of them is a firewall -problem. - -One related gotcha: Windows Firewall profiles can re-enable themselves. A rule -scoped to `Private,Domain` will silently stop working on a network Windows has -since reclassified as *Public*, and an update that re-enables a profile has the -same effect. Scope the rule to the LAN subnet rather than to a profile name: - -```powershell -New-NetFirewallRule -DisplayName 'Whisper STT' -Direction Inbound -Action Allow ` - -Protocol TCP -LocalPort 20129 -Profile Any -RemoteAddress LocalSubnet -``` - -`-RemoteAddress LocalSubnet` keeps it reachable from your office while staying -unreachable from the internet — which is the correct posture even with auth in -front. - -## Trap 3: n8n throws away your audio (twice) - -Putting n8n in the path is deliberate — it's where the API key check lives — but -it has two behaviours that silently break a proxy. - -**First: Code nodes discard binary data.** My workflow was Webhook → Code -(validate key) → HTTP Request (forward audio). The Code node returned JSON, and -n8n's binary payload — the audio itself — never made it past it. Subsequent -error: *"Make sure that the previous node outputs a binary file."* - -n8n's Webhook node accepts multipart uploads and stores them as binary. To -preserve that through an auth check, the Code node must pass the binary -reference through explicitly, not just return JSON. And the key name is not -what you'd guess: - -```text -┌──────────────┬────────────────────────────┐ -│ input field │ binary key in n8n │ -├──────────────┼────────────────────────────┤ -│ file │ data0 │ -│ (second) │ data1 │ -└──────────────┴────────────────────────────┘ -``` - -The multipart field is named `file`, but n8n indexes it as `data0`. Forwarding -`$binary.data` fails; `$binary.data0` works. - -**Second: execution logging stores the audio.** By default n8n persists -execution data — including binary payloads — which means every dictation is -written to the workflow database. For audio that's unacceptable. Disabling it: - -```json -"settings": { "saveDataSuccessExecution": "none" } -``` - -⚠ **This is the trap with teeth.** If you edit a workflow via the n8n API and -omit the `settings` object, the update **silently resets it** and you go back to -logging audio. Nothing warns you. Verify after every workflow change: - -```bash -curl -s -H "X-N8N-API-KEY: $KEY" \ - http://localhost:5678/api/v1/workflows/ \ - | jq '.settings' -``` - -## Trap 4: the stock nginx config hijacks port 80 - -I run the gateway as an nginx container. It kept returning 404s for paths that -were definitely configured — because the stock `default.conf` also declares a -server block on port 80, and it wins as the default server. My config was -loaded and correct, and simply never saw the traffic. - -```dockerfile -# remove the stock config before starting -command: > - sh -c "rm -f /etc/nginx/conf.d/default.conf && nginx -g 'daemon off;'" -``` - -Two smaller notes from the same build, both worth knowing before you deploy to -a NAS: - -- **You can't bind-mount a config file you haven't created yet** — the deploy - fails with *"Bind mount failed: ... does not exist."* On DSM the obvious - workaround of writing the file from inside another container doesn't work - either, because containers see only their own mounts, never the real host - filesystem. I ended up base64-embedding the config in the compose `command` - and writing it at startup — no host filesystem access needed at all. -- **The `/volume1` mounts available to containers are read-only**, so the - obvious write paths are closed. - -## The authorisation model, honestly - -Two layers, and it's worth being precise about what each one buys you. - -**Per-device API keys.** Each device gets its own key, so revoking a lost phone -doesn't affect anyone else: - -```json -{ - "iphone": "stt_", - "ipad": "stt_", - "laptop": "stt_" -} -``` - -The n8n workflow checks the `Authorization` header against this list and -returns a real 403 when it doesn't match. One subtlety: an API key in a URL -query string lands in proxy logs and browser history — keep it in the header. - -**What this protects.** It stops unauthorised use of your GPU and keeps the -endpoint from being an open transcription service on the internet. What it does -not do is encrypt the audio — that's TLS at the proxy layer, which is why the -public entry point is HTTPS-only. - -This is **access control for a private service**, not a hardened public API. -There's no rate limiting and no per-key quota yet. For an internal office -deployment across a handful of known devices that's proportionate; if you were -opening it to third parties you'd want limits, logging and rotation on top. - -## What I'd do differently - -1. **Verify the bind address first, not the firewall.** Two hours went into - testing the wrong layer for a problem that `netstat` answers in one line. - Both failures are "connection timed out", and I should have known that - loopback-only refuses everything regardless of firewall state. -2. **Check what the toolkit installer actually installed.** I trusted - `nvcc --version` as proof of a working toolchain. A compiler that runs but - can't find its own headers is not installed, and the error message will not - tell you that. -3. **Set logging policy before wiring the pipeline, not after.** I configured - `saveDataSuccessExecution: none` during the build, but the same edit through - the API would have silently re-enabled audio retention with no warning. - Privacy settings that can be reset by an unrelated update need a verification - step. - -## The result - -Four devices — a Windows development PC, an iPhone, an iPad and Android — all -dictating through one GPU on my own network. Typical transcription of a short -sentence is well under a second, and the end-to-end request through all four -layers returns a real transcript in about 2 seconds. - -The measured win that matters most is memory. Because the model unloads when -idle, a toggle drops GPU usage from **4,906 MiB to 1,321 MiB** — about 3.6 GB -returned — so the machine can go back to development work, local LLM inference -or image generation, then load the model again on the next dictation. - -And the honest framing on speed: **roughly 5x faster than typing** is the -correct figure for prose (130 wpm spoken vs ~40 typed). It's less dramatic for -code, where you're thinking more than typing. The gain is largest for exactly -the work offices drown in — email, documentation, notes, contracts, support -replies. - -## Could this work for your office? - -The pieces are unglamorous and the payoff is immediate: one machine with a GPU, -open-source software, and a delivery layer for authentication. No per-seat -subscription, no minute quotas, no audio leaving your premises — and the whole -office dictating instead of typing. - -I build exactly this kind of internal infrastructure: self-hosted services with -proper auth, GPU workloads that share hardware sensibly, and the integration -layer that makes them usable from the devices your staff already carry. If you -want speech-to-text (or another internal API) running on your own hardware — -or on a workstation you already own — that's the work I do. - -Reach me at [me@hoelee.com](mailto:me@hoelee.com?subject=Self-hosted%20speech-to-text) -or WhatsApp [+60 12-797 2969](https://wa.me/60127972969), or see what I do at -[hoelee.com](https://hoelee.com). +So the useful conclusion is not "the reclaim works". It is that reclaim is a +rounding error next to the write rate, deletion is not the lever I thought +it was while retention is 1, and the trend — not the task card — is what I +should be alerting on. That is the same lesson as +[Your Disk-Full Alert Is Lying](/posts/your-disk-full-alert-is-lying/), +arriving from the other direction: alert on the consequence (bytes free over +time), because the mechanism's own status is not evidence. ```` --- -## 文章 07 / 10:从云端转本地:在 12GB 显卡与群晖 N8N 上搭建中英混读高保真 TTS 语音栈 -- **Slug**: `self-hosted-tts-cosyvoice2-n8n-gpu` -- **英文标题**: How I Replaced Cloud TTS with a Self-Hosted Neural Voice Stack on an RTX 3060 -- **分类**: `case-studies` | **发布日期**: 2026-10-22 -- **线上地址**: https://blog.hoelee.com/posts/self-hosted-tts-cosyvoice2-n8n-gpu/ (EN) | https://blog.hoelee.com/posts/zh/self-hosted-tts-cosyvoice2-n8n-gpu/ (ZH) +## 文章 02 / 11:Synology 电子表格 API 是一个容器,不是一个 API 端点 +- **Slug**: `synology-spreadsheet-api-is-a-container` +- **英文标题**: The Synology Spreadsheet API Is a Container, Not an API Endpoint +- **分类**: `devops` | **发布日期**: 2025-08-20 +- **线上地址**: https://blog.hoelee.com/posts/synology-spreadsheet-api-is-a-container/ (EN) | https://blog.hoelee.com/posts/zh/synology-spreadsheet-api-is-a-container/ (ZH) - **本篇审核状态**: ⏳ 待审核 (Pending) ### ✍️ 顾问审阅意见区 (Review Feedback) @@ -2567,647 +303,576 @@ or WhatsApp [+60 12-797 2969](https://wa.me/60127972969), or see what I do at ### 🇨🇳 中文版原文 (Chinese Markdown Twin) ````markdown --- -title: "从云端转本地:在 12GB 显卡与群晖 N8N 上搭建中英混读高保真 TTS 语音栈" -description: "记录如何将内部自动化工作流从依赖公网 TTS API 迁移至本地 RTX 3060 12GB 显卡,基于 CosyVoice 2 与群晖 N8N 实现中英混读与多音色零样本克隆。" -pubDate: 2026-10-22 -category: case-studies -blueprint: ai-agent-automation -blueprintLayer: L3-local-gpu-inference -tags: ["tts", "ai", "n8n", "gpu", "cosyvoice", "self-hosting"] -ogImage: "/og/zh-self-hosted-tts-cosyvoice2-n8n-gpu.jpg" -banner: "/banners/self-hosted-tts-cosyvoice2-n8n-gpu.jpg" +title: "Synology 电子表格 API 是一个容器,不是一个 API 端点" +description: "如何在 Synology Office 电子表格上做自动化:官方的 spreadsheet-api 容器,以及四个陷阱——一个假的\"未安装\"、凭据正确却报 401、永远无法通过认证的 2FA,还有一堵权限墙。" +pubDate: 2025-08-20 +updatedDate: 2026-09-26 +category: devops +blueprint: sme-digital-suite +blueprintLayer: L3-entitlement-backoffice +tags: [synology, dsm, docker, portainer, rest-api, spreadsheet, debugging, self-hosting] +ogImage: /og/zh-synology-spreadsheet-api-is-a-container.jpg +banner: /banners/synology-spreadsheet-api-is-a-container.jpg draft: false --- -在过去两年中,我们的内部业务自动化管线、Telegram 智能机器人以及视频知识库转写系统,一直依赖云端 Text-to-Speech(文本转语音)服务。起初,社区封装的 Microsoft Edge-TTS 提供了一个零成本的过渡方案;但依赖公网未公开接口的爬虫调用本质上极其脆弱——微软端点频繁变更签名、国内与海外网络抖动、以及跨国链路的偶发限流,经常导致自动化链路在半夜静默失败。而转用商业级 Azure Speech 或 Google Cloud TTS,在面对大批量长文本合成时,按字符计费的月度账单又显得不合算。 +我想要的东西很普通:从我 NAS 上的电子表格读一个单元格,把一个单元格写回去,然后从另一端得到一张图表——不用打开 Excel,也不用把公司的数据送到某个云 API。 -随着我们在 Unraid 服务器上为 Windows 11 虚拟机配置了直通的 **NVIDIA RTX 3060 12GB** 独立显卡,我们决定将整套语音合成系统完全收敛到本地局域网。 +我跑着一台 Synology DS1821+,装好了 Synology Office(`Spreadsheet` 套件),所以这看起来是个已解决的问题。它确实是个已解决的问题。只是要穿过四个相互矛盾的假信号才能找到真正的答案,而且其中有一个我中途得出的结论错得相当彻底,值得写下来。 -本文记录我们如何选型阿里巴巴开源的 **CosyVoice 2**,将其接入群晖 NAS 的 **n8n** 自动化集群,实现显存按需管理与开机常驻,并构建覆盖女童、正太、青年解说与纯正中英双语的零样本语音栈。 +## 为什么这件事值得写 ---- +如果你自托管,总有一天你需要一个服务去和同一台机器上的另一个服务对话。这篇帖子里的故障模式并不只属于 Synology——它们就是"厂商把东西寄来了,但不在你会去找的地方"这个问题的通用形态: -## 1. 核心需求与设计指标 +1. **API 清单里缺一条,不等于这个 API 不存在。** 我枚举了 1,515 个 API,得出结论说这个功能不存在。其实它是一个容器。 +2. **我信任的两个诊断工具在撒谎。** `synopkg` 把一个正在运行的套件报成"未开启",`ps` 给我看了一台空荡荡、却正在服务生产流量的机器。 +3. **范围最精准的凭据失败,看起来却像是你的错。** 密码验证过正确还返回 `401`,几乎总是关于你把请求发到了*哪里*,而不是你发了*什么*。 +4. **权限模型在认证之后才咬人。** 你可以完美登录,却仍然对每个文件都收到 `403`,原因在于文件所在的位置。 -在开工搭建之前,我们确立了四个关键要求: +如果以上任何一条听起来耳熟,这篇帖子的后半部分就是能跑通的完整配置。 -1. **丝滑的中英混读(Code-switching)能力**:在马来西亚与东南亚的业务沟通场景中,日常对话几乎都是中英双语交织(例如:“*请确认这个 webhook 已经 trigger,并检查 logs*”)。传统的 TTS 模型在遇到英文字词时往往会生硬卡顿、甚至读错音素,引擎必须能够自然过渡。 -2. **零样本(Zero-shot)多音色快速切换**:需要支持多种人设音色——讲故事需要的活泼童声、科技资讯需要的沉稳播音男声、以及客服交互需要的自然女声,且无需耗时数小时重新微调。 -3. **显存共存与无痛调度**:12GB 显存是宝贵资产,这台工作机平时还要承载 LM Studio 的 Qwen 大模型推理以及 ComfyUI 生图生视频任务。TTS 引擎要么显存占用极小,要么能够随时一键启停释放显存。 -4. **无缝替换群晖 n8n 旧节点**:自动化调度中心跑在群晖 DSM 的 n8n (`192.168.1.1:5678`) 上,本地新接口必须兼容通用 HTTP Webhook,无需重构现有工作流业务逻辑。 +## 文档说了什么,以及它为什么把我带偏 ---- +Synology 宣传"Office Suite APIs"——面向 Drive、Spreadsheet、MailPlus 和 Calendar 的 REST API。营销页面上逐字列出了我想要的正是这些: -## 2. 模型选型:为什么是 CosyVoice 2? +- "读取并写入某个范围内的单元格样式。" +- "新增、重命名、删除表格,并把工作表导出为 CSV 文件。" +- "创建、读取、导出和删除电子表格。执行批量更新……" -针对中文、英文以及核心的**中英混读**场景,我们横向对比了目前主流的本地开源方案: +文档本身藏在 Synology 账户登录后面——这是很常见的事,不是什么丑闻——但它意味着搜索引擎先找到的是承诺,而不是契约。 -| 模型方案 | 优势 | 不足 | 选型结论 | -| :--- | :--- | :--- | :--- | -| **Edge-TTS / Piper** | 超轻量、纯 CPU 即可跑 | 音质机械感明显、无法自主克隆 | 彻底淘汰 | -| **ChatTTS** | 拟人化笑声与叹气细节好 | 经常胡言乱语、英文发音偏弱、长句难控 | 仅供玩票 | -| **GPT-SoVITS (v2)** | 特定人物音色克隆还原度极高 | 语种切换边界容易卡顿顿挫、中英混读较硬 | 备选 / 按需冷启 | -| **CosyVoice 2 (0.5B)** | **中英混读极度自然、首包延迟仅 300ms** | 常驻需要约 3.2GB 显存 | **生产主力首选** | +于是我自己在 NAS 上找。DSM 暴露了一个网关 API 目录,你可以直接问它存在什么: -阿里开源的 **CosyVoice 2**(0.5B 自回归语言模型 + 流匹配 Flow Matching 解码器)在多语种混排上展现出了目前开源界的最佳水准。英文单词直接嵌入在中文句子中读出时,发音地道、重音准确,完全没有传统音素拼接的违和感。 - ---- - -## 3. 局域网网络与硬件拓扑 - -整套系统的部署拓扑如下: - -``` -[ 外部调用 / 终端应用 ] - │ - ▼ -[ 群晖 DSM NAS (192.168.1.1) ] - ├── 反向代理网关 (Traefik / Nginx) - └── n8n 自动化调度集群 (Stack 272) - │ 局域网 HTTP POST / GET (/webhook/ltts) - ▼ (千兆内网无公网延迟) -[ Unraid 7.x 主机 (192.168.1.6) ] - └── Windows 11 虚拟机 (GPU 直通) - ├── NVIDIA GeForce RTX 3060 12GB - └── CosyVoice 2 FastAPI 服务 (127.0.0.1:50000) +```bash +curl -s "http://192.168.1.1:8081/webapi/query.cgi?api=SYNO.API.Info&query=all" \ + | python -c "import json,sys; d=json.load(sys.stdin)['data']; print(len(d), 'APIs')" ``` -通过在 CosyVoice 的服务脚本中直接挂载 FastAPI 路由,我们在 Windows 本地 `50000` 端口暴露出 `/tts` 端点,内网其他服务只需向 `http://192.168.1.123:50000/tts` 发送请求即可在 2 秒内拿回二进制 WAV 音频。 - ---- - -## 4. 显存治理:常驻守护与一键开关 - -12GB 显存如果任由各个 AI 工具同时加载,瞬间就会爆显存(OOM)。我们采取了“分级常驻 + 幂等开关”策略: - -1. **低显存常驻(日常状态)**:CosyVoice 2 推理仅占用 **3.2 GB 显存**,剩余近 9 GB 显存完全足以同时运行日常的系统桌面和轻量任务。我们将其写入 Windows 开机启动项(`shell:startup\CosyVoice 2.lnk`),开机静默常驻后台。 -2. **一键切换脚本(高负载避让)**:当需要运行 ComfyUI 渲染整首 MV 或加载 14B 大语言模型时,桌面上放有一个免人工干预的批处理快捷方式 `CosyVoice 2 (开·关).bat`: - -```bat -@echo off -title CosyVoice 2 Toggle -for /f "tokens=5" %%a in ('netstat -aon ^| findstr :50000') do ( - taskkill /F /PID %%a >nul 2>&1 - echo STOPPED. GPU 显存已完全释放。 - exit /b -) -:: 若未运行,拉起后台推理服务 -start /b python webui.py --port 50000 --model_dir pretrained_models/CosyVoice2-0.5B -echo ONLINE - CosyVoice 2 已加载至显卡,服务就绪。 +``` +1515 APIs ``` -双击一次即刻杀掉进程、半秒内退还 3.2GB 显存;渲染完毕后再双击一次,25 秒内重新完成模型加载。 - ---- - -## 5. 群晖 N8N 联动接入 - -我们在群晖 n8n 上配置了名为 **`Local TTS API (CosyVoice)`** 的独立工作流,绑定路径为 `/webhook/ltts`: - -- **GET 支持**:`http://192.168.1.1:5678/webhook/ltts?text=你好Hello&voice=child`,浏览器或监控告警可直接单链调用下载。 -- **POST 支持**:接收标准 JSON 体 `{"text": "...", "voice": "..."}`,供各类聊天机器人与后台脚本程序化触发。 - -在工作流内部,我们使用 JavaScript Code 节点对传入文本做字符解码与清洗,再通过 HTTP Request 节点转发给本地 50000 端口,最终以 `firstEntryBinary` 模式直接将音频流送还客户端。 - ---- - -## 6. 音色库扩展:零样本克隆实践 - -得益于 CosyVoice 2 的 Zero-shot 能力,只需提供 3~5 秒无杂音的人声样音,模型即可实时复刻其声线特征。我们在服务内部预制了常用音色表: - -| 音色代号 | 声音风格 | 样音来源与特色 | -| :--- | :--- | :--- | -| `child` / `girl` | 活泼女童声 | 纯净 4 秒学前童声对话,清脆甜美 | -| `boy` | 清脆男童声(正太音) | 5 秒少儿动漫旁白 | -| `male` / `yunxi` | 阳光青年男声 | 5 秒科技解说,**中英专业词汇混读极佳** | -| `news` | 沉稳新闻男声 | 5 秒纪录片解说样本 | -| `female` | 温暖知性女声 | 5 秒电台散文朗诵 | -| `default` | 旗舰高保真女声 | CosyVoice 官方基准母声 | - -调用时只需指定 `voice` 参数,无需重启后端或切换模型权重,即可实现毫秒级换人合成。 - ---- - -## 7. 运行成效 - -在本地 RTX 3060 上运行实测: -- **生成效率**:实时率(RTF)稳定在 **0.18** 左右,合成一段 10 秒的标准语音仅耗时约 **1.8 秒**。 -- **首包响应**:n8n 收到请求至音频开始回传约 **320 毫秒**,完全满足交互式即时语音应答的要求。 -- **自主掌控**:不再受制于第三方厂商的封号、限频与网络审查,所有音频资产与 Prompt 完全留存在本地内网。 - -自托管高品质 AI 语音不再是大型服务器集群的专利。借助新一代自回归+扩散语音架构与消费级显卡,一套完全受控、零月租且音质超越商业云服务的全天候语音栈,已经完全可以在自托管生产环境中稳定运转。 -```` - -### 🇬🇧 英文版原文 (English Markdown Primary) -````markdown ---- -title: "How I Replaced Cloud TTS with a Self-Hosted Neural Voice Stack on an RTX 3060" -description: "How I migrated our production automation workflows from cloud speech APIs to a self-hosted CosyVoice 2 pipeline on a 12GB RTX 3060, integrated with Synology N8N." -pubDate: 2026-10-22 -category: case-studies -blueprint: ai-agent-automation -blueprintLayer: L3-local-gpu-inference -tags: ["tts", "ai", "n8n", "gpu", "cosyvoice", "self-hosting"] -ogImage: "/og/self-hosted-tts-cosyvoice2-n8n-gpu.jpg" -banner: "/banners/self-hosted-tts-cosyvoice2-n8n-gpu.jpg" -draft: false ---- - -For nearly two years, our internal business workflows, Telegram bots, and automated learning summaries relied on cloud-hosted text-to-speech APIs. Initially, Microsoft Edge-TTS provided a generous, zero-cost bridge. But running production workloads over unofficial browser-endpoint scraping is inherently fragile: sudden upstream schema changes, IP rate limits, and latency spikes across international transit routes routinely caused intermittent delivery drops. Commercial APIs like Azure Speech or Google Cloud TTS offered stability, but recurring meter billing scales awkwardly when generating long-form narration. - -With a dedicated RTX 3060 12GB GPU passed through to a Windows 11 VM on our Unraid server, we decided to bring our entire speech synthesis stack fully on-premises. - -Here is how we architected a self-hosted neural TTS pipeline using Alibaba's open-source **CosyVoice 2**, hooked it into our Synology DSM **n8n** automation cluster, managed GPU memory alongside our other local AI models, and achieved instant sub-second audio responses across Chinese, English, and mixed-language speech. - ---- - -## 1. The Design Goals - -Before touching code, our target operational envelope required four non-negotiable criteria: - -1. **Fluid Bilingual Code-Switching**: In Malaysian and Southeast Asian business communication, text is almost never purely monolingual. Sentences naturally mix Chinese syntax with English technical terms (e.g., *"请检查这个 pull request 并确认 webhook 状态"*). The engine must articulate both languages without sudden cadence jumps or unnatural accent shifts. -2. **Zero-Shot Voice Variety**: We needed distinct voice profiles—cheerful child voices for storybook projects, authoritative male anchors for news roundups, and clear conversational female tones for support bots—cloned from brief reference clips without days of fine-tuning. -3. **Constrained VRAM Footprint**: The RTX 3060 has 12GB of VRAM. Our VM regularly runs local LLMs (Qwen GGUF on LM Studio) and ComfyUI image/video pipelines. The TTS engine had to either idle under ~3.5GB of VRAM or provide frictionless cold-start toggles. -4. **Drop-in Webhook Compatibility**: Our central automation runs on Synology DSM via n8n (`192.168.1.1:5678`). Replacing cloud nodes could not require rewriting dozens of downstream workflow schemas. - ---- - -## 2. Model Selection: Why CosyVoice 2 Won - -We evaluated the primary open-source contenders against our bilingual requirement: - -| Model Architecture | Strengths | Drawbacks | Verdict | -| :--- | :--- | :--- | :--- | -| **Edge-TTS / Piper** | Ultra-lightweight, CPU-only | Robotic cadence, rigid voices, cloud dependency | Deprecated | -| **ChatTTS** | Conversational laughter, pause tags | Unpredictable halluncinations, weak English | Not suitable | -| **GPT-SoVITS v2** | Unrivaled character cloning accuracy | Phoneme boundaries stumble on mixed Chinese-English | Secondary / On-demand | -| **CosyVoice 2 (0.5B)** | **Superb bilingual flow, 300ms first-packet latency** | 3.2GB VRAM baseline | **Primary Production Engine** | - -CosyVoice 2 (the 0.5B parameter variant from Alibaba's FunAudioLLM team) emerged as the definitive winner. By combining an autoregressive language model with flow-matching diffusion decoders, it treats cross-lingual text-to-speech as a unified sequence. English terms embedded inside Chinese phrases flow with native pronunciation and natural human breath pauses. - ---- - -## 3. Infrastructure & Network Topology - -Our self-managed infrastructure runs on a tiered hardware split: +一千五百一十五个。其中出现了 `SYNO.Office.*`——但只有快照和一个"最近使用的公式"列表: ``` -[ Internet / Clients ] - │ - ▼ -[ Synology DSM NAS (192.168.1.1) ] - ├── Portainer / Traefik Reverse Proxy - └── n8n Automation Engine (Stack 272) - │ HTTP POST / GET (/webhook/ltts) - ▼ (Local 1Gbps LAN) -[ Unraid 7.x Server (192.168.1.6) ] - └── Windows 11 VM (GPU Passthrough) - ├── NVIDIA GeForce RTX 3060 12GB - └── CosyVoice 2 FastAPl Service (127.0.0.1:50000) +SYNO.Office.Sheet.Snapshot +SYNO.Office.Sheet.Snapshot.History +SYNO.Office.Sheet.MruFc ``` -The Windows VM hosts the CUDA 12.x PyTorch runtime. We exposed a lightweight FastAPI wrapper inside CosyVoice’s runtime script (`webui.py`), allowing our Synology n8n instance to trigger generation over LAN via `http://192.168.1.123:50000/tts`. +没有 values 端点。没有 styles 端点。没有写入端点。我把整个目录过滤了一遍,找任何提到 sheet 或 cell 的东西,结果一无所获,然后我得出结论——并且告诉了托我建这个东西的人——**这台 NAS 没有单元格级的电子表格 API。** ---- +那个结论是错的。我想把错在哪说清楚,因为那个推理错误才是可以复用的部分:**我把一个发现面当成了全部。** 网关目录列出的是 DSM 自己的 Web 网关服务的 API。Office Suite API 不由那个网关提供。它是一个独立服务,作为一个独立产物发布,因此对我跑的那次查询不可见。 -## 4. Managing GPU Memory: Resident vs. On-Demand +## 陷阱一:把正在运行的服务报成未安装的工具 -Leaving every AI model loaded simultaneously will exhaust 12GB of VRAM instantly. We designed a dual-tier lifecycle: +在找到真正的答案之前,我花了不少时间确信这个软件根本没在跑。两条命令让这个说法看起来很成立。 -1. **CosyVoice 2 as the Resident Daemon**: Consuming only **3.2 GB of VRAM**, CosyVoice 2 runs as an auto-starting background service when Windows boots (`shell:startup\CosyVoice 2.lnk`). This leaves 8.8 GB free for general desktop and lightweight inference. -2. **One-Click State Toggle Batches**: For heavy tasks (such as running 1080p video generation in ComfyUI or 14B LLMs), we created an idempotent batch script on the desktop: +第一条是 Synology 自己的套件状态查询: -```bat -@echo off -title CosyVoice 2 Toggle -for /f "tokens=5" %%a in ('netstat -aon ^| findstr :50000') do ( - taskkill /F /PID %%a >nul 2>&1 - echo STOPPED. GPU memory freed. - exit /b -) -:: If stopped, launch background worker -start /b python webui.py --port 50000 --model_dir pretrained_models/CosyVoice2-0.5B -echo ONLINE - CosyVoice 2 loaded to GPU. +```bash +sudo synopkg is_onoff SynologyDrive +sudo synopkg is_onoff Spreadsheet ``` -A single double-click halts the process and reclaims all 3.2GB within 500ms; clicking it again restores the service in under 25 seconds. - ---- - -## 5. Integrating with Synology N8N - -In n8n, we configured a dedicated workflow: **`Local TTS API (CosyVoice)`** listening on `/webhook/ltts`. - -To ensure total interoperability with existing scripts, the workflow accepts both: -- **`GET /webhook/ltts?text=Hello&voice=child`**: Ideal for browser testing and simple URL triggers. -- **`POST /webhook/ltts`** with JSON body `{"text": "...", "voice": "..."}`: Used by our bots and backend services. - -The n8n pipeline consists of three streamlined nodes: -1. **Webhook Node**: Receives incoming requests. -2. **Parse & Clean Text (Code Node)**: Normalizes character encodings and defaults voice selections. -3. **HTTP Request Node**: Forwards the JSON payload to `http://192.168.1.123:50000/tts` and streams the binary `audio/wav` response directly back to the requester. - ---- - -## 6. Curating Zero-Shot Reference Voices - -CosyVoice 2 synthesizes speech using zero-shot voice cloning: feeding a 3- to 5-second clean audio sample allows the model to clone the acoustic timbre instantly. - -We packaged a library of curated reference samples into `asset/voices/` and mapped them to intuitive alias parameters: - -| Voice Key | Style Profile | Sample Source | -| :--- | :--- | :--- | -| `child` / `girl` | Cheerful female child voice | Clean 4s preschool dialogue clip | -| `boy` | Energetic young boy (anime style) | 5s youth animation dialogue | -| `male` / `yunxi` | Engaging, modern tech male anchor | 5s professional narration | -| `news` | Deep, formal broadcast presenter | 5s documentary voiceover | -| `female` | Warm, conversational support agent | 5s acoustic reading sample | -| `default` | Original CosyVoice high-fidelity voice | Model's baseline reference | - -Switching voices is as simple as passing `&voice=child` in the query string or `{"voice": "male"}` in the POST payload. - ---- - -## 7. Real-World Performance - -Running on the RTX 3060: -- **Generation Speed**: Real-time factor (RTF) averages **0.18**. A 10-second sentence renders in under **1.8 seconds**. -- **Latency**: First audio packet arrives at n8n in approximately **320ms**, enabling near-instant voice replies on Telegram. -- **Cost & Privacy**: Zero monthly cloud API charges, zero audio data leaving our local subnet, and complete immunity to external provider outages. - -Self-hosting modern neural TTS is no longer an exercise in brittle compile scripts and robotic phoneme tables. With open-source diffusion models and a modest 12GB workstation GPU, you can run a private, high-fidelity voice engine that surpasses commercial cloud offerings in customization and control. -```` - ---- - -## 文章 08 / 10:我如何在自家 NAS 上自托管 Mem0 记忆栈(让 AI 助手有记忆) -- **Slug**: `self-hosting-mem0-memory-stack` -- **英文标题**: How I Self-Hosted a Mem0 Memory Stack (So My AI Agent Remembers) -- **分类**: `case-studies` | **发布日期**: 2026-09-16 -- **线上地址**: https://blog.hoelee.com/posts/self-hosting-mem0-memory-stack/ (EN) | https://blog.hoelee.com/posts/zh/self-hosting-mem0-memory-stack/ (ZH) -- **本篇审核状态**: ⏳ 待审核 (Pending) - -### ✍️ 顾问审阅意见区 (Review Feedback) -```text -【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 -【事实与数字核对】: -【人设与用词卫生】: -【CRO与转化建议】: +``` +SynologyDrive isn't turned on, [262] +Spreadsheet isn't turned on, [262] ``` -### 🇨🇳 中文版原文 (Chinese Markdown Twin) -````markdown ---- -title: "我如何在自家 NAS 上自托管 Mem0 记忆栈(让 AI 助手有记忆)" -description: "一套私有、自托管的 AI 助手记忆层——mem0 API + LiteLLM + PostgreSQL/pgvector,跑在 Synology NAS 上。语义记忆由你掌控,而不是第三方手里。" -pubDate: 2026-09-16 -category: case-studies -tags: [mem0, docker, postgres, pgvector, litellm, ai, sharing] -ogImage: /og/zh-self-hosting-mem0-memory-stack.jpg -banner: /banners/self-hosting-mem0-memory-stack.jpg ---- +与此同时两个套件都明摆着在服务请求。`SynologyDrive` 自己的状态文件里是 `status=enabled`,Office 的守护进程也在进程表里——一个任务守护进程、一个跑在 `office` 用户账户下的连接池,还有网关 worker。在这套 DSM 版本上,`is_onoff` 根本不是一个可靠的答案。 -一个每次对话后都忘光一切的 AI 助手,就是一个每轮都要你重新自我介绍的工具。我的 AI 助手(就是驱动这个博客工作流的那个)曾经每场会话都从零开始——直到我给它加了一层**记忆**:一套自托管的 [mem0](https://mem0.ai) 栈,负责存储它学到的事实、按语义检索、并跨会话存活。 +第二条命令更糟,因为那是我自己的失误: -这就是我在自家 Synology NAS 上自托管它的故事——私有、完全由我掌控、数据绝不离开我的局域网。 - -## 为什么这件事重要 - -记忆层改变的是一个助手真正能为企业做的事: - -- **不再重复回答同样的问题。** 记住客户获批的试用、他买的产品、上次的售后问题——下一段对话从上一次结束的地方继续。 -- **让「个性化」成真。** 一个记得客户偏好和历史记录的机器人,就是一个人。这不是提示词糖衣;这是一份存储的、可检索的记录。 -- **把数据掌控权留在自己手里。** 我对托管式记忆服务不满的每一点,自托管都解决了——事实存在我自己的 PostgreSQL 里、我自己的 NAS 上、我自己网络的后面。 - -对任何跑 AI 助手(售后机器人、研究助手、个人自动化)的人来说,问题不是助手**要不要**记住——而是这份记忆是一份私有资产,还是第三方的数据。 - -## mem0 做了什么 - -Mem0 是给 LLM 应用用的「开箱即用的记忆」。你不用手搓嵌入表和相似度检索,它给一个小 API,把记忆需要的三件事都做了: - -1. **加一条记忆** —— `POST /memories` 传一条事实或一段对话;它抽取、去重并存储(可选由 LLM 分类)。 -2. **检索** —— `GET /search` 带一个 query,返回按语义相似度排序的相关事实。 -3. **按用户隔离** —— 记忆归属 `user_id`,所以可以按客户、按项目、按会话分开,互不串扰。 - -「记忆」就是抽取出来的事实;「检索」就是向量相似度。哪怕你从没亲手碰过向量数据库,也能让助手有记忆。 - -## 技术栈 - -Synology DS1821+ 上用 Portainer compose 栈跑三个容器: - -- **mem0 API** —— 记忆服务本身(本地自定义构建),监听 `20015` 端口。 -- **LiteLLM** —— 真正做事实抽取的模型前面的 LLM 网关。不碰 mem0 配置就能换底层模型。 -- **PostgreSQL 17 + pgvector** —— 数据库。`pgvector/pgvector` 把 Postgres 和向量扩展打包成一等公民,语义搜索和别的一切同库。 - -```text -┌──────────────┐ /search & /memories ┌──────────────────┐ -│ AI agent / │ ──── X-Api-Key + JSON ───────▶ │ mem0 API :20015 │ -│ Hermes / bot │ └────────┬─────────┘ -└──────────────┘ │ pgvector - ▼ - PostgreSQL 17 + pgvector -┌──────────────┐ model calls (extract) ┌──────────────────┐ -│ OpenAI etc. │ ◀───────── LiteLLM ──────────│ fact-classifier │ -└──────────────┘ └──────────────────┘ +```bash +ps w | grep -iE "office|drive|pgbouncer" ``` -一份有代表性的 compose 长这样: +``` +(no output) +``` + +那看起来像一台死机。它不是。**在 DSM 上,不带 `sudo` 的 `ps` 只会显示你自己的进程。** 用 root 重跑一遍,画面就反转了: + +```bash +sudo ps aux | grep -E "office|pgbouncer|synoscgi" | grep -v grep +``` + +它们全都在。我用两条根本不可能让我看到真相的命令,"证明"了两次这套栈是挂的: + +> 如果要从这篇帖子里带走一个习惯:当一个诊断工具说"什么都没有在跑"时,先检查这个诊断工具到底有没有权限看到任何东西。 + +## 陷阱二:没有启动错误信息的容器 + +真正的答案,在我停止相信自己亲手得出的证据之后,出现在 Docker Hub 上:`synology/spreadsheet-api`。它不是 Office 套件的一部分,也不是网关端点。它自己的描述说得很清楚: + +> "Spreadsheet API 不是 Office 套件的一部分。这个镜像在客户端和 DSM 之间提供代理服务。每个 worker 专属于单个用户和单个电子表格。" + +兼容性表格把镜像标签对到 Office 版本上,这是第一件要查的事,因为配对不是可选的: + +| Docker 镜像标签 | 所需的 Synology Office 版本 | +|---|---| +| `3.4.1` | 3.7.0 或更高 | +| `3.3.2` | 更老的版本 | + +Synology 还警告不要把镜像和 Office 放在同一台机器上,因为每个 worker 会把整个电子表格加载进内存。我仍然把它跑在同一个 DSM 上,并加了内存上限——这是有意的取舍,不是推荐做法。 + +然后我跑了它,它立刻死掉,吐出一段这个: + +``` +/app/dist/index.js:424 +}`;var ot=UD(function(){return Ht($,qe+"return "+Ee).apply(e,H)});... +``` + +一段压缩过的 JavaScript——最没用的一类错误信息。真相一旦找到,其实很平常:**`AUTH_SECRET` 是必填项,而且没有默认值。** 它给会话令牌签名。没有它,服务就起不来,而且没法告诉你为什么。 + +要可靠地读出容器的真实要求,而不是听它的启动噪音,直接向打包产物要答案: + +```bash +docker run --rm --entrypoint grep synology/spreadsheet-api:3.4.1 \ + -ohE '.{0,80}process\.env\.PORT.{0,80}' /app/dist/index.js +``` + +```js +serverPort: parseInt(process.env.PORT) || 3e3, +serverHost: process.env.HOST || "0.0.0.0", +workerTimeout: parseInt(process.env.WORKER_TIMEOUT) || 600*1e3, +``` + +一行就给出配置契约:`AUTH_SECRET` 给令牌签名,`PORT` 默认 `3000`,`HOST` 默认 `0.0.0.0`,worker 十分钟后回收。它还自带一份 OpenAPI 规范和 Swagger UI,这个我后面会再说到。 + +## 陷阱三:密码被证明正确,却收到 401 + +容器跑起来之后,认证成了下一堵墙。这是请求,这是它返回的东西: + +```bash +curl -s -X POST http://192.168.1.1:8791/spreadsheets/authorize \ + -H 'Content-Type: application/json' \ + -d '{"username":"","password":"","host":"192.168.1.1:5001","protocol":"https"}' +``` + +```json +{"error":"Unauthorized"} +``` + +`401 Unauthorized`,而我用的正是刚刚登录过 DSM 的密码。最自然的解读——密码错了、账户错了——是一条死路,而我真走了进去:重新敲一遍密码,在 DSM 登录页试那个账户(能登录),把 HTTPS 换成 HTTP 端口(同样 401)。 + +真正的问题出在 `host` 字段。这个服务反过来问*你*该对着哪个 DSM 做认证,然后自己跟那个 host 做一次 TLS 握手。我给它的是一个裸 IP 地址,而用那个名字出示的证书和地址不匹配,于是握手失败——代理把一个失败的握手报成 `Unauthorized`,跟密码错误一模一样。 + +换成一个持有有效证书的主机名,立刻就修好了: + +```bash +curl -s -X POST http://192.168.1.1:8791/spreadsheets/authorize \ + -H 'Content-Type: application/json' \ + -d '{"username":"","password":"","host":"cloud.example.com","protocol":"https"}' +``` + +```json +{"token":"eyJhbGciOi...","host":"cloud.example.com"} +``` + +> **如果你的 Synology API 登录返回 401 而你又确定密码是对的,去查 `host`:它必须是一个容器能接受其证书的名字。一个裸的局域网 IP 不行。** + +它返回的令牌是 JWT,有效期 28 天,绑定一个 DSM 会话——所以 DSM 重启或账户被强制登出,它就会失效。集成中途突然冒出来的 `401`,当作"重新授权"来对待,而不是"凭据变了"。 + +## 陷阱四:2FA 永远无法认证 + +这个是如果你事先不知道就会浪费最多时间的一个,所以直说:**登录 schema 里没有一次性验证码字段。** + +```yaml +AuthorizationBody: + properties: + username: {type: string} + password: {type: string} + host: {type: string} + protocol: {type: string} +``` + +没有 OTP,没有应用密码,没有令牌交换。如果账户开了两步验证,这个 API 会永远返回 `401`——密码正确也一样,换哪个 host 都一样。唯一可行的安排是开一个关掉 2FA 的专用服务账户,权限只限定在它需要的文件夹——这本来就是更好的做法,也是我一开始就该做的,而不是先用我自己的管理员账户去试。 + +## 进得来之后:权限陷阱 + +认证不等于授权。等我的服务账户能登录了,针对我真正关心的那个电子表格的每次调用都返回: + +```json +{"statusCode":403,"code":"403","error":"Forbidden","message":"Permission denied"} +``` + +仔细读一下,它信息量很大:`403 Permission denied` 意味着**文件存在,但你无权拿到。** 一个错误的 ID 会返回别的东西: + +```json +{"statusCode":404,"code":"404","error":"Not Found","message":"Spreadsheet not found"} +``` + +两种不同的失败,两种不同的修法,把两者混为一谈就要白花一个小时。我的问题是位置问题:那个电子表格建在 Synology Drive 的个人 **My Drive** 里,在磁盘上是 `/volume1/homes//Drive/Document/…`。个人主目录别的 DSM 账户够不着——权限设置不行,共享文件夹的技巧也不行,因为它根本不在任何共享文件夹里。修法是把这个文件移进一个共享文件夹并在那里授予读写权限,或者用 Drive 把那个特定文件分享给服务账户并授予编辑权。 + +## 修复:一整套能跑通的配置 + +容器,配上一个真正的密钥和内存上限: ```yaml services: - mem0-postgres: - image: pgvector/pgvector:pg17 + spreadsheet-api: + image: synology/spreadsheet-api:3.4.1 + container_name: spreadsheet-api + restart: always environment: - POSTGRES_USER: mem0 - POSTGRES_PASSWORD: ${MEM0_DB_PASSWORD} - POSTGRES_DB: mem0 - volumes: - - ./data/pg:/var/lib/postgresql/data - restart: unless-stopped - - mem0-litellm: - image: ghcr.io/berriai/litellm:main-stable - command: ["--config", "/app/config.yaml"] - volumes: - - ./litellm-config.yaml:/app/config.yaml - restart: unless-stopped - - mem0-api: - build: ./mem0-api - environment: - OPENAI_API_KEY: ${OPENAI_API_KEY} - OPENAI_API_BASE: http://mem0-litellm:4000/v1 # go through the gateway - MEM0_API_KEY: ${MEM0_API_KEY} # X-Api-Key for /search & /memories - POSTGRES_URL: postgresql://mem0:${MEM0_DB_PASSWORD}@mem0-postgres/mem0 + AUTH_SECRET: "" + PORT: "3000" + HOST: "0.0.0.0" ports: - - "20015:8000" - restart: unless-stopped + - "8791:3000" + mem_limit: 2g ``` -(我是从 mem0 仓库本地构建、把模型/事实抽取指向 LiteLLM;确切的镜像版本是我自己维护本地镜像的结果。真实 API key 我放在 compose 文件外面,走环境变量密文注入。) +一条只属于 DSM 的注意事项:DSM 上任何 compose 文件都别写 `cpus:`。它的内核没有 CPU CFS 调度器,这个键会被静默忽略——你得到的是有 CPU 限制的错觉,其实没有任何限制。 -## 使用 - -起起来之后,这个 API 小到意外。加一条事实(快速、逐字保存): +然后 API 就能用了,而且形态很讨喜。登录,创建或指定一个电子表格,读写范围: ```bash -curl -X POST http://192.168.1.1:20015/memories \ - -H "Content-Type: application/json" \ - -H "X-Api-Key: $MEM0_API_KEY" \ - -d '{ - "user_id": "customer-2211", - "text": "Customer 2211 prefers email over WhatsApp for order updates." - }' +TOKEN=$(curl -s -X POST http://192.168.1.1:8791/spreadsheets/authorize \ + -H 'Content-Type: application/json' \ + -d '{"username":"","password":"","host":"cloud.example.com","protocol":"https"}' \ + | python -c "import json,sys; print(json.load(sys.stdin)['token'])") + +# read a range (sheet-qualified A1 notation) +curl -s -H "Authorization: Bearer ***" \ + "http://192.168.1.1:8791/spreadsheets//values/Sheet1!A1:C4" + +# write a range, formulas included +curl -s -X PUT -H "Authorization: Bearer ***" -H 'Content-Type: application/json' \ + -d '{"values": [["Item","Qty"],["Widget",12],["Gadget",7],["Total","=SUM(B2:B3)"]]}' \ + "http://192.168.1.1:8791/spreadsheets//values/Sheet1!A1:B4" ``` -之后再取最相关的记忆: +两个我没想到的细节,都是对我有利的: + +- **电子表格 ID 来自 Office 的 URL。** 一个位于 `…/oo/r/` 的电子表格——包括分享链接转到的也正是这个路径——把它那一段放进 API 调用就能寻址。 +- **公式是 Office 算的,不是你算的。** 把表格导出成 CSV 返回的是 `=SUM(B2:B3)` 和 `=SUMPRODUCT(B2:B3,C2:C3)` 的*求值后*结果——这些公式我从没在客户端算过。这正是用这个 API 而不是自己解析文件的全部理由:你继承了 Synology 自己的计算引擎。 + +有一个值得说出来的真实缺口:**没有 list 端点。** 规范声明了一个 "Statistics" 标签,却没有为它提供任何路由(`/statistics` → `404 Route not found`),也没有别的东西能枚举电子表格。你必须已经从文档的 URL 知道那个 ID。对你有意搭好的自动化来说没问题;如果你想浏览,那就没用。 + +## 从另一端得到一张图表 + +读单元格只是半件事;最初的要求里还有图表。同一个 API 能直接给你一份真正的 workbook: ```bash -curl -X POST http://192.168.1.1:20015/memories/search \ - -H "Content-Type: application/json" \ - -H "X-Api-Key: $MEM0_API_KEY" \ - -d '{ - "user_id": "customer-2211", - "query": "how should I reach this customer?", - "limit": 5 - }' +curl -s -H "Authorization: Bearer ***" \ + "http://192.168.1.1:8791/spreadsheets//xlsx" -o export.xlsx ``` -然后把返回的事实塞进助手回答前的系统提示词(或上下文)。这就是全部循环:**存事实、召回相关的、在下一句回复里用上。** +那会返回一个合法的 `.xlsx`——`PK` 魔数,什么都能打开。接着我自己的服务(一个小的 FastAPI 容器,里面有 LibreOffice 负责公式求值,matplotlib 负责渲染)读取范围并生成 PNG 图表和仪表盘,整条管线端到端跑通,不需要 Excel,也不需要任何云依赖: -### 让我花了一天时间的 `infer` 坑 +``` +Synology Office → spreadsheet-api → .xlsx export → chart renderer → PNG +``` -- `POST /memories` 默认 **`infer=true`** 会跑 LLM 事实抽取器——分类、清洗每条记忆。聪明但**慢**,而且每次调用都要一次模型往返。 -- 如果我只是想让助手**逐字快速地**记下某件事(客户说「请叫我 Andy」),我传 **`infer=false`**——不经过 LLM,近乎瞬时存储。 +## 重来一次我会怎么做 -我栈上的路由是 `/search` 和 `/memories`,**没有 `/v1` 前缀**(早期一个自以为有 `/v1` 的包装器 404 了一阵子),认证是朴实的 `X-Api-Key` 头。都是小事,但都让我费过时间。 - -## 如果重来我会怎么做 - -- **从第一天起对常规记录就用 `infer=false`。** 只对重要的事实跑 LLM 抽取;默认的推理模式让每一次写入都为了一句随手记付出的成本不值。 -- **把 API key 当真正的机密。** 它会嵌进 agent 配置和 compose 环境变量里,所以我把它从 compose 文件中拿出来,用环境密文注入。 -- **把数据库放在我信任的盘上。** Mem0 的下限就是你 Postgres 的下限。我把它跑在 NAS 受保护的卷上、带备份任务——因为一个会失忆的记忆层还不如没有。 +1. **在断定某个 Synology 功能不存在之前,先去查 Docker Hub。** 我花了不少真实时间,从一个根本不可能包含答案的 API 清单去证明一个反面结论。`synology/*` 在 Docker Hub 上,一次搜索就到。 +2. **一开始就用一个关掉 2FA 的专用服务账户**,权限限定在单个共享文件夹。我先用管理员账户试,所以同一小时内同时撞上了 2FA 墙和 `403` 墙。 +3. **当一个诊断工具说"什么都没有在跑",检查它的权限。** DSM 上不带 root 的 `ps` 不是进程列表,它是你自己的进程列表,它会高高兴兴地让你得出机器已死的结论。 +4. **读容器本身,别只读它的文档。** 厂商自己的运行命令在镜像页面上,但精确的默认值(`PORT` 3000,worker 超时 600 秒)和必填的 `AUTH_SECRET` 来自 grep 打包产物——一条命令,不用猜。 ## 结果 -一层私有、自托管的记忆,用两个小 HTTP 调用就能访问。我的助手现在跨会话记得客户、偏好和决策——而且因为整个栈都在我自己网络后面的 PostgreSQL 里,这一切都没有离开我的掌控。 - -如果你跑的 AI 助手动不动就忘掉上下文,自托管 mem0 是最划算、最省事的升级之一——而且你能在不把记忆送进别人数据库的前提下做到。 +在 NAS 上端到端验证:登录、创建、写单元格、读回单元格、CSV 导出和 `.xlsx` 导出全部返回 `200`,CSV 导出证明了 Office 引擎在服务端求值了 `=SUM`/`=SUMPRODUCT`。导出的 workbook 喂给图表服务,把同一份数据渲染成 PNG。四个陷阱记录在案,一个错误结论得到纠正,大约一天的活——现在我自己的硬件上有一份脚本可以驱动的电子表格。 --- -## 想让你的生意也用上带记忆的 AI 吗? - -我为企业构建并自托管 AI 助手、记忆栈、网站和基础设施。如果你想让助手真正**记住**你的客户——或者你想聊聊雇佣我——我很乐意帮上忙: - -- 📱 **WhatsApp:** [+60 12-797 2969](https://wa.me/60127972969) -- 📧 **邮箱:** [me@hoelee.com](mailto:me@hoelee.com) -- 🌐 **网站:** [hoelee.com](https://hoelee.com) +*我在马来西亚为小企业做这类自托管集成——电子表格和 NAS 自动化、仪表盘,以及把你的数据留在你自己硬件上的内部工具。如果你需要这类东西,[WhatsApp 联系我](https://wa.me/60127972969) 或 [给我发邮件](mailto:me@hoelee.com?subject=Self-hosted%20spreadsheet%20automation)——也可以看看我在 [hoelee.com](https://hoelee.com) 还做些什么。* ```` ### 🇬🇧 英文版原文 (English Markdown Primary) ````markdown --- -title: "How I Self-Hosted a Mem0 Memory Stack (So My AI Agent Remembers)" -description: "A private, self-hosted memory layer for AI agents — mem0 API + LiteLLM + PostgreSQL with pgvector on a Synology NAS. Semantic memory under your control, not a third party's." -pubDate: 2026-09-16 -category: case-studies -tags: [mem0, docker, postgres, pgvector, litellm, ai, sharing] -ogImage: /og/self-hosting-mem0-memory-stack.jpg -banner: /banners/self-hosting-mem0-memory-stack.jpg +title: "The Synology Spreadsheet API Is a Container, Not an API Endpoint" +description: "How to automate Synology Office spreadsheets: the official spreadsheet-api container, and the four traps — a fake 'not installed', a 401 with correct credentials, 2FA that can never authenticate, and a permission wall." +pubDate: 2025-08-20 +updatedDate: 2026-09-26 +category: devops +blueprint: sme-digital-suite +blueprintLayer: L3-entitlement-backoffice +tags: [synology, dsm, docker, portainer, rest-api, spreadsheet, debugging, self-hosting] +ogImage: /og/synology-spreadsheet-api-is-a-container.jpg +banner: /banners/synology-spreadsheet-api-is-a-container.jpg +draft: false --- -An AI agent that forgets everything between conversations is a tool you have -to reintroduce yourself to every session. My AI assistant (the one that runs -this very blog's workflow) used to start each chat from zero — until I gave it -a **memory layer**: a self-hosted [mem0](https://mem0.ai) stack that stores -facts it learns, retrieves them semantically, and survives across sessions. +I wanted something ordinary: read a cell from a spreadsheet on my NAS, write a cell back, and have a chart come out the other end — without opening Excel, and without shipping my company's numbers to a cloud API. -This is the story of how I self-hosted it on my Synology NAS — private, fully -under my control, no data leaving my LAN. +I run a Synology DS1821+ with Synology Office (the `Spreadsheet` package) installed, so this looked like a solved problem. It is a solved problem. It just took four separate false signals to find the actual solution, and one of my conclusions along the way was flatly wrong in a way worth writing down. ## Why this matters -A memory layer changes what an agent can actually *do* for a business: +If you self-host, you will eventually need a service to talk to another service on the same box. The failure modes in this post are not Synology-specific — they are the general shape of "the vendor ships the thing, but not where you'd look for it": -- **It stops re-answering the same questions.** Remember a customer's granted - trial, their product, their last support issue — and the next conversation - picks up where the last one ended. -- **It makes "personalization" real.** A bot that recalls your customer's - preferences and history is a bot that feels like a person. That's not - prompt-sugar; it's a stored, searchable record. -- **It keeps control of your data.** Every "memory" I dislike about hosted - memory services is solved by running the stack yourself — the facts live - in my own PostgreSQL, on my own NAS, behind my own network. +1. **A missing entry in an API list is not proof the API doesn't exist.** I enumerated 1,515 APIs and concluded the feature was absent. It was a container. +2. **Two of the diagnostics I trusted were lying.** `synopkg` reported a running package as "not turned on", and `ps` showed me an empty machine that was serving production traffic. +3. **The best-scoped credential failure looks like your fault.** A `401` with a verified-correct password is almost always about *where* you sent the request, not *what* you sent. +4. **The permission model bites after authentication.** You can log in perfectly and still be told `403` on every file, because of where the file lives. -For anyone running AI agents (support bots, research assistants, personal -automation) the question isn't *should* the agent remember — it's whether the -memory is a private asset or a third party's. +If any of that sounds familiar, the second half of this post is the working setup. -## What mem0 does +## What the docs say, and why that sent me the wrong way -Mem0 is "memory in a box" for LLM apps. Instead of you hand-rolling an -embeddings table and a similarity search, it gives you a small API that does -the three things memory needs: +Synology advertises "Office Suite APIs" — REST APIs for Drive, Spreadsheet, MailPlus and Calendar. The marketing page lists exactly what I wanted, verbatim: -1. **Add a memory** — `POST /memories` with a fact or a conversation; it - extracts, dedupes, and stores it (optionally classified by an LLM). -2. **Search** — `GET /search` with a query returns the most relevant stored - facts, ranked by semantic similarity. -3. **User scoping** — memories belong to a `user_id`, so you can keep memory - per customer, per project, or per conversation without cross-talk. +- "Read and write cell styles within a range." +- "Add, rename, delete, and export sheets as CSV files." +- "Create, retrieve, export, and delete spreadsheet. Perform batch updates…" -The "memory" is the extracted fact. The "retrieval" is vector similarity. You -get the agent even if you never touch a vector database yourself. +The documentation itself sits behind a Synology Account login, which is a normal thing to hit and not a scandal — but it means the first thing a search engine finds is the promise, not the contract. -## The stack +So I went looking on my own NAS. DSM exposes a gateway API catalogue, and you can just ask it what exists: -Three containers on my Synology DS1821+, as a Portainer compose stack: - -- **mem0 API** — the memory service itself (custom local build), listening - on port `20015`. -- **LiteLLM** — the LLM gateway in front of whatever model does the fact - extraction. I can swap the underlying model without touching mem0's config. -- **PostgreSQL 17 + pgvector** — the database. `pgvector/pgvector` bundles - Postgres with the vector extension as a first-class citizen, so semantic - search lives in the same DB as everything else. - -```text -┌──────────────┐ /search & /memories ┌──────────────────┐ -│ AI agent / │ ──── X-Api-Key + JSON ───────▶ │ mem0 API :20015 │ -│ Hermes / bot │ └────────┬─────────┘ -└──────────────┘ │ pgvector - ▼ - PostgreSQL 17 + pgvector -┌──────────────┐ model calls (extract) ┌──────────────────┐ -│ OpenAI etc. │ ◀───────── LiteLLM ──────────│ fact-classifier │ -└──────────────┘ └──────────────────┘ +```bash +curl -s "http://192.168.1.1:8081/webapi/query.cgi?api=SYNO.API.Info&query=all" \ + | python -c "import json,sys; d=json.load(sys.stdin)['data']; print(len(d), 'APIs')" ``` -A representative compose looks like this: +``` +1515 APIs +``` + +Fifteen hundred and fifteen. Among them, `SYNO.Office.*` appears — but only for snapshots and a "recently used formulas" list: + +``` +SYNO.Office.Sheet.Snapshot +SYNO.Office.Sheet.Snapshot.History +SYNO.Office.Sheet.MruFc +``` + +No values endpoint. No styles endpoint. No write endpoint. I filtered the whole catalogue for anything mentioning sheets or cells and came up empty, and I concluded — and told the person I was building this for — that **the NAS had no cell-level spreadsheet API.** + +That conclusion was wrong. I want to be precise about why it was wrong, because the reasoning error is the reusable part: **I treated one discovery surface as exhaustive.** The gateway catalogue lists APIs served by DSM's own web gateway. The Office Suite API is not served by that gateway. It is a separate service, published as a separate artifact, and therefore invisible to the query I ran. + +## Trap 1: the tool that says a running service isn't installed + +Before finding the real answer, I spent a while convinced the software wasn't even running. Two commands made that look true. + +The first was Synology's own package-state query: + +```bash +sudo synopkg is_onoff SynologyDrive +sudo synopkg is_onoff Spreadsheet +``` + +``` +SynologyDrive isn't turned on, [262] +Spreadsheet isn't turned on, [262] +``` + +Meanwhile both packages were plainly serving requests. `SynologyDrive` had `status=enabled` in its own state file, and the Office daemons were in the process table — a task daemon, a connection pooler running under an `office` user account, and gateway workers. `is_onoff` was simply not a reliable answer on this DSM build. + +The second command was worse because it was my own mistake: + +```bash +ps w | grep -iE "office|drive|pgbouncer" +``` + +``` +(no output) +``` + +That looks like a dead system. It isn't. **On DSM, `ps` without `sudo` shows you only your own processes.** Re-run it as root and the picture inverts: + +```bash +sudo ps aux | grep -E "office|pgbouncer|synoscgi" | grep -v grep +``` + +There they all are. I had "proven" the stack was down twice, using two commands that couldn't have shown me otherwise: + +> If you take one habit from this post: when a diagnostic says "nothing is running", check whether the diagnostic had the privileges to see anything at all. + +## Trap 2: the container with no startup error message + +The actual answer, once I stopped believing my own evidence, was on Docker Hub: `synology/spreadsheet-api`. Not part of the Office package, not a gateway endpoint. Its own description is unambiguous: + +> "Spreadsheet API is not part of the Office package. This image provides a proxy service between clients and DSM. Each worker is dedicated to a single user and a single spreadsheet." + +The compatibility table matches image tags to Office versions, which is the first thing to check because the pairing is not optional: + +| Docker image tag | Required Synology Office | +|---|---| +| `3.4.1` | 3.7.0 or higher | +| `3.3.2` | older | + +Synology also warns against co-locating it with Office, since each worker loads whole spreadsheets into memory. I ran it on the same DSM anyway and capped it, which is a deliberate trade rather than a recommendation. + +Then I ran it and it died immediately with this: + +``` +/app/dist/index.js:424 +}`;var ot=UD(function(){return Ht($,qe+"return "+Ee).apply(e,H)});... +``` + +A minified JavaScript blob — the least useful class of error message there is. The cause, once found, was mundane: **`AUTH_SECRET` is required and has no default.** It signs the session tokens. Without it the service cannot start and cannot tell you why. + +The reliable way to read a container's actual requirements, rather than its startup noise, is to ask the bundle directly: + +```bash +docker run --rm --entrypoint grep synology/spreadsheet-api:3.4.1 \ + -ohE '.{0,80}process\.env\.PORT.{0,80}' /app/dist/index.js +``` + +```js +serverPort: parseInt(process.env.PORT) || 3e3, +serverHost: process.env.HOST || "0.0.0.0", +workerTimeout: parseInt(process.env.WORKER_TIMEOUT) || 600*1e3, +``` + +That gives you the config contract in one line: `AUTH_SECRET` to sign tokens, `PORT` defaulting to `3000`, `HOST` to `0.0.0.0`, workers recycled after ten minutes. It also ships its own OpenAPI spec and a Swagger UI, which I'll come back to. + +## Trap 3: a 401 while the password is provably correct + +With the container running, authentication became the next wall. Here is the request, and here is what it returned: + +```bash +curl -s -X POST http://192.168.1.1:8791/spreadsheets/authorize \ + -H 'Content-Type: application/json' \ + -d '{"username":"","password":"","host":"192.168.1.1:5001","protocol":"https"}' +``` + +```json +{"error":"Unauthorized"} +``` + +`401 Unauthorized` with a password I had just used to sign into DSM. The natural reading — wrong password, wrong account — is a dead end, and I went down it: retyped the password, tried the account on the DSM login page (it worked), tried the HTTP port instead of HTTPS (same 401). + +The actual problem was the `host` field. The service asks *you* which DSM it should authenticate against, then does its own TLS handshake with that host. I had given it a bare IP address, and the certificate presented on that name doesn't match the address, so the handshake failed — and the proxy reports a failed handshake as `Unauthorized`, exactly like a bad password would. + +Switching to a hostname with a valid certificate fixed it instantly: + +```bash +curl -s -X POST http://192.168.1.1:8791/spreadsheets/authorize \ + -H 'Content-Type: application/json' \ + -d '{"username":"","password":"","host":"cloud.example.com","protocol":"https"}' +``` + +```json +{"token":"eyJhbGciOi...","host":"cloud.example.com"} +``` + +> **If your Synology API login returns 401 and you're sure the password is right, check the `host`: it must be a name whose certificate the container accepts. A bare LAN IP is not that.** + +The token it returns is a JWT, valid for 28 days, tied to a DSM session — so it dies if DSM restarts or the account is forcibly logged out. Treat a sudden `401` mid-integration as "re-authorize", not "credentials changed". + +## Trap 4: 2FA cannot ever authenticate + +This is the one that would waste the most time if you didn't know it in advance, so here it is plainly: **the sign-in schema has no one-time-code field.** + +```yaml +AuthorizationBody: + properties: + username: {type: string} + password: {type: string} + host: {type: string} + protocol: {type: string} +``` + +No OTP, no app-password, no token exchange. If the account has two-factor authentication enabled, this API will return `401` forever, with the correct password, on every host. The only workable arrangement is a dedicated service account with 2FA off, scoped to the folders it needs — which is better practice anyway, and is what I should have started with instead of testing against my own admin account first. + +## The permissions trap, after you're in + +Authentication is not authorization. Once my service account could log in, every call against the spreadsheet I actually cared about returned: + +```json +{"statusCode":403,"code":"403","error":"Forbidden","message":"Permission denied"} +``` + +Read that carefully, because it is informative: `403 Permission denied` means **the file exists and you may not have it.** A bad ID returns something different: + +```json +{"statusCode":404,"code":"404","error":"Not Found","message":"Spreadsheet not found"} +``` + +Two different failures, two different fixes, and conflating them costs an hour. Mine was a location problem: the spreadsheet had been created in Synology Drive's personal **My Drive**, which on disk is `/volume1/homes//Drive/Document/…`. A personal home directory is not reachable by another DSM account — not by permission settings, not by shared-folder tricks, because it isn't in a shared folder at all. The fix is to move the file into a shared folder and grant Read/Write there, or to Drive-share the specific file to the service account with edit rights. + +## The fix: the whole working setup + +The container, configured with a real secret and a memory cap: ```yaml services: - mem0-postgres: - image: pgvector/pgvector:pg17 + spreadsheet-api: + image: synology/spreadsheet-api:3.4.1 + container_name: spreadsheet-api + restart: always environment: - POSTGRES_USER: mem0 - POSTGRES_PASSWORD: ${MEM0_DB_PASSWORD} - POSTGRES_DB: mem0 - volumes: - - ./data/pg:/var/lib/postgresql/data - restart: unless-stopped - - mem0-litellm: - image: ghcr.io/berriai/litellm:main-stable - command: ["--config", "/app/config.yaml"] - volumes: - - ./litellm-config.yaml:/app/config.yaml - restart: unless-stopped - - mem0-api: - build: ./mem0-api - environment: - OPENAI_API_KEY: ${OPENAI_API_KEY} - OPENAI_API_BASE: http://mem0-litellm:4000/v1 # go through the gateway - MEM0_API_KEY: ${MEM0_API_KEY} # X-Api-Key for /search & /memories - POSTGRES_URL: postgresql://mem0:${MEM0_DB_PASSWORD}@mem0-postgres/mem0 + AUTH_SECRET: "" + PORT: "3000" + HOST: "0.0.0.0" ports: - - "20015:8000" - restart: unless-stopped + - "8791:3000" + mem_limit: 2g ``` -(Mine is built from the mem0 repo with the model/fact-extraction directed -through LiteLLM; the exact image tag is me maintaining a local build, and I -keep the real API key out of the compose file — it's an env secret.) +One DSM-specific note: omit `cpus:` from any compose file on DSM. Its kernel has no CPU CFS scheduler, so the key is silently ignored — you get the illusion of a CPU limit and no limit. -## Using it - -Once it's up, the API is refreshingly small. Add a fact (fast, verbatim): +Then the API works, and the shape is pleasant. Sign in, create or address a spreadsheet, read and write ranges: ```bash -curl -X POST http://192.168.1.1:20015/memories \ - -H "Content-Type: application/json" \ - -H "X-Api-Key: $MEM0_API_KEY" \ - -d '{ - "user_id": "customer-2211", - "text": "Customer 2211 prefers email over WhatsApp for order updates." - }' +TOKEN=$(curl -s -X POST http://192.168.1.1:8791/spreadsheets/authorize \ + -H 'Content-Type: application/json' \ + -d '{"username":"","password":"","host":"cloud.example.com","protocol":"https"}' \ + | python -c "import json,sys; print(json.load(sys.stdin)['token'])") + +# read a range (sheet-qualified A1 notation) +curl -s -H "Authorization: Bearer $TOKEN" \ + "http://192.168.1.1:8791/spreadsheets//values/Sheet1!A1:C4" + +# write a range, formulas included +curl -s -X PUT -H "Authorization: Bearer $TOKEN" -H 'Content-Type: application/json' \ + -d '{"values": [["Item","Qty"],["Widget",12],["Gadget",7],["Total","=SUM(B2:B3)"]]}' \ + "http://192.168.1.1:8791/spreadsheets//values/Sheet1!A1:B4" ``` -Retrieve the most relevant memories later: +Two details I did not expect, both in my favour: + +- **The spreadsheet ID comes from the Office URL.** A spreadsheet at `…/oo/r/` — including one behind a share link, which redirects into exactly that path — is addressable by putting that segment in the API call. +- **Office computes the formulas, not you.** Exporting a sheet as CSV returned the *evaluated* results of `=SUM(B2:B3)` and `=SUMPRODUCT(B2:B3,C2:C3)` — formulas I never evaluated client-side. That's the whole reason to use this API instead of parsing a file yourself: you inherit Synology's own calculation engine. + +There is one real gap worth stating: **there is no list endpoint.** The spec declares a "Statistics" tag but serves no route for it (`/statistics` → `404 Route not found`), and nothing else enumerates spreadsheets. You must already know the ID from the document's URL. Fine for automation you set up on purpose; useless if you wanted to browse. + +## Getting a chart out the other end + +Reading cells was half the job; the original ask included charts. The same API can hand you a real workbook: ```bash -curl -X POST http://192.168.1.1:20015/memories/search \ - -H "Content-Type: application/json" \ - -H "X-Api-Key: $MEM0_API_KEY" \ - -d '{ - "user_id": "customer-2211", - "query": "how should I reach this customer?", - "limit": 5 - }' +curl -s -H "Authorization: Bearer $TOKEN" \ + "http://192.168.1.1:8791/spreadsheets//xlsx" -o export.xlsx ``` -Then inject the returned facts into the agent's system prompt (or context) -before it answers. That's the whole loop: **store facts, retrieve what's -relevant, use it in the next reply.** +That returns a valid `.xlsx` — `PK` magic, opens in anything. From there my own service (a small FastAPI container with LibreOffice inside it for formula evaluation and matplotlib for rendering) reads the ranges and produces PNG charts and dashboards, so the pipeline runs end to end without Excel and without any cloud dependency: -### The `infer` gotcha that cost me a day - -- `POST /memories` with the **default `infer=true`** runs the LLM fact - extractor — it classifies and cleans each memory. That's smart but **slow**, - and every call costs a model round-trip. -- If I just want the agent to note something verbatim and fast (user said - "please call me Andy"), I pass **`infer=false`** — no LLM hop, near-instant - storage. - -The route of my stack is `/search` and `/memories` **without a `/v1` prefix** -(an early wrapper that assumed `/v1` 404'd for a while), and auth is a plain -`X-Api-Key` header. Small details, but they cost me time to discover. +``` +Synology Office → spreadsheet-api → .xlsx export → chart renderer → PNG +``` ## What I'd do differently -- **Set `infer=false` for routine logging from day one.** Only run the LLM - extractor on the facts that matter; the default inference mode makes every - write pricey for no benefit on throwaway notes. -- **Treat the API key as a real secret.** It gets embedded in agent configs - and compose envs, so I keep it out of the compose file and inject it via - environment secrets. -- **Put the DB on a disk I trust.** Mem0 is only as durable as its Postgres. - I run it on my NAS's protected volumes, with a backup job — because a - memory layer that forgets is worse than none. +1. **Check Docker Hub before concluding a Synology feature doesn't exist.** I burned real time proving a negative from an API list that could not have contained the answer. `synology/*` on Docker Hub was one search away. +2. **Start with a dedicated, non-2FA service account** scoped to one shared folder. I tested with an admin account first, which is how I met the 2FA wall and the `403` wall in the same hour. +3. **When a diagnostic says "nothing is running", check its privileges.** `ps` without root on DSM is not a process list, it's a list of your own processes, and it will happily let you conclude the machine is dead. +4. **Read the container, not just its docs.** The vendor's own run command is on the image page, but the exact defaults (`PORT` 3000, worker timeout 600 s) and the required `AUTH_SECRET` came from grepping the bundle — one command, no guessing. ## The result -A private, self-hosted memory layer answered by two small HTTP calls. My -agent now remembers customers, preferences, and decisions across sessions — -and because the stack sits in my own PostgreSQL behind my own network, none -of that leaves my control. - -If you run AI agents that keep forgetting their context, self-hosting mem0 -is one of the highest-value, lowest-friction upgrades you can make — and you -can do it without sending your memory to someone else's database. +Verified end to end on the NAS: sign-in, create, cell write, cell read-back, CSV export and `.xlsx` export all returned `200`, and the CSV export proved the Office engine evaluated `=SUM`/`=SUMPRODUCT` server-side. The exported workbook fed a chart service that rendered the same data to PNG. Four traps documented, one wrong conclusion corrected, roughly a day of work — and a spreadsheet on my own hardware that a script can now drive. --- -## Want a memory-enabled AI setup for your business? - -I build and self-host AI agents, memory stacks, websites, and infrastructure -for businesses. If you'd like your assistant to actually *remember* your -customers — or you want to talk about hiring me — I'd love to help: - -- 📱 **WhatsApp:** [+60 12-797 2969](https://wa.me/60127972969) -- 📧 **Email:** [me@hoelee.com](mailto:me@hoelee.com) -- 🌐 **Website:** [hoelee.com](https://hoelee.com) +*I build self-hosted integrations like this for small businesses in Malaysia — spreadsheet and NAS automation, dashboards, and internal tools that keep your data on your own hardware. If that's the kind of thing you need, [WhatsApp me](https://wa.me/60127972969) or [email me](mailto:me@hoelee.com?subject=Self-hosted%20spreadsheet%20automation) — or see what else I do at [hoelee.com](https://hoelee.com).* ```` --- -## 文章 09 / 10:把 AI 修图工具做成 WordPress 插件:22 个版本换来的经验 -- **Slug**: `shipping-an-ai-photo-editor-as-a-wordpress-plugin` -- **英文标题**: Shipping an AI Photo Editor as a WordPress Plugin: 22 Versions of Hard Lessons -- **分类**: `case-studies` | **发布日期**: 2026-09-18 -- **线上地址**: https://blog.hoelee.com/posts/shipping-an-ai-photo-editor-as-a-wordpress-plugin/ (EN) | https://blog.hoelee.com/posts/zh/shipping-an-ai-photo-editor-as-a-wordpress-plugin/ (ZH) +## 文章 03 / 11:我差点把这颗 SSD 送修——真正坏的是 SATA 数据线 +- **Slug**: `that-dying-ssd-was-just-a-bad-sata-cable` +- **英文标题**: I Was About to RMA This SSD — the Fault Was a SATA Cable +- **分类**: `devops` | **发布日期**: 2026-09-16 +- **线上地址**: https://blog.hoelee.com/posts/that-dying-ssd-was-just-a-bad-sata-cable/ (EN) | https://blog.hoelee.com/posts/zh/that-dying-ssd-was-just-a-bad-sata-cable/ (ZH) - **本篇审核状态**: ⏳ 待审核 (Pending) ### ✍️ 顾问审阅意见区 (Review Feedback) @@ -3221,883 +886,3460 @@ customers — or you want to talk about hiring me — I'd love to help: ### 🇨🇳 中文版原文 (Chinese Markdown Twin) ````markdown --- -title: "把 AI 修图工具做成 WordPress 插件:22 个版本换来的经验" -description: "从单个 HTML 文件到一个真正上线的 WordPress 插件:fal.ai 异步队列、绝不能静默失败的水印、可选的名单元件,以及五个只有在真实环境里才会出现的 bug。" -pubDate: 2026-09-18 -category: case-studies -blueprint: sme-digital-suite -blueprintLayer: L1-high-conversion-web -tags: [wordpress, php, fal-ai, docker, ai-image, javascript] -ogImage: /og/zh-shipping-an-ai-photo-editor-as-a-wordpress-plugin.jpg -banner: /banners/shipping-an-ai-photo-editor-as-a-wordpress-plugin.jpg +title: "我差点把这颗 SSD 送修——真正坏的是 SATA 数据线" +description: "一颗 Seagate IronWolf 110 SSD 疯狂报 WRITE FPDMA 超时、mkfs 报 'superblock magic doesn't match'、然后读写静默——教科书般的坏盘。我只换了一根 SATA 线,它就干净格式化、零报错。动手判死刑前,先这样排查。" +pubDate: 2026-09-16 +category: devops +blueprint: self-hosted-infrastructure +blueprintLayer: L1-compute-storage-network +tags: [unraid, sata, ssd, storage, troubleshooting, smart, fio, cable] draft: false +ogImage: /og/zh-that-dying-ssd-was-just-a-bad-sata-cable.jpg +banner: /banners/that-dying-ssd-was-just-a-bad-sata-cable.jpg --- -几周前我[写过那个概念验证](/posts/zh/ai-furniture-compositing-with-flux-kontext/):一个 -`index.html`、没有后端,两张家具照片进去,一张布置好的房间场景出来。它回答了 -它本该回答的问题——*能不能保住真实的产品,只把周围的房间生成出来?*——同时留下 -了一个显而易见的问题。 +所有存储指南都告诉你:先看 SMART,再信事件日志。我也照做了,两者都指向同一个结论:这颗 SSD 要死了。而我距离把一颗健康硬盘送去 RMA 只差一步。 -那篇 PoC 的结尾写着「*在决定做成完整的 WordPress 插件之前*」。这篇文章讲的就是 -那个插件。它从 `0.0.1` 走到 `0.0.22`,58 个 commit,而其中几乎没有任何工作是 AI 那部分。 +2026 年 9 月,一颗 Seagate IronWolf 110 960 GB SATA SSD——SMART 全绿、寿命约 99%、重映射扇区为零——反复在 btrfs `mkfs` 时失败,后来干脆连读都不回。内核日志里堆满了 `WRITE FPDMA QUEUED` 超时、`NCQ disabled due to excessive errors`、`lost async page write`。最后一次 `mkfs` 打印出 superblock 后,回读失败了。 -## 为什么这件事值得关心(写给老板,不是写给开发者) - -PoC 的局限在于它活在一个 HTML 文件里,API key 就写在源码里。作为发给客户看的演示, -这没问题。但一家家具店要把这东西放到自己网站上,就不行了: - -- **API key 不能出现在浏览器里。** 任何人 view-source 就能看到,然后把你的 fal.ai - 额度刷光。它必须放在服务端,由一个管理员控制的设置页面来管。 -- **没人想盯着生成过程。** 访客上传、等待、拿到图。如果中途挂了,店主根本不该知道。 -- **顾客的照片不能泄露。** 匿名访客的原图绝不能进公开的媒体库;生成结果除非 - *那位访客本人*同意分享,否则也不能公开。 -- **输出必须带水印。** 否则你就是在给整个互联网提供免费 AI 修图服务。 -- **店主需要拿到线索。** 一个只会产出一张漂亮图片、拿不到联系方式的 AI 工具是个玩具。 - 接上表单和 webhook,它就是家具生意的线索管道。 - -上面这五条都是**产品**需求,而每一条都比那次 AI 调用本身花的代码更多。 - -## 架构:真正让它跑起来的无聊部分 - -这是一个正常的 WordPress 插件——PHP 前缀 `hre_`、命名空间 `HRE`、激活时用 -`dbDelta()` 建自定义表、自带 autoloader、运行时不依赖 Composer。有意思的决策在别处。 - -### 生成永远是异步的 - -fal.ai 的任务要 15–20 秒。PHP-FPM 的请求超时、`max_execution_time`、以及没耐心的 -访客,让同步生成注定失败。所以流程是「入队 + 轮询」: - -``` -访客上传 → POST /uploads → 归一化 → 启动视觉分析 -访客选择 → GET /prompts/{cat} → 每个风格的提示词 -访客确认 → POST /jobs → fal 入队(返回 uuid) -浏览器轮询 → GET /jobs/{uuid} → status: queued | processing | done -``` - -访客永远不等服务商。任务行携带 fal 的请求 id,轮询要么拿到完成的结果,要么显示 -真实的进度。前端是跑在 session cookie 上的小型状态机,所以中途刷新页面会回到 -访客原来所在的位置。 - -### 归属权靠 session cookie,不靠 URL 里的 ID - -匿名访客没有账号,这让授权很容易做错。我最终定下的规则是: -**每一次读取都通过调用者自己的 session hash 来解析**,绝不接受客户端传来的 ID。 - -- `GET /preview` 只输出调用者**自己**归一化后的上传图。它根本没有路径或 URL 参数 - ——别人请求它只会得到 404,因为那个 session 里没有文件。这也让私有存储路径 - 不会出现在任何 JSON 响应里。 -- `GET /jobs/{uuid}` 是按 *session hash + uuid* 查任务的。从别的浏览器猜一个 UUID - 什么也拿不到。 - -就这一个决策,消掉了「我改了 URL 里的 id 就看到了别人的照片」这一整类 bug。 - -### 水印是硬需求,所以回退逻辑绝不能静默 - -这个 bug 教给我的最多。水印那一步做的是 GD `imagecopyresampled` 合成。如果它失败, -一个很诱人的「有韧性」的写法是: - -```php -// 别这么写 -if ( ! $watermarked ) { - rename( $stage, $final ); // 直接把没水印的文件发出去 -} -``` - -我当初就是这么写的。它完全静默、没有日志,插件会心安理得地输出没有水印的结果, -而后台还显示「水印:已开启」。店主几周后才发现,是因为看到了一张没水印的图。 - -修法分三部分: - -1. **记录根因,而不是最近的那个症状。** `apply()` 返回的是 - `hre_no_watermark_source`——一个下游错误。真正的原因是水印来源的解析链 - (`site_logo` → `get_theme_mod('custom_logo')`)根本没解析到 logo。我加了一个 - `block_reason()` 诊断,重新走一遍解析链,并针对每个失败分支返回**具体**信息。 -2. **在后台暴露出来。** 一条常驻的 `notice-warning` 提示:水印已开启但不会被应用, - 并附上具体原因。不需要去翻日志。 -3. **让失败在测试时就看得见。** 一个独立探针把已知水印合成到已知底图上,并采样 - 预期水印矩形内的一个像素——这证明了变换路径本身是好的,从而把「功能坏了」和 - 「功能没配好」区分开。 - -**我现在遵守的规则:** 当某个「尽力而为」的分支掩盖了一个不可协商的变换时,它必须 -记录具体原因**并且**在后台 UI 里告警。一个悄悄让必需功能降级的回退不是韧性——那是 -一个有礼貌的 bug。 - -### 名单元件:默认关闭,开启后异步 - -名单元件是一个总开关。关闭时插件什么都不收集,向导的行为和以前完全一样。开启时, -管理员配置的字段会在生成之前变成必填,存入自定义表,并转发到 webhook。 - -两个值得照抄的决策: - -- **字段列表由管理员定义、完全动态**——`{key, label, type, required, placeholder, - options[]}`——所以前端表单是照着配置把自己渲染出来的。默认的五项(姓名、电话、 - 邮箱、留言、同意)只是起点,店主可以整个替换。 -- **Webhook 投递是排程的,绝不内联执行。** 访客不该为别人的接口等待: - -```php -wp_schedule_single_event( time() + 5, 'hre_lead_webhook', array( $lead_id ) ); -``` - -投递失败后按线性退避重试三次,然后标记为 `failed`。后台列表会显示状态徽章 -(pending / retrying / delivered / failed)和尝试次数——这一点很重要——插件的数据 -保留规则会保留**已投递**的线索,但按正常周期清理未投递的,因为一条没送出去的线索 -只是躺在你数据库里的个人隐私数据。 - -### 服务商的急停开关必须在服务端强制执行 - -管理员可以停用图像服务商,并设置一段代替「生成」按钮显示给访客的文案。把复选框 -变灰只是 UX;真正的强制发生在创建任务接口的开头: - -```php -if ( ! (bool) Settings::get( 'fal_provided' ) ) { - return $this->error_response( 'hre_provider_disabled', $msg, 503 ); -} -``` - -名单元件那道闸同理。浏览器端的闸是 UX,服务端的闸才是产品。 - -## 只有在真实安装里才会冒出来的五个 bug - -这是所有「怎么做 AI 插件」的文章都不会写的一段,而 58 个 commit 里大部分都花在这。 - -### 1. 把后台 REST 路由注册在 `is_admin()` 里,会静默 404 - -只在 `is_admin()` 为真时注册后台路由,看起来是对的,实际上完全坏了: -**REST 请求里 `is_admin() === false`**,所以路由从未被注册,每次调用都返回 -`404 "No route was found matching the URL and request method"`——这读起来就像是 -URL 打错了,完全不像注册 bug。要在插件启动时就注册;真正的访问控制是 -`permission_callback`(权限 + nonce)。 - -### 2. `rest_url()` 结尾没有斜杠 - -最近耗掉我一个下午的就是这个。`rest_url()` 返回的是 -`https://example.com/wp-json/my-plugin/v1/`——结尾的斜杠属于**命名空间**,下一段 -路径必须自己带一个斜杠。不带的话: - -```js -const rest = window.hreAdmin.rest; // ".../wp-json/hoelee-ai-photo-remix/v1" -fetch( rest + 'admin/photos/' + id ) // ❌ ".../v1admin/photos/123" -fetch( rest + '/admin/photos/' + id ) // ✅ -``` - -`.../v1admin/photos/123` 是一个 404,而且浏览器控制台里没有任何报错,于是 `catch` -分支触发,界面弹出笼统的「*Something went wrong.*」。它已经悄悄弄坏了**四个**接口 -——照片分页、照片删除、webhook 测试按钮、线索重发。修法是在每个调用点加一个字符; -诊断却花了长得多的时间,因为这个失败模式和服务器出错完全无法区分。用两条 curl 就能 -证明:正确的拼接返回 `403`(路由存在、缺 nonce),坏的那个返回 `404`。 - -### 3. 一个后台设置表单能抹掉另一个标签页的设置 - -每个后台标签页只提交自己的字段,但保存处理函数会跑完**整个**设置表。一个没被提交 -的复选框,和一个被取消勾选的复选框长得一模一样,所以保存「限制」页会静默地把 -「默认允许分享」写成 `false`,而保存那一页又会把整个名单元件配置清空。修法在 -清洗器里,不在表单里——要区分「这次提交里没有这个键」和「有这个键但是空值」: - -```php -// 本页提交了 → 用新值(清空就是清空) -// 本页没有提交 → 保留当前值 -if ( array_key_exists( $key, $raw ) ) { - $clean[ $key ] = sanitize( $raw[ $key ] ); -} -``` - -我为这件事补了一个回归测试(写入配置 → 保存另一个标签页的子集 → 断言原配置还在)。 -这类 bug 只有在你有了两个标签页之后才会存在,所以它才会被发出去。 - -### 4. 二进制接口不能走 JSON 解析的 fetch 助手 - -结果下载是一个 JPEG 流。共用的 `api()` 助手对每个响都做 `res.json()`,碰到图片字节 -就抛异常——而一个吞异常的 `.catch(function(){})` 把错误吃掉了,于是症状是 -*「结果一直不出现」*,控制台里什么都没有。二进制接口需要自己的原始 fetch 助手: -检查 `res.ok`、只在出错时解析 JSON、成功时返回 `res.blob()`。 - -### 5. 在缩放之前触发的尺寸上限,等于废掉了缩放 - -插件会把上传图缩到工作尺寸(1920×1080 边界)。我把防解压炸弹的限制设得太低—— -1 MB / 1 MP——结果每一张正常的手机照片都在**被缩放之前**就被拒了。访客看到预览刚 -出现就立刻取消选中,被反馈成「缩放功能坏了」。 - -真正的教训是 UX,不是数字:客户端必须在**显示本地预览之前**就拒掉超限文件。 -一闪就没,读起来就是 bug,哪怕底下那句提示其实是对的。现在上限是 15 MB / 50 MP, -高到正常照片一定能通过并被归一化。 - -## 如果重来一次我会怎么做 - -- **产品依赖的东西,先写失败路径。** 水印那个 bug 之所以存在,是因为我写了成功路径, - 然后把失败路径藏了起来。现在我先把「这条线断了,店主会看到什么」写完,再宣告 - 功能完成。 -- **第一天就拿真实站点测 REST 拼接。** 两条 curl(`.../v1/admin/x` → 403 对比 - `.../v1admin/x` → 404)本来能在第一周就抓出四个坏接口,而不是拖到第四周。我已经 - 把它写进项目的 `AGENTS.md`,让它不会再犯。 -- **别去猜服务商的 API 形状。** 我在 `fal.ai/api/me`(根本不存在的接口)上浪费了 - 时间,之后才发现正确的 key 校验是往队列接口发一个带鉴权的 `POST {}`:`401` 表示 - 被拒,其他都说明 key 没问题。先读真实 schema,再写客户端。 -- **前端就保持两个 shortcode。** 我曾经很想把向导拆成五个 shortcode 和五个页面构建器 - 组件。保持成「一个应用 + 一个画廊」意味着每次 UI 迭代都是单文件改动,而正是这个 - 迭代速度让 22 个版本得以发出去。 - -## 结果 - -一个具备产品形态的 WordPress 插件:**`0.0.22`,共 22 次发布**,10 张自定义数据表、 -异步 fal.ai 队列、服务端密钥管理、带重试 webhook 的动态名单元件、区分分享状态的 -照片归档,以及一个 10 个标签页、不用碰代码就能改完所有配置的后台。 - -这就是演示和产品之间的区别。而我最在意的那个数字是:**58 个 commit 里,大概只有四个 -和 AI 模型有关。** 其余全是那些不体面的工作,却决定了客户能不能在没有我的情况下 -把这东西跑起来:校验、数据保留、权限、失败的可见性,以及一个说真话的后台页面。 - ---- - -## 想给你的生意也做一套? - -我为马来西亚的中小企业做 WordPress 插件、AI 图像流水线和自托管基础设施——而且是 -做成你真的能跑起来的产品,不是要你天天伺候的演示。如果你想要 AI 产品图、一套线索 -收集管道,或者为你的业务定制插件,欢迎直接找我: - -- 📱 **WhatsApp:** [+60 12-797 2969](https://wa.me/60127972969) -- 📧 **邮箱:** [me@hoelee.com](mailto:me@hoelee.com?subject=WordPress%20AI%20plugin%20project) -- 🌐 **网站:** [hoelee.com](https://hoelee.com) -```` - -### 🇬🇧 英文版原文 (English Markdown Primary) -````markdown ---- -title: "Shipping an AI Photo Editor as a WordPress Plugin: 22 Versions of Hard Lessons" -description: "From a single HTML file to a shipped WordPress plugin: the fal.ai async queue, a watermark that must never silently fail, optional lead capture, and five bugs that only appeared in production." -pubDate: 2026-09-18 -category: case-studies -blueprint: sme-digital-suite -blueprintLayer: L1-high-conversion-web -tags: [wordpress, php, fal-ai, docker, ai-image, javascript] -ogImage: /og/shipping-an-ai-photo-editor-as-a-wordpress-plugin.jpg -banner: /banners/shipping-an-ai-photo-editor-as-a-wordpress-plugin.jpg -draft: false ---- - -A few weeks ago I [wrote about the proof of concept](/posts/ai-furniture-compositing-with-flux-kontext/): one -`index.html`, no backend, two furniture photos in, a staged room scene out. It -answered the question it was built to answer — *can you keep the real product and -only generate the room around it?* — and it left one obvious question open. - -That PoC ended with the words *"before committing to the full WordPress plugin."* -This post is about the plugin. It went from version `0.0.1` to `0.0.22` across 58 -commits, and almost none of that work was the AI part. - -## Why it matters (for a business owner, not a developer) - -The PoC's limitation was that it lived in a single HTML file with the API key in -the source. That's fine for a demo you email a client. It is not fine for -something a furniture shop puts on their own website, where: - -- **The API key cannot be in the browser.** Anyone can view-source and drain your - fal.ai credit. It has to live server-side, behind a settings screen an admin - controls. -- **Nobody wants to babysit a generation.** The visitor uploads, waits, gets a - picture. If the process dies halfway, the shop owner should never hear about it. -- **Photos of customers must not leak.** An anonymous visitor's source photo must - never end up in the public Media Library, and a result must never be public - unless *that visitor* opted in to sharing it. -- **Output needs a watermark.** Otherwise you're running a free AI photo service - for the entire internet. -- **The owner needs to capture the lead.** An AI tool that produces a pretty - picture and no contact details is a toy. Attached to a form + webhook, it's a - lead pipeline for a furniture business. - -Every one of those five points is a *product* requirement, and every one of them -cost more code than the AI call itself. - -## Architecture: the boring parts that make it work - -The plugin is a normal WordPress plugin — PHP prefix `hre_`, namespace `HRE`, -custom tables created with `dbDelta()` on activation, an autoloader, no Composer -runtime dependency. The interesting decisions are elsewhere. - -### Generation is asynchronous, always - -fal.ai jobs take 15–20 seconds. PHP-FPM request timeouts, `max_execution_time`, -and impatient visitors make synchronous generation a losing bet. So the flow is a -queue-and-poll: - -``` -visitor uploads → POST /uploads → normalize → start vision analysis -visitor picks → GET /prompts/{cat} → per-style prompts -visitor confirms → POST /jobs → fal queue submit (returns uuid) -browser polls → GET /jobs/{uuid} → status: queued | processing | done -``` - -The visitor never waits on a provider. The job row carries the fal request id, and -a poll either finds a finished result or shows genuine progress. The front end is -a small state machine over a session cookie, so a mid-wizard refresh restores -where the visitor was. - -### Ownership is the session cookie, not an ID in the URL - -Anonymous visitors have no accounts, which makes authorization easy to get wrong. -The rule I settled on: **every read resolves through the caller's own session -hash**, never through an ID accepted from the client. - -- `GET /preview` streams the caller's *own* normalized upload. There is no path or - URL parameter at all — a stranger requesting it gets a 404 because their session - has no file. This also keeps private storage paths out of every JSON payload. -- `GET /jobs/{uuid}` looks the job up *by session hash + uuid*. Guessing a UUID - from another browser returns nothing. - -That's one decision that removes an entire class of "I changed the id in the URL -and saw someone else's photo" bugs. - -### The watermark is a hard requirement, so a fallback must never be silent - -This is the bug that taught me the most. The watermark step does a GD -`imagecopyresampled` composite. If it ever fails, the tempting "resilient" move is: - -```php -// DON'T do this -if ( ! $watermarked ) { - rename( $stage, $final ); // ship the un-watermarked file -} -``` - -I did exactly that. It's silent, it has no log line, and it means the plugin -happily serves un-watermarked results while the admin screen says "watermark: on." -The owner found out weeks later by noticing a photo without a watermark. - -The fix was three parts: - -1. **Log the root cause, not the nearest symptom.** `apply()` returned - `hre_no_watermark_source` — a downstream error. The real cause was that the - watermark source resolution chain (`site_logo` → `get_theme_mod('custom_logo')`) - had no logo to resolve. I added a `block_reason()` diagnostic that re-walks the - chain and returns a *specific* message per failure branch. -2. **Surface it in the admin.** A persistent `notice-warning` says the watermark - is enabled but won't be applied, plus the concrete reason. No log-reading - required. -3. **Make the failure visible to me in testing.** A standalone probe composites a - known watermark onto a known base and samples a pixel inside the expected - watermark rectangle — proving the transform path itself works, which separates - "the feature is broken" from "the feature is unconfigured." - -**Rule I now follow:** when a best-effort branch masks a non-negotiable transform, -it must log the concrete reason *and* warn in the admin UI. A silent fallback that -degrades a required feature is not resilience — it's a bug with good manners. - -### Lead capture: off by default, asynchronous when on - -Lead capture is a master toggle. Off, the plugin collects nothing and the wizard -behaves exactly as before. On, the visitor's configured fields are required before -generation, stored in a custom table, and forwarded to a webhook. - -Two decisions worth copying: - -- **The field list is admin-defined and fully dynamic** — `{key, label, type, - required, placeholder, options[]}` — so the front form renders itself from - config. The defaults (name, phone, email, message, consent) are just a starting - point the owner can replace entirely. -- **Webhook delivery is scheduled, never inline.** The visitor must not wait on - someone else's endpoint: - -```php -wp_schedule_single_event( time() + 5, 'hre_lead_webhook', array( $lead_id ) ); -``` - -Delivery retries three times with linear backoff, then marks the record `failed`. -The admin list shows a status badge (pending / retrying / delivered / failed) plus -the attempt count, and — this matters — the plugin's data retention rule keeps -*delivered* leads but purges undelivered ones on the normal schedule, because an -undelivered lead is just PII sitting in your database. - -### The provider kill switch has to be enforced server-side - -The admin can disable the image provider and set a message that visitors see -instead of the generate button. Greying out the checkbox is UX; the enforcement is -a check at the top of the job-creation endpoint: - -```php -if ( ! (bool) Settings::get( 'fal_provided' ) ) { - return $this->error_response( 'hre_provider_disabled', $msg, 503 ); -} -``` - -Same for the lead gate. The browser gate is UX. The server gate is the product. - -## The five bugs that only showed up in the real install - -This is the part no article about "building an AI plugin" ever includes, and it's -where most of the 58 commits went. - -### 1. Admin REST routes registered inside `is_admin()` silently 404 - -Registering admin routes only when `is_admin()` is true looks correct and is -completely broken: **REST requests report `is_admin() === false`**, so the routes -are never registered and every call returns `404 "No route was found matching the -URL and request method"` — which reads exactly like a URL typo, not a registration -bug. Register at plugin boot; the `permission_callback` (capability + nonce) is -what gates access. - -### 2. `rest_url()` has no trailing slash - -The one that cost me the most recent afternoon. `rest_url()` returns -`https://example.com/wp-json/my-plugin/v1/` — the trailing slash is on the -*namespace*, and the next path segment must start with its own slash. Concatenating -without one: - -```js -const rest = window.hreAdmin.rest; // ".../wp-json/hoelee-ai-photo-remix/v1" -fetch( rest + 'admin/photos/' + id ) // ❌ ".../v1admin/photos/123" -fetch( rest + '/admin/photos/' + id ) // ✅ -``` - -`.../v1admin/photos/123` is a 404 with no browser console error, so the -`catch` block fires and the UI shows the generic *"Something went wrong."* It had -quietly broken **four** endpoints — photo pagination, photo delete, the webhook -test button, and lead resend. The fix is one character per call site; the -diagnosis took far longer, because the failure mode is indistinguishable from a -server error. Prove it with two curls: the correct join returns `403` (route -exists, nonce missing), the broken one returns `404`. - -### 3. A WordPress admin settings form can wipe a different tab's settings - -Each admin tab posts only its own fields, but the save handler runs the *whole* -settings map. A checkbox that isn't submitted looks identical to a checkbox that -was unchecked, so saving the "limits" tab silently wrote `false` over the -"share by default" option, and saving that one cleared the entire lead-capture -configuration. The fix belongs in the sanitizer, not the forms — distinguish -"absent from this submission" from "present and empty": - -```php -// present in this tab → use the new value (a cleared field clears) -// absent from this tab → keep the current value -if ( array_key_exists( $key, $raw ) ) { - $clean[ $key ] = sanitize( $raw[ $key ] ); -} -``` - -I added a regression test for exactly this (seed config → save a different tab's -subset → assert the seed survived). It's the kind of bug that only exists once you -have two tabs, which is why it shipped. - -### 4. A binary endpoint must not go through a JSON fetch helper - -The result download is a JPEG stream. The shared `api()` helper did `res.json()` -on every response, which threw on image bytes — and a swallowing -`.catch(function(){})` ate the error, so the symptom was *"the result never shows -up"* with nothing in the console. Blob endpoints need their own raw fetch helper -that checks `res.ok`, parses JSON only on error, and returns `res.blob()` on -success. - -### 5. A size limit that fires before the resize defeats the resize - -The plugin downscales uploads to a working size (1920×1080 bounds). I had set the -decompression-bomb guard too low — 1 MB / 1 MP — which meant every legitimate -phone photo was rejected *before* it could be resized. Visitors saw the preview -appear and instantly de-select, reported as "the resize feature is broken." - -The real lesson is UX, not numbers: the client must reject an over-limit file -*before* showing the local preview. Flash-then-disappear reads as a bug even when -the message underneath is correct. The caps now sit at 15 MB / 50 MP, high enough -that normal photos always pass and get normalized. - -## What I'd do differently - -- **Write the failure path first for anything the product depends on.** The - watermark bug existed because I wrote the happy path and then hid the unhappy - one. Now I write the "what does the owner see when this breaks" branch before - the feature is finished. -- **Test REST joins against the live site on day one.** A two-curl check - (`.../v1/admin/x` → 403 vs `.../v1admin/x` → 404) would have caught four broken - endpoints in week one instead of week four. I've added it to the project's - `AGENTS.md` so it can't recur. -- **Don't guess at a provider's API surface.** I lost time on `fal.ai/api/me` - (which doesn't exist) before discovering the right key check is an authenticated - `POST {}` to the queue endpoint: `401` means rejected, anything else means the - key is fine. Read the real schema, then write the client. -- **Keep the front end to two shortcodes.** I was tempted to split the wizard into - five shortcodes and five page-builder widgets. Keeping it as one app + one - gallery shortcode meant every UI iteration was a single-file change, and that - iteration speed is the reason 22 versions shipped. - -## The result - -A production-shaped WordPress plugin: **`0.0.22` across 22 releases**, with 10 -custom database tables, an async fal.ai queue, server-side key handling, dynamic -lead capture with a retrying webhook, a role-aware photo archive, and everything -configurable from a 10-tab admin screen without touching code. - -It is the difference between a demo and a product, and — the number I actually -care about — **58 commits, of which roughly four were about the AI model.** The -rest was the unglamorous work that decides whether a client can run the thing -without me: validation, retention, permissions, failure visibility, and an admin -screen that tells the truth. - ---- - -## Want this for your business? - -I build WordPress plugins, AI image pipelines, and self-hosted infrastructure for -Malaysian SMEs — and I ship them as products you can actually run, not demos you -have to babysit. If you want AI product photography, a lead-capture pipeline, or -a custom plugin for your business, I'd love to talk: - -- 📱 **WhatsApp:** [+60 12-797 2969](https://wa.me/60127972969) -- 📧 **Email:** [me@hoelee.com](mailto:me@hoelee.com?subject=WordPress%20AI%20plugin%20project) -- 🌐 **Website:** [hoelee.com](https://hoelee.com) -```` - ---- - -## 文章 10 / 10:在多台机器之间同步一个会自我学习的 AI Agent -- **Slug**: `syncing-a-self-improving-ai-agent-across-machines` -- **英文标题**: Syncing a Self-Improving AI Agent Across Machines -- **分类**: `case-studies` | **发布日期**: 2026-02-18 -- **线上地址**: https://blog.hoelee.com/posts/syncing-a-self-improving-ai-agent-across-machines/ (EN) | https://blog.hoelee.com/posts/zh/syncing-a-self-improving-ai-agent-across-machines/ (ZH) -- **本篇审核状态**: ⏳ 待审核 (Pending) - -### ✍️ 顾问审阅意见区 (Review Feedback) -```text -【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 -【事实与数字核对】: -【人设与用词卫生】: -【CRO与转化建议】: -``` - -### 🇨🇳 中文版原文 (Chinese Markdown Twin) -````markdown ---- -title: "在多台机器之间同步一个会自我学习的 AI Agent" -description: "如何用基于 git 的 profile distribution 在两台电脑之间同步 Hermes agent 的技能、配置和定时任务——以及为什么我选择手动同步而不是用 cron。" -pubDate: 2026-02-18 -updatedDate: 2026-09-11 -category: case-studies -blueprint: ai-agent-automation -blueprintLayer: L2-llm-gateway-agents -tags: [hermes, git, gitea, ai-agents, devops, sync] -ogImage: /og/zh-syncing-a-self-improving-ai-agent-across-machines.jpg -banner: /banners/syncing-a-self-improving-ai-agent-across-machines.jpg ---- - -我的 agent 会学习。每当我带它走一遍不平凡的工作流程——如何发布到 Gitea、如何排查一个时好时坏的 Docker 容器、如何写一条 Shopee 商品列表——它就会把过程存成一项 *skill*:一个下次遇到同类任务时自动加载的可复用流程。几个月下来,它累积了 172 项技能,横跨二十个分类。它们就是我的第二大脑。 - -问题在于:这个大脑只存在于一台机器上。当我换到另一台电脑工作时,agent 就变"笨"了——它不知道我在第一台机器上教过它什么。 - -这篇文章讲的是我如何让 agent 的知识跟着我在机器之间流动,为什么那个显而易见的做法会悄悄毁掉工作成果,以及最后发现最关键的那个决定。 +只有一件事救了这颗盘:在判它死刑之前,我换了根 SATA 数据线。 ## 为什么这很重要 -如果你在运行任何会自我学习的 agent——Hermes、Claude Code、Codex、Cursor——你都会遇到一模一样的问题。agent 在本地累积知识,但这些知识不会跟着你走。你要么在每台机器上重新教它一遍(毫无意义),要么让两份副本逐渐漂移、直到互相矛盾(更糟)。 +一根有问题的 SATA 口或线材,会产生**和坏盘一模一样的症状**,而且 SMART 全程保持漂亮。线材故障发生在链路层——传输出错超时,内存在你的文件系统或 SMART 看到任何错误字节之前,就把这次 I/O 丢了。只靠 SMART 判断,你会冤枉健康硬件、发起一趟无意义的 RMA,而换上的新盘在同一根线上照样坏。 -正确地解决它需要三件事,也正是任何工程师在同步*任意*状态时都关心的三件事: +## 那些"盘要死了"的症状 -- **一个共享的真相来源**——一份两台机器都能拉取的权威副本。 -- **不静默丢数据**——同步绝不能覆盖你在另一台机器上做过的工作。 -- **一个决策点**——当两台机器改动了同一处内容时,由*你*来做选择,而不是让工具替你决定。 +这是一颗独立的 Seagate IronWolf 110(ZA960NM10001,企业级 SATA SSD,约 894 GiB),我准备把它加进 Unraid 缓存池。三件事陆续发生,全都很像坏盘: -把这三件事做对,你的 agent 在两台机器上就是同一个人。做错了,你就得花一个周末去重建一个被错误的 `--force` 抹掉的技能。 +1. 内核日志每约 30 秒就循环一轮 libata 错误处理: + ``` + ata7.00: exception Emask 0x4 (timeout), WRITE FPDMA QUEUED, status { DRDY } + ata7.00: exception ... action 0x6 frozen + attribute NCQ disabled due to excessive errors + Buffer I/O error on dev sdd1 ... lost async page write + ``` + 硬盘无法完成排队的写入,内核硬重置链路;降级之后它**丢掉了真实数据**——`/dev/sdd` 有 28 个 LBA 报 lost async page write。 -## 三种官方机制 +2. `mkfs.btrfs -K -f /dev/sdd1` 打印出完整的文件系统头,然后校验失败: + ``` + Filesystem size: 894.25GiB + ERROR: superblock magic doesn't match + ``` + btrfs 写入了 superblock,回读时拿到的是**不一样的字节**。这是最可怕的静默写路径损坏。 -Hermes 提供了三种迁移 agent 的方式,它们回答的是不同的问题: +3. 之后 `smartctl -H /dev/sdd` **超时**。这颗盘连健康查询都不回应了。结合上面的写损坏内核标志,"送 RMA"是合理的结论。 -| 需求 | 机制 | 命令 | -|---|---|---| -| 只要技能 | Skills Hub "tap"(一个 `SKILL.md` 文件夹的 git 仓库) | `hermes skills tap add` + `install` | -| 整个 agent、带版本、可拉取更新 | **Profile distribution**(git 仓库 + `distribution.yaml`) | `hermes profile install` / `update` | -| 一次性迁移 / 备份 | 导出文件(`.tar.gz`) | `hermes profile export` / `import` | +## 改变结论的那个细节 -对于"同一 agent 在两台机器上",**profile distribution** 才是持久的答案。它把整个 agent——SOUL、配置、技能、定时任务——打包成一个 git 仓库,另一台机器用一条命令就能拉取更新。 +排查到一半我必须物理移动这颗盘——它被接到另一个 SATA 口、换了根线。我在动任何其他操作之前,重跑了**完全相同**的 `mkfs.btrfs` 命令。 -我所有东西本来就用 Gitea(git.hoelee.com),所以在那里放一个 distribution 仓库是顺理成章的。没有新工具、没有新账号,也符合我每个项目都遵循的"Gitea 优先"惯例。 +它通过了。零报错。`btrfs device stats` 全部清零。一次加了 `verify=crc32c`(写入带校验和的数据并**回读核对**)的 8 GiB `fio` 写入以 err=0 干净跑完,回读一致。`smartctl` 超时再也没有出现。`dmesg` 自那次换线以来对这颗盘**零**报错。 -## 我差点踩进去的坑 +除了链路,什么都没变。那些"静默写损坏",是 SATA 传输在线上损坏了帧,不是闪存的问题。 -distribution 安装器有一个安全特性,*听起来*像限制,却恰恰是救命的东西:**它拒绝安装到 `default` profile 里。** 你必须给它一个命名 profile。 +## 能抓到它 vs 抓不到它的测试 -这不是麻烦。第二台电脑本来就有自己的 agent 和项目相关的技能。如果我把它*覆盖*安装上去——或者用了会覆盖现有 profile 的 `--force`——我就会删掉那台机器本地的成果。`default` 拒绝机制就是那道护栏,逼着你在现有 agent *旁边*安装,然后再合并。 +这一趟得出两个教训: -而这正是整个练习真正的教训:**合并才是产品本身。** 同步不是"复制文件",而是调和两个都以为自己是真相来源的 agent。 +**普通的 `fio randrw` 对这个故障是瞎的。** 标准的 60 秒 `randrw`(70/30、4k、iodepth 32)写读随机扇区——但它从不*核对*读回来的字节是否和你写的一致。对一颗在线上损坏数据的盘,它会报 err=0、"干净通过"。我第一轮测试就是这样:*干净*,却在一颗随后 mkfs 失败的盘上。 -## 那个差点让我翻车的目录事实 - -这里是微妙的部分,也是那种"看起来没事、直到出事"的坑。 - -distribution 仓库里放的是技能树的**副本**——它不是*活跃目录*。活跃技能在 `~/AppData/Local/hermes/skills/`(agent 真正写入的地方);仓库副本只是我推送的一份快照。它们是两棵会漂移的、互相独立的树。 - -所以一次同步实际上涉及**三方**,而不是两方: +**你需要 `verify`,而且要点对区域。** fio 的 `verify=crc32c` 写入校验和并回读核对,这正是能揪出回读不一致的开关。而且故障是**局部**的:坏掉的 LBA(约 234,422,526–869,距设备起始约 111.8 GiB)落在我第一轮测试跑过位置再往后 100 GiB 处。在错误的偏移量上测试完全测不到。证据就是:指向健康区域的 verify 任务通过了;同一任务指向已知坏区间时,硬盘像先前缓存池故障时那样直接卡住。 ``` -活跃技能目录 ←→ 仓库副本(D:\dev\hoelee-agent-dist\skills) ←→ Gitea 远端 +# 判别性测试:写入带校验和,回读,不一致就失败 +# 要么跑全表面,要么跑 dmesg 标记的精确 LBA 区间 +fio --name=verify --filename=/dev/sdd \ + --offset=111G --size=2G \ + --rw=write --verify=crc32c --do_verify=1 \ + --bs=4k --ioengine=io_uring --direct=1 --iodepth=32 ``` -我在上次推送之后新建的一个技能,*只*存在于活跃目录里。如果我假设仓库副本是权威、并"从它开始同步",就会静默删掉那个技能。所以每次同步前我做的第一件事,就是比对两棵树: +同一任务跑在*健康*盘上,`verify` 会通过;链路坏的话,fio 会报校验和不符或卡死——远比普通的 randrw 更早暴露问题。 -```bash -diff -rq ~/AppData/Local/hermes/skills D:/dev/hoelee-agent-dist/skills -``` +## 我会改的做法 -漂移是*正常的*,不是错误。整套纪律在于搞清楚三方里谁领先,然后有意识地调和。 - -## 为什么我手动同步,而不是用 cron - -这是最关键的决定,而它归结为冲突策略。我想要双向同步——两台机器都会编辑技能——而当两边编辑了*同一个*技能时,我想**两边都保留、由我自己来挑**,而不是让工具静默丢掉其中一个。 - -这种策略本质上是交互式的。一个自动拉取的 cron 要么覆盖成果,要么在我没盯着的时候触发。所以我让触发变成手动:我说一句*"同步技能"*,agent 就去执行,并在**任何冲突时停下来问我**。这不是偷懒——而是合并的决定权在我手里,自动化做不了这个决定。 - -我记录下来的(也是现在真正在跑的)流程是: - -```bash -# 1. 把远端拉进仓库副本,只快进——绝不 force -cd D:\dev\hoelee-agent-dist && git pull --ff-only origin main - -# 2. 调和活跃目录 ↔ 仓库副本 -diff -rq ~/AppData/Local/hermes/skills D:/dev/hoelee-agent-dist/skills - -# 3. 只暂存真正的技能内容(绝不包含 curator 垃圾) -# 4. 提交 + 推送,然后验证远端确实有了 -git ls-remote origin main # 必须等于本地 HEAD -``` - -如果拉取被拒绝,或者 diff 显示同一个技能在两边都被改过,我就停下来做决定。绝不 `--force`,绝不 reset。 - -## 那坨悄悄撑大仓库的垃圾 - -第一次打包时的一个具体数字:我的技能目录有 **57 MB**,但真正的技能内容只有 **~8 MB**。剩下的是 agent 的 curator 不断写入的运行时状态——一个 40 MB 的 hub 索引缓存、curator 备份、使用统计、一份账本。 - -这些都不该进共享仓库。它们每天都在变、是机器本地的、而且会让每次同步都变成一团糟。一个 `.gitignore` 就能把它们剥掉: - -```gitignore -# skill 运行时垃圾——绝不入库 -skills/.hub/ -skills/.curator_backups/ -skills/.curator_ledger.jsonl -skills/.usage.json -skills/.bundled_manifest -``` - -当你打包一个会自我学习的 agent 时,会发现它不只是文件——是文件*加上*一层必须挡在外面的簿记。跟给 `node_modules` 写 `.gitignore` 是同一个道理,只不过对象是你自己的记忆。 - -## 我会做得不一样的地方 - -- **先想清楚触发方式,再选机制。** 我花了不少功夫纠结 distribution 还是 export,却还没回答"我要手动还是自动"——而这个答案反过来会*改变*机制。如果我一开始就知道要的是手动的、冲突感知的同步,第一天就会照这个方式去设计脚本。 -- **把"副本 vs 活跃目录"的区分当作一条有名字的不变量。** 我是靠 diff 才发现的;它本该从第一次 `cp -r` 起就写进我的笔记里。 -- **提前决定每台机器的 `user_id`。** 技能走 git 同步,但情节记忆(mem0)是另一个后端——两台机器要么共享一个记忆桶、要么各留各的,这是一个应该早点明确的单行配置选择。 +- **先换线。** 在看到超时或写损坏时,在给盘判死刑之前,重新插拔/更换线材,或换到另一个口,重跑*相同*的失败命令。问题跟着**端口**走就是链路故障;跟着**盘**走(换了好口还坏)才是盘的问题。这是最便宜、最能一锤定音的测试,而我花了好几小时才做。 +- **别信一个干净的 `randrw`。** 它看不见静默损坏。凡是盘出现过任何写症状,都用 `verify=crc32c` 和 `do_verify=1`。 +- **对准日志里的 LBA 区间。** 内核或文件系统已经标记了具体扇区的话,就在*那里*测,而不是从偏移 0 开始。 +- **SMART 全绿 ≠ 链路健康。** UDMA_CRC 为零只说明*当前*链路干净,它看不到过去那段不稳定的链路;而传输超时的页面在算出 CRC 之前就已经被丢了。 ## 结果 -现在我有一个 git 仓库——`git.hoelee.com/hoelee/hoelee-agent-dist`——装着 172 项技能、我的配置、SOUL 和定时任务。另一台机器把它装进一个命名 profile,再把自己本地的技能合并进去,我们靠一个"每次冲突都问我"的手动触发器保持同步。第一次真正的同步推送了一个只存在于活跃机器上的技能,验证它落地了(两边都是 `edbf7ac`),并且没有动任何现有的技能。 +这颗几分钟前就要被我送去 RMA 的盘,现在已经是一颗格式化好、挂载上、verify 全过的缓存 SSD,`btrfs device stats` 全部清零。修好它的成本:一根线。相信原有诊断的成本:一趟没必要的保修,还有一台迟早会在那根坏线上损坏数据的机器。 -给任何想同步 agent 的人的一句实在话:*文件*是简单的——git 干了大部分重活。难的是那些护栏:那个你绝不能跑的 `--force`,那个你绝不能误当成真相来源的副本,还有那个你绝不能让工具替你静默解决的冲突。 - ---- - -## 想为自己的 agent 搭建这套东西吗? - -我为企业和个人搭建自托管的 AI 基础设施——agent、bot、自动化。如果你正在跨机器运行 agent(或想开始),或者需要自托管工具方面的帮助,我很乐意聊聊: - -- 📱 **WhatsApp:** [+60 12-797 2969](https://wa.me/60127972969) -- 📧 **Email:** [me@hoelee.com](mailto:me@hoelee.com?subject=Agent%20sync%20setup) -- 🌐 **Website:** [hoelee.com](https://hoelee.com) +如果你在 NAS 或自管服务器上遇到一颗盘报 FPDMA 超时、但 SMART 看起来没问题——换线,别急着换盘。 ```` ### 🇬🇧 英文版原文 (English Markdown Primary) ````markdown --- -title: "Syncing a Self-Improving AI Agent Across Machines" -description: "How I sync my Hermes agent's skills, config, and cron jobs between two PCs with a git-backed profile distribution — and why I sync manually instead of on a cron." -pubDate: 2026-02-18 -updatedDate: 2026-09-11 -category: case-studies -blueprint: ai-agent-automation -blueprintLayer: L2-llm-gateway-agents -tags: [hermes, git, gitea, ai-agents, devops, sync] -ogImage: /og/syncing-a-self-improving-ai-agent-across-machines.jpg -banner: /banners/syncing-a-self-improving-ai-agent-across-machines.jpg +title: "I Was About to RMA This SSD — the Fault Was a SATA Cable" +description: "A Seagate IronWolf 110 SSD threw WRITE FPDMA timeouts, failed mkfs with 'superblock magic doesn't match', and went silent — a textbook dying drive. I swapped one SATA cable and it formatted clean with zero errors. How to test before condemning a drive." +pubDate: 2026-09-16 +category: devops +blueprint: self-hosted-infrastructure +blueprintLayer: L1-compute-storage-network +tags: [unraid, sata, ssd, storage, troubleshooting, smart, fio, cable] +draft: false +ogImage: /og/that-dying-ssd-was-just-a-bad-sata-cable.jpg +banner: /banners/that-dying-ssd-was-just-a-bad-sata-cable.jpg --- -My agent learns. Every time I walk it through a non-trivial workflow — how to -publish to Gitea, how to troubleshoot a flaky Docker container, how to write a -Shopee listing — it saves that as a *skill*: a reusable procedure it loads the -next time the task comes up. Over a few months that grew to 172 skills across -twenty categories. They're my second brain. +Every storage guide tells you to start with SMART and trust the event log. I did. Both pointed at one verdict: this SSD is dying. I was one config change away from RMA-ing a healthy drive. -The problem: that brain lives on one machine. When I sit down at my other PC, -the agent is *dumber* — it doesn't know what I taught it on the first one. +In September 2026 a Seagate IronWolf 110 960 GB SATA SSD — SMART-clean, ~99% life, zero reallocated sectors — kept failing a btrfs `mkfs` and then stopped answering reads. The kernel log was full of `WRITE FPDMA QUEUED` timeouts, `NCQ disabled due to excessive errors`, and `lost async page write`. The final `mkfs` printed its superblock, then failed to read it back. -This is the story of how I made the agent's knowledge follow me between -machines, why the obvious approach would have silently destroyed work, and the -one decision that turned out to matter most. +Exactly one detail saved the drive: I swapped the SATA cable before I condemned it. ## Why this matters -If you run any self-improving agent — Hermes, Claude Code, Codex, Cursor — you -have this exact problem. The agent accumulates knowledge locally, and none of it -moves. You either re-teach it on every machine (pointless) or you let the two -copies drift until they contradict each other (worse). +A bad SATA port or cable produces **the same symptoms as a dead drive**, and it produces them while SMART stays immaculate. Cable faults happen at the link layer — the transport times out and the kernel drops the I/O before your filesystem or SMART ever sees a wrong byte. If you diagnose by SMART alone, you'll condemn healthy hardware, raise a pointless RMA, and the replacement will fail the same way on the same cable. -Solving it properly means three things, and they're the same three things any -engineer cares about when syncing *any* state: +## The symptoms that screamed "dead drive" -- **A shared source of truth** — one canonical copy both machines pull from. -- **No silent data loss** — a sync that can't clobber work you did on the other - machine. -- **A decision point** — when two machines changed the same thing, *you* pick, - not the tool. +This was a standalone Seagate IronWolf 110 (ZA960NM10001, an enterprise SATA SSD, ~894 GiB) I was preparing for an Unraid cache pool. Three things happened, all consistent with a failing SSD: -Get those three right and your agent is genuinely the same person on both -machines. Get them wrong and you spend a weekend reconstructing a skill a bad -`--force` wiped out. +1. The kernel log cycled through libata error handling every ~30 s: + ``` + ata7.00: exception Emask 0x4 (timeout), WRITE FPDMA QUEUED, status { DRDY } + ata7.00: exception ... action 0x6 frozen + attribute NCQ disabled due to excessive errors + Buffer I/O error on dev sdd1 ... lost async page write + ``` + The drive stopped completing queued writes, the kernel hard-reset the link, and once it degraded it **dropped real pages** — 28 `/dev/sdd` LBAs lost async page writes. -## The three official mechanisms +2. `mkfs.btrfs -K -f /dev/sdd1` printed a full filesystem header, then failed verification: + ``` + Filesystem size: 894.25GiB + ERROR: superblock magic doesn't match + ``` + btrfs wrote its superblock, reread it, and got different bytes back. That's silent write-path corruption — the worst kind. -Hermes ships three ways to move an agent, and they answer different questions: +3. After that, `smartctl -H /dev/sdd` **timed out**. The drive wasn't answering even a health poll. Combined with the write-corruption kernel flags, "RMA it" was the reasonable conclusion. -| Need | Mechanism | Command | -|---|---|---| -| Just skills | Skills Hub "tap" (a git repo of `SKILL.md` folders) | `hermes skills tap add` + `install` | -| Whole agent, versioned, pullable | **Profile distribution** (git repo + `distribution.yaml`) | `hermes profile install` / `update` | -| One-off move / backup | Export file (`.tar.gz`) | `hermes profile export` / `import` | +## The detail that changed the verdict -For "same agent on two machines," the **profile distribution** is the durable -answer. It packages the whole agent — SOUL, config, skills, cron — as a git -repo, and the other machine pulls updates with one command. +Mid-diagnosis I had to move the drive physically — I landed it on a different SATA port with a different cable. I reran the *identical* `mkfs.btrfs` command before doing anything else. -I already run Gitea (git.hoelee.com) for everything else, so a distribution -repo there was the natural fit. No new tooling, no new accounts, and it plays -by the same Gitea-first convention I use for every project. +It passed. Zero errors. `btrfs device stats` came back all-zero. An 8 GiB `fio` write with `verify=crc32c` (which writes patterned data and **rereads it to check bytes**) completed at err=0 with a clean read-back. The `smartctl` timeout never returned. `dmesg` shows **zero** error lines for the drive since that swap. -## The trap I almost walked into +Nothing changed except the link. The "silent write corruption" was the SATA transport corrupting frames on the wire, not the NAND. -The distribution installer has a safety property that *sounds* like a -limitation but is exactly what saves you: **it refuses to install into the -`default` profile.** You must give it a named profile. +## The test that would have caught it (and the one that won't) -That's not an annoyance. The second PC already had its own agent with -project-specific skills. If I'd installed the distribution *over* it — or used -`--force`, which overwrites an existing profile — I'd have deleted that -machine's local work. The `default`-refusal is the guardrail that forces you to -install *alongside* the existing agent, then merge. +Two lessons came out of this: -Which is the real lesson of this whole exercise: **the merge is the product.** -The sync isn't "copy files." It's reconciling two agents that both think -they're the source of truth. +**A plain `fio randrw` is blind to this fault.** A standard 60 s `randrw` test (70/30, 4k, iodepth 32) writes and reads random sectors — but it never *checks* that the bytes you read back match what you wrote. On a drive that corrupts on the wire, it reports err=0 and a clean pass. That's exactly what my first test did: *clean*, on a drive that then failed mkfs. -## The layout fact that would have clobbered me - -Here's the subtle part, and it's the kind of thing that looks fine until it -isn't. - -The distribution repo holds a **copy** of the skills tree — it is *not* the -live directory. The live skills live in `~/AppData/Local/hermes/skills/` (where -the agent actually writes); the repo copy is a snapshot I push. They are two -separate trees that drift. - -So a sync actually has **three parties**, not two: +**You need `verify`, and you need the right region.** fio's `verify=crc32c` writes checksums and rereads to confirm them — that's what trips read-back mismatches. And the fault was **localized**: the corrupt LBAs (~234,422,526–869, around 111.8 GiB into the device) sat 100 GiB past where my first test ran. A test at the wrong offset misses it entirely. The proof: a verify job pointed at the healthy region passed; the same job pointed at the known-bad range stalled the drive exactly like the pool failure had. ``` -live skills dir ←→ repo copy (D:\dev\hoelee-agent-dist\skills) ←→ Gitea remote +# The discriminating test: write w/ checksum, reread, fail on mismatch +# Run against the ENTIRE surface or the exact LBA range dmesg flagged +fio --name=verify --filename=/dev/sdd \ + --offset=111G --size=2G \ + --rw=write --verify=crc32c --do_verify=1 \ + --bs=4k --ioengine=io_uring --direct=1 --iodepth=32 ``` -A skill I create after the last push exists *only* in the live dir. If I'd -assumed the repo copy was authoritative and "synced" from it, I'd have -silently deleted that skill. The first thing I do before any sync is diff the -two trees: - -```bash -diff -rq ~/AppData/Local/hermes/skills D:/dev/hoelee-agent-dist/skills -``` - -Divergence is *normal*, not an error. The whole discipline is knowing which of -the three parties is ahead and reconciling deliberately. - -## Why I sync manually, not on a cron - -This was the decision that mattered most, and it came down to the conflict -policy. I want two-way sync — both machines edit skills — and when both edit -the *same* skill, I want to **keep both and pick myself**, not have a tool -silently drop one. - -That policy is inherently interactive. A cron job that auto-pulls either -overwrites work or fires when I'm not looking. So I made the trigger manual: I -say *"sync skills"*, the agent runs it, and it **stops and asks me on any -conflict**. It's not laziness — it's that the merge decision is mine to make, -and automation can't make it for me. - -The flow I documented (and now run) is: - -```bash -# 1. Pull remote into the repo copy, fast-forward only — never force -cd D:\dev\hoelee-agent-dist && git pull --ff-only origin main - -# 2. Reconcile live dir ↔ repo copy -diff -rq ~/AppData/Local/hermes/skills D:/dev/hoelee-agent-dist/skills - -# 3. Stage only real skill content (never the curator junk) -# 4. Commit + push, then verify the remote actually has it -git ls-remote origin main # must match local HEAD -``` - -If the pull refuses, or a diff shows the same skill changed on both sides, I -stop and decide. Never `--force`, never a reset. - -## The junk that was silently bloating the repo - -One concrete number from the first packaging: my skills directory was **57 MB**, -but only **~8 MB** was actual skill content. The rest was runtime state the -agent's curator writes constantly — a 40 MB hub index cache, curator backups, -usage tracking, a ledger. - -None of that belongs in a shared repo. It changes daily, it's machine-local, -and it would have made every sync a noisy mess. A `.gitignore` strips it: - -```gitignore -# skill runtime junk — never ship -skills/.hub/ -skills/.curator_backups/ -skills/.curator_ledger.jsonl -skills/.usage.json -skills/.bundled_manifest -``` - -The moment you package a self-improving agent, you discover it's not just -files — it's files *plus* a layer of bookkeeping you have to keep out. Same -lesson as a `.gitignore` for `node_modules`, but for your own memory. +If you run the same job on a *healthy* drive, `verify` succeeds. If the link is bad, fio reports checksum mismatches or hangs — long before a plain run would tell you anything. ## What I'd do differently -- **Think about the trigger before the mechanism.** I spent effort deciding - distribution-vs-export before I'd answered "do I want this manual or - automated?" — and the answer to that question *changed* the mechanism. If I'd - known I wanted manual, conflict-aware sync from the start, I'd have designed - the script that way on day one. -- **Treat the copy-vs-live distinction as a named invariant.** I discovered it - by diffing; it should have been a line in my notes from the first `cp -r`. -- **Decide per-machine `user_id` up front** for memory. Skills sync via git, - but episodic memory (mem0) is a separate backend — two machines either share - one memory bucket or keep separate ones, and that's a one-line config choice - I should have made explicit earlier. +- **Swap the cable first.** Before condemning a drive for timeout or write-corruption, reseat/replace the cable or move to a different port and rerun the *same* failing command. If the problem follows the **port**, it's a link fault; if it follows the **drive** across good ports, it's the drive. This is the single cheapest, most decisive test and I skipped it for hours. +- **Don't trust a clean `randrw`.** It can't see silent corruption. Use `verify=crc32c` and `do_verify=1` whenever a drive has shown any write symptom. +- **Target the logged LBA range.** If the kernel or filesystem already flagged specific sectors, test *there*, not at offset 0. +- **SMART-clean ≠ healthy link.** Zero UDMA_CRC just means the *current* link is clean; it can't see the past flaky one, and transport-timeout pages are dropped before a CRC is even computed. ## The result -I now have one git repo — `git.hoelee.com/hoelee/hoelee-agent-dist` — holding -172 skills, my config, SOUL, and cron jobs. The other machine installs it into -a named profile, merges its own skills in, and we stay in sync with a manual -trigger that asks me on every conflict. The first real sync pushed a -skill that existed only on the live machine, verified it landed (`edbf7ac` on -both ends), and left every existing skill untouched. +The drive I was minutes away from RMA-ing is now a formatted, mounted, verified-working cache SSD with `btrfs device stats` reading all zeros. The cost of the fix: one cable. The cost of trusting the diagnosis I had: a needless warranty claim and a rig kept on a cable that was going to corrupt data sooner or later anyway. -The honest takeaway for anyone syncing an agent: the *files* are easy — git -does the heavy lifting. The hard parts are the guardrails: the `--force` you -must never run, the copy you must never mistake for the source of truth, and -the conflict you must never let a tool resolve silently. +If you're on a NAS or a home server and a drive "fails" with FPDMA timeouts but SMART looks fine — change the cable before you change the drive. +```` --- -## Want this for your own agent setup? +## 文章 04 / 11:换了不同的硬盘,同样的损坏又来了——真凶是 TRIM,不是 SSD +- **Slug**: `the-cause-was-trim-not-the-ssds` +- **英文标题**: The Corruption Came Back on Different Drives — the Cause Was TRIM, Not the SSDs +- **分类**: `devops` | **发布日期**: 2026-09-18 +- **线上地址**: https://blog.hoelee.com/posts/the-cause-was-trim-not-the-ssds/ (EN) | https://blog.hoelee.com/posts/zh/the-cause-was-trim-not-the-ssds/ (ZH) +- **本篇审核状态**: ⏳ 待审核 (Pending) -I build self-hosted AI infrastructure — agents, bots, and automation — for -businesses and individuals. If you're running an agent across machines (or want -to start), or need a hand with self-hosted tooling, I'd love to talk: +### ✍️ 顾问审阅意见区 (Review Feedback) +```text +【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 +【事实与数字核对】: +【人设与用词卫生】: +【CRO与转化建议】: +``` -- 📱 **WhatsApp:** [+60 12-797 2969](https://wa.me/60127972969) -- 📧 **Email:** [me@hoelee.com](mailto:me@hoelee.com?subject=Agent%20sync%20setup) -- 🌐 **Website:** [hoelee.com](https://hoelee.com) +### 🇨🇳 中文版原文 (Chinese Markdown Twin) +````markdown +--- +title: "换了不同的硬盘,同样的损坏又来了——真凶是 TRIM,不是 SSD" +description: "两周前 btrfs RAID1 阵列在看似健康的 NVMe 盘上静默损坏数据,两周后同一个全零校验和出现在完全不同的硬盘上。真凶是 Seagate IronWolf 110 上的队列化 TRIM(NCQ)——FreeBSD 早就拉黑了这个固件缺陷,Linux 却一直没有。我是怎么抓到它、以及修复方法的全过程。" +pubDate: 2026-09-18 +category: devops +tags: [unraid, btrfs, trim, ssd, raid, data-loss, smart, troubleshooting, seagate] +ogImage: /og/zh-the-cause-was-trim-not-the-ssds.jpg +banner: /banners/the-cause-was-trim-not-the-ssds.jpg +--- + +两周前我写了一篇文章,讲一个 btrfs RAID1 阵列如何在两块看起来完全健康的三星 PM9A3 NVMe 盘上静默损坏 Windows 虚拟机——读出来的全是**全零**数据块,单靠一块坏盘根本无法解释。那次调查以一句诚实的「不确定」收尾:两块盘测试都干净,最大嫌疑是它们共用的 M.2 转接卡。 + +然后它又发生了。在**不同的硬盘**上,走**不同的总线**。校验和指纹一模一样。这一次我找到了根因——而且跟 SSD 本身无关。 + +## 为什么这很重要 + +如果你在 Unraid(或任何 Linux 机器)上跑 btrfs RAID1 + SATA SSD + 自动 TRIM,这篇是给你的提醒:**队列化 TRIM 正在同时、在同一位置、静默地摧毁我阵列的两份镜像。** RAID 冗余在这种损坏面前毫无保护力。而全程被 SMART 标记为「failing」的那块盘,跟真正的损坏一点关系都没有。 + +--- + +## 环境 + +- **unRaid 7.x**,Intel i9-13900K。 +- **`ssd` 池**:两块 **Seagate IronWolf 110 960 GB** SATA SSD + (`ZA960NM10001`,序列号 `HKR02TFK` + `HKR02L9P`)组 **btrfs RAID1**, + 挂载在 `/mnt/ssd`,上面跑着 Docker 数据根目录(`/var/lib/docker`)和 + Windows 11 虚拟机的虚拟磁盘(`domains/Win11Enterprise/vdisk1.img`)。 +- 虚拟机虚拟磁盘**没有**开 `NOCOW`,所以 btrfs 每次读取都会校验——和上次 + 事故能被发现靠的是同一个设置。 + +顺带一提:其中一块盘(`sdd`)正是 *[《我当时差点就去 RMA 这块 SSD——其实是 SATA 线坏了》](/posts/zh/that-dying-ssd-was-just-a-bad-sata-cable/)* +里那块盘——换线之后格式化干净,就进了这个池。 + +## 第一步——一个「假」的 SMART 故障 + +凌晨 02:53,Unraid 的通知铃响了: + +``` +Unraid Ssd disk SMART health [1] — Warning [UNRAID] - +raw read error rate (failing now) is 19665 (sdd = ZA960NM10001_HKR02TFK) +``` + +「failing now」是 SMART 里最强的措辞——盘自报该属性**跌破阈值**。但在这些 +Seagate 盘上,raw 值是障眼法:IronWolf 110 的属性 1 raw 字段是厂商编码的 +复合值(高半部分是错误数,低半部分是操作计数)。`19665 = 0x00004CD1` → +高半部分 = **0 个错误**。真正触发的是*归一化*值:`093`,**最差值 088**, +低于 `090` 阈值,于是盘在 SMART 返回状态里自报 `FAILING_NOW`/`IN_THE_PAST`。 +另一块盘(`sdb`)形状相同,raw 只有 `341`。 + +所有真实的故障计数器都是零:重映射 0、坏块增长 0、编程/擦除失败 0、 +不可纠正 ECC 0、UDMA CRC 0、寿命剩余 99 %、SMART 总体 **PASSED**,刚跑完的 +扩展自检也干净。这是 IronWolf 110 有据可查的行为——多年前 Synology 用户就 +在 100 % 寿命时撞上过同样的「Failing」旗标,社区共识是:只要真实计数器不动, +这个型号的属性 1 触发就当固件噪音处理。 + +所以:盘是误报,但这次报警让我去看了——然后才找到真正的损坏。 + +## 第二步——一个不该存在的校验和 + +`btrfs device stats /mnt/ssd`: + +``` +[/dev/sdd1].corruption_errs 27 [/dev/sdb1].corruption_errs 31 +``` + +全部集中在同一个文件:**ino 261 = Windows 虚拟机的虚拟磁盘**。 +`dmesg` 里是上一个 NVMe 事故里我盯了一周的同一个签名: + +``` +btrfs: checksum verify failed on logical 1505629372416 mirror 1 wanted 0x8941f998 +``` + +**`0x8941f998` 是 4 KiB 全零块的 CRC32C。** 池在读出空白块——而且关键的,是 +在**两块盘的相同逻辑偏移上同时读出**。我翻了 PM9A3 阵列那次的笔记:值相同, +「确定性全零」行为相同,让 RAID1 失效的关联方式也相同。 + +这个匹配是指纹级的。无论这是什么,它都不是硬盘的问题,也不是 M.2 转接卡的 +问题——IronWolf 这对盘走的是 **SATA 口**,完全不同的控制器路径。问题出在 +**比硬盘高一层**:有一个机制决定同时擦掉两块盘上相同的数据。Linux 里恰好 +只有一个机制干这事:**discard / TRIM**。 + +## 第三步——根因:在 Linux 从未拉黑的硬盘上跑队列化 TRIM + +Unraid 的池配置开了自动 TRIM,btrfs 以 `discard=async` 挂载——内核批量收集 +空闲块发给硬盘。对 SATA SSD 来说,那就是**队列化 TRIM**(`DATA SET +MANAGEMENT` 命令以 NCQ 命令形式延迟执行,即 `SEND FPDMA QUEUED`)。 + +IronWolf 110 的队列化 TRIM **不稳定的问题早就被记录了**。FreeBSD 内核有一个 +文档化的报告——[bug 264139](https://bugs.freebsd.org/264139), +*「ata: NCQ_DSM_TRIM trim method for Seagate IronWolf 110 SATA SSD hangs drives」*, +2024 年合并的修复提交写得毫不客气:[commit `a6cef617660a`](https://lists.freebsd.org/archives/freebsd-fs/2024-March/003273.html): +「Seagate IronWolf 110 SATA SSD 已被报告在启用 NCQ trim 时不稳定。」 + +而 Linux 自己的怪癖清单(`drivers/ata/libata-core.c`)——内核会在这里主动把 +有问题的盘降级为非队列化或禁用 TRIM——收录了 Micron M500/M550/1100、 +Crucial M500/M550/MX100、三星 840/850/860/870 等,但**没有一条 Seagate +条目**。我自己机器上的 `dmesg` 恰好证明这个机制存在而且在选择性生效: + +``` +ata6.00: Model 'Samsung SSD 840 PRO Series', rev 'DXM06B0Q', applying quirks: noncqtrim zeroaftertrim +``` + +这条怪癖给了机箱里*另一块* SSD,而两块 IronWolf 110 什么怪癖都没有, +拿到了完整的队列化 TRIM。 + +为什么这会毁掉 RAID1?因为 btrfs RAID1 在两块成员盘上存的是*同一份*空闲 +映射——会在同一轮里对两块盘丢弃相同的逻辑区间。如果这个固件上的 TRIM 路径 +会多失效(或失效错)LBA,就会**同时清掉两块镜像上的同一批活动块**。你的 +镜像变成同一个洞的两份拷贝:两块盘都校验失败,自愈没有任何可抄的源,数据 +彻底没了。 + +> 诚实的保留意见:FreeBSD 记录的是盘侧的*不稳定/卡死*,而「队列化 TRIM 抹掉 +> 了活动数据」是我根据这个记录加指纹(双镜像全零、SMART 干净、CRC 错误计数 +> 不涨)推断的机制。它符合每一条观察。证明靠实验——见下面的结果。 + +## 第四步——修复(持久化,一次只改一个变量) + +只改一处,双管齐下——持久配置 + 热挂载: + +```bash +# /boot/config/pools/ssd.cfg (备份:/root/ssd.cfg.bak.20260918-0329) +diskAutotrim="off" # 原来是 "on" + +# 不停阵列、不动 Docker(36 个容器全程在线)直接生效 +mount -o remount,nodiscard /mnt/ssd +findmnt /mnt/ssd # → rw,noatime,ssd,space_cache=v2 (不再有 discard=async) +``` + +然后做一次完整读写 scrub,搞清楚到底坏了多少: + +``` +scrub started 03:29:53, finished 03:53:07 (23 min) +csum_errors: 18 corrected_errors: 16 uncorrectable_errors: 2 +read_errors: 0 verify_errors: 0 super_errors: 0 +``` + +`read/verify/super = 0` 是指纹的另一半:硬件读盘*完全正常*——没有任何部件在 +故障,只是盘上存的字节和校验和不符。18 个坏块里,**16 块只有一块镜像坏, +已从完好副本自愈;2 个 uncorrectable 其实是同一个 4 KiB 块两块镜像都坏**—— +永久丢失,位于虚拟机虚拟磁盘约 45.2 GiB 处(`logical 1505629372416`,文件 +偏移 `48560156672`)。我把这一个块填零,至少虚拟机读到那里不再报错;原始 +字节无论如何都找不回来了。 + +还有一个值得知道的坑:**scrub 跑了 18 个错误,`btrfs device stats` 计数器 +却纹丝不动**——scrub 发现的错误和读取时发现的错误是分开统计的。你没法只盯 +`device stats` 一个数;dmesg 和 scrub 输出也得一起盯。(我的看门狗三样都查, +细节见文末。) + +## 换成我会怎么做 + +1. **任何 btrfs 池开自动 TRIM 之前,先查这块盘的队列化 TRIM 记录。** + FreeBSD 维护一份「别给这盘发 TRIM」清单不是没有原因的。Linux 在 + `libata-core.c` 里有同样的机制——花一个下午 grep + 首次开机后看一眼 + `dmesg`,好过一次从备份里恢复虚拟机。 +2. **TRIM 可以有,但不能队列化。** SATA SSD 想跑 fstrim 就强制非队列化 + (`libata.force=…:noncqtrim`),并在第一次 trim 后做一次 scrub 验证。 + `discard=sync` **没用**——只要盘支持,sync 同样走队列化路径。 +3. **三个损坏信号一起盯**,别只看一个:`btrfs device stats`、 + `dmesg | grep 'csum failed'`、周期性 scrub。三者各有各的计数器(见上文)。 +4. **并入池之前先交叉验证。** 同批次、同固件的盘是关联故障风险;两块盘共一个 + 固件 bug 就是最坏的那种关联故障。镜像两次都没救得了我。 +5. **买企业级 SATA SSD 时**:Linux 怪癖清单上的盘(Micron M500/M550/1100、 + Crucial M500/M550/MX100、三星 840/850/860/870)以及一切有记录在案的 + NCQ-TRIM bug(IronWolf 110)直接排除。三星 PM893/PM897、Micron 5400 + PRO/MAX、Solidigm D3-S4610/S4620、WD Ultrastar DC SA620/SA630、Kingston + DC600M 都有断电保护(PLP)且不在 Linux 怪癖清单上;而且 Micron、Solidigm、 + WD、Kingston 会公开发布固件更新说明,真出了问题还能给你推送修复。NVMe + 从根上绕开了 SATA 队列化 TRIM 这一类问题——我那两块 PM9A3 也不在 NVMe + 怪癖表里。 + +## 结果 + +只改了一个变量(关自动 TRIM),其他原封不动。紧接着: + +- 第二次 scrub(04:10–04:39):**`corrected_errors: 0`** ——16 块自愈块保持 + 住了,整盘重读没有出现任何新错误。 +- `corruption_errs` 维稳在 sdd1=27 / sdb1=31,持续数小时的 Docker + 无虚拟机 + 运行(此前计数器是每天在涨的)。 +- dmesg 里没有新增 `csum failed` 行。 + +确认窗口还有几天:Win11 虚拟机重新上线(它产生的是能复现问题的写入模式)、 +对照基线文件每日检查、2026-09-22 再做一次复核 scrub。如果关了 TRIM 损坏还在, +下一个嫌疑就不是硬盘,而是内存(这台机器没有 ECC)——用 memtest 测。如果 +一直平静,那 IronWolf 110 队列化 TRIM 固件 bug 就算坐实了——我敢说论坛里 +「健康硬盘毁掉我的 RAID」的帖子,相当一部分也是它干的。 + +一个「正在故障」的 SMART 告警、一块零错误的硬盘、一个全新阵列上双镜像同时 +损坏——每个迹象都指向别处,而真正的凶手是一个我们大多数人不假思索就开启的 +存储功能。 + +--- + +*我的存储故障系列之一:[NVMe 事故](/posts/when-smart-says-healthy-but-your-raid-is-corrupting-data/) 和 [SATA 线警醒](/posts/that-dying-ssd-was-just-a-bad-sata-cable/)。* +```` + +### 🇬🇧 英文版原文 (English Markdown Primary) +````markdown +--- +title: "The Corruption Came Back on Different Drives — the Cause Was TRIM, Not the SSDs" +description: "Two weeks after a btrfs RAID1 pool corrupted on healthy-looking NVMe drives, the same all-zero checksum reappeared on a different drive stack. The culprit was queued TRIM (NCQ) on Seagate IronWolf 110 SSDs — a firmware bug FreeBSD blacklisted but Linux never did. How I caught it and the fix." +pubDate: 2026-09-18 +category: devops +tags: [unraid, btrfs, trim, ssd, raid, data-loss, smart, troubleshooting, seagate] +ogImage: /og/the-cause-was-trim-not-the-ssds.jpg +banner: /banners/the-cause-was-trim-not-the-ssds.jpg +--- + +Two weeks ago I published how a btrfs RAID1 pool on two healthy-looking Samsung +PM9A3 NVMe drives silently corrupted a Windows VM — reads returning +**all-zero** blocks that no single bad drive could explain. That investigation +ended with an honest shrug: the drives tested clean, the strongest suspect was +the shared M.2 riser. + +Then it happened again. On *different* drives, on a *different* bus. The exact +same checksum fingerprint. This time I found the root cause — and it wasn't +the SSDs. + +## Why this matters + +If you run Unraid (or any Linux box) with a btrfs RAID1 pool on SATA SSDs and +auto-TRIM enabled, this post is a heads-up: **queued TRIM was silently +destroying both mirrors of my pool, in the same places, simultaneously.** RAID +redundancy gives you zero protection against it. And SMART — which flagged a +drive as *failing* through all of this — had nothing to do with the actual +corruption. + +--- + +## The setup + +- **unRaid 7.x** on an Intel i9-13900K. +- **Pool `ssd`**: two **Seagate IronWolf 110 960 GB** SATA SSDs + (`ZA960NM10001`, serials `HKR02TFK` + `HKR02L9P`) in **btrfs RAID1**, + mounted at `/mnt/ssd`, holding Docker's data root (`/var/lib/docker`) and + the Windows 11 VM's virtual disk (`domains/Win11Enterprise/vdisk1.img`). +- The VM's vdisk is **not** `NOCOW`, so btrfs validates every read against a + checksum — the same setting that caught the previous incident. + +Trivia: one of these drives (`sdd`) is the very drive from *["I Was About to +RMA This SSD — the Fault Was a SATA Cable"](/posts/that-dying-ssd-was-just-a-bad-sata-cable/)* +— after the cable swap it formatted clean and joined this pool. + +## Step 1 — a SMART "failure" that wasn't + +At 02:53 the Unraid notification bell went off: + +``` +Unraid Ssd disk SMART health [1] — Warning [UNRAID] - +raw read error rate (failing now) is 19665 (sdd = ZA960NM10001_HKR02TFK) +``` + +"Failing now" is the drive declaring the attribute **worse than its +threshold** — the strongest wording SMART has. But the raw value is a red +herring on these Seagates: on IronWolf 110s, attribute 1's raw field is a +vendor-encoded composite (errors in the high half, an operation counter in the +low half). `19665 = 0x00004CD1` → high half = **0 errors**. The *normalized* +value is what tripped: `093` with a **worst of 088**, below the `090` +threshold, so the drive self-reports `FAILING_NOW` / `IN_THE_PAST` on its +SMART return status. The twin (`sdb`) showed the same shape with a raw of +only `341`. + +Every real failure counter was zero: reallocated 0, grown bad block 0, +program/erase fails 0, uncorrectable ECC 0, UDMA CRC 0, SSD life left 99 %, +SMART overall **PASSED**, and a just-completed extended self-test was clean. +This is a documented IronWolf 110 behaviour — the same "Failing" flag at 100 % +lifespan hit Synology users years ago, and it's why the community treats that +model's attribute-1 trip as firmware noise unless the real counters move. + +So: false alarm on the *drive*, but the alarm made me go look — and that's +when I found the real damage. + +## Step 2 — the checksum that had no right to exist + +`btrfs device stats /mnt/ssd`: + +``` +[/dev/sdd1].corruption_errs 27 [/dev/sdb1].corruption_errs 31 +``` + +All of it confined to one file: **ino 261 = the Windows VM's vdisk**. +`dmesg` showed the same signature I'd spent a week staring at in the NVMe +incident: + +``` +btrfs: checksum verify failed on logical 1505629372416 mirror 1 wanted 0x8941f998 +``` + +**`0x8941f998` is the CRC32C of 4 KiB of zeros.** The pool was reading back +empty blocks — and crucially, on **both mirrors at the same logical offsets**. +I verified it against my notes from the PM9A3 pool: identical value, identical +"deterministic zeros" behaviour, identical RAID1-defeating correlation. + +That match is a fingerprint. Whatever this is, it isn't the drives and it +isn't the M.2 riser — the IronWolf pair lives on **SATA ports**, a +completely different controller path. It's the *layer above* the drives +deciding to erase the same data on both members at once. There is exactly one +mechanism in Linux that does that: **discard / TRIM**. + +## Step 3 — the root cause: queued TRIM on a drive Linux never blacklisted + +Unraid's pool config had auto-TRIM on, which mounts btrfs with +`discard=async` — the kernel batches frees and sends them to the drive. On +SATA SSDs that means **queued TRIM** (the `DATA SET MANAGEMENT` command +deferred as an NCQ command, `SEND FPDMA QUEUED`). + +The IronWolf 110 is *known to be unstable with queued TRIM*. FreeBSD's +kernel has a documented report — [bug 264139](https://bugs.freebsd.org/264139), +*"ata: NCQ_DSM_TRIM trim method for Seagate IronWolf 110 SATA SSD hangs +drives"* — and the fix, merged in 2024, is blunt: +[commit `a6cef617660a`](https://lists.freebsd.org/archives/freebsd-fs/2024-March/003273.html): +"The Seagate IronWolf 110 SATA SSD drive has been reported to be unstable with +NCQ trim enabled." + +Meanwhile Linux's own quirk list (`drivers/ata/libata-core.c`) — where the +kernel deliberately downgrades broken drives to non-queued or disabled TRIM — +contains Micron M500/M550/1100, Crucial M500/M550/MX100, Samsung 840/850/860/870 +and a few others, but **no Seagate entry at all**. My own `dmesg` proved the +mechanism exists and is selective: + +``` +ata6.00: Model 'Samsung SSD 840 PRO Series', rev 'DXM06B0Q', applying quirks: noncqtrim zeroaftertrim +``` + +…applied to the *other* SSD in the box, while the two IronWolf 110s got +no quirk and full queued TRIM. + +Why does that corrupt a RAID1? Because btrfs RAID1 stores the *same* free-space +map on both members — it discards the same logical extents on both drives in +the same pass. A TRIM path that invalidates more (or the wrong) LBAs on this +firmware zeroes the **same live blocks on both mirrors at once**. Your mirror +becomes two copies of the same hole: the checksum fails on both, self-heal has +nothing to copy from, and the data is gone. + +> The honest caveat: FreeBSD documents *instability/hangs* from the drive +> side, and "queued TRIM erased live data" is the mechanism I infer from that +> plus the fingerprint (zeros on both mirrors, SMART-clean, CRC error counter +> untouched). It fits every observation. The proof is the test — see the +> result below. + +## Step 4 — the fix (persistent, one variable at a time) + +One change, applied twice — persistent config and live mount: + +```bash +# /boot/config/pools/ssd.cfg (backup: /root/ssd.cfg.bak.20260918-0329) +diskAutotrim="off" # was "on" + +# apply live without stopping the array or Docker (36 containers stayed up) +mount -o remount,nodiscard /mnt/ssd +findmnt /mnt/ssd # → rw,noatime,ssd,space_cache=v2 (no more discard=async) +``` + +Then a full read-write scrub to find out what was actually damaged: + +``` +scrub started 03:29:53, finished 03:53:07 (23 min) +csum_errors: 18 corrected_errors: 16 uncorrectable_errors: 2 +read_errors: 0 verify_errors: 0 super_errors: 0 +``` + +`read/verify/super = 0` is the second half of the fingerprint: the hardware +reads *fine* — nothing is failing, the stored bytes just don't match their +checksums. Of the 18 bad blocks, **16 were bad on one mirror and were healed +from the clean copy. Two uncorrectable entries were one single 4 KiB block +that was bad on both mirrors** — permanent loss, ~45.2 GiB into the VM's +vdisk (`logical 1505629372416`, file offset `48560156672`). I zero-filled +that one block so the VM's reads at least don't error; the original bytes are +unrecoverable either way. + +And a wrinkle worth knowing: **`btrfs device stats` counters did not move +during the scrub** even though it found 18 errors — scrub-detected errors and +read-detected errors are tracked separately. You cannot watch only `device +stats`; you have to watch dmesg + scrub output too. (My watchdog checks all +three; the details are at the end.) + +## What I'd do differently + +1. **Never enable auto-TRIM on a btrfs pool without checking the drive's + queued-TRIM record.** FreeBSD keeps a "don't TRIM this drive" list for a + reason. Linux has the same mechanism in `libata-core.c` — an afternoon of + grep + a `dmesg` check after the first boot beats a restored-from-backup VM. +2. **Keep TRIM on the menu, just not queued.** If you want fstrim on SATA + SSDs, force non-queued TRIM (`libata.force=…:noncqtrim`) and verify with a + scrub after the first trim pass. `discard=sync` does **not** help — it + still uses the queued path on drives that advertise it. +3. **Watch all three corruption signals**, not one: `btrfs device stats`, + `dmesg | grep 'csum failed'`, and periodic scrubs. Each can move + independently (see above). +4. **Corroborate before joining pairs.** Same-batch, same-firmware drives are + a correlated-failure risk; a pair sharing one firmware bug is the + correlated-failure worst case. The mirror didn't save me either time. +5. **When buying enterprise SATA SSDs**: the drives on Linux's quirk list + (Micron M500/M550/1100, Crucial M500/M550/MX100, Samsung 840/850/860/870) + and anything with a documented NCQ-TRIM bug (IronWolf 110) are out. + Samsung PM893/PM897, Micron 5400 PRO/MAX, Solidigm D3-S4610/S4620, + WD Ultrastar DC SA620/SA630, and Kingston DC600M all carry PLP plus no + Linux-quirk entries, and vendors that publish firmware release notes + (Micron, Solidigm, WD, Kingston) can actually ship you a fix. NVMe + sidesteps the SATA queued-TRIM class entirely — my PM9A3s aren't in the + NVMe quirk table either. + +## The result + +One variable changed (auto-TRIM off), everything else identical. Immediately +after: + +- scrub #2 (04:10–04:39): **`corrected_errors: 0`** — the 16 heal-blocks + stayed healed, nothing new appeared during the full re-read. +- `corruption_errs` flat at sdd1=27 / sdb1=31 for hours of normal Docker + + VM-less operation (counters had been climbing daily before). +- No new `csum failed` lines in dmesg. + +The confirmation window runs a few days: Win11 VM back on (it produces the +write pattern that reproduced this), daily checks against a baseline file, +and a re-scrub on 2026-09-22. If corruption reappears with TRIM off, the next +suspect isn't the drives — it's the RAM (no ECC on this box), and memtest is +the test. If it stays quiet, the IronWolf 110 queued-TRIM firmware bug is +confirmed as the cause of both this incident and — I'd bet — a good share of +the "healthy drives corrupting my RAID" reports the forums keep collecting. + +A "failing" SMART warning, a drive with zero errors, and corruption on +both mirrors of a fresh pool — every sign pointed somewhere else, and the +actual culprit was a storage feature most of us enable without a second +thought. + +--- + +*Part of my storage-failure series: [the NVMe incident](/posts/when-smart-says-healthy-but-your-raid-is-corrupting-data/) and the [SATA cable wake-up call](/posts/that-dying-ssd-was-just-a-bad-sata-cable/).* +```` + +--- + +## 文章 05 / 11:上游被删了,然后带着一个重写版回来 +- **Slug**: `the-upstream-was-deleted-then-came-back-rewritten` +- **英文标题**: The Upstream Was Deleted, Then Came Back as a Rewrite +- **分类**: `devops` | **发布日期**: 2026-10-06 +- **线上地址**: https://blog.hoelee.com/posts/the-upstream-was-deleted-then-came-back-rewritten/ (EN) | https://blog.hoelee.com/posts/zh/the-upstream-was-deleted-then-came-back-rewritten/ (ZH) +- **本篇审核状态**: ⏳ 待审核 (Pending) + +### ✍️ 顾问审阅意见区 (Review Feedback) +```text +【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 +【事实与数字核对】: +【人设与用词卫生】: +【CRO与转化建议】: +``` + +### 🇨🇳 中文版原文 (Chinese Markdown Twin) +````markdown +--- +title: "上游被删了,然后带着一个重写版回来" +description: "我线上跑的阅读服务,依赖的镜像官方仓库已经 404。几个月后上游回来了——233 个提交、换了语言、零 release。怎么分辨「项目死了」和「项目在重写」。" +pubDate: 2026-10-06 +category: devops +tags: ["docker", "self-hosting", "upstream", "maintenance", "registry"] +ogImage: "/og/zh-the-upstream-was-deleted-then-came-back-rewritten.jpg" +banner: "/banners/the-upstream-was-deleted-then-came-back-rewritten.jpg" +draft: false +--- + +`docker pull hectorqin/reader` 返回 **404**。而这正是我线上阅读服务所依赖的项目:一个只发邀请码的小书库,给我家人和几位付费读者用,每天在跑,上面还搭了一条我自己做的语音朗读管线,让「朗读」按钮念出来的是正经的神经网络音色。 + +404 还不是最有意思的部分。**2026-09-16**,同一个仓库被从零重新初始化——提交信息是 `chore: 初始化仓库`——十六天后,它已经有了 **233 个提交**、另一门语言、另一个端口、另一种数据库、另一个镜像仓库。我依赖的项目没有死,它是被**一个重写版替换了**,名字没变、地址没变、那 11,036 颗星也没变。 + +所以问题是:**怎么判断一个上游项目是死了,还是正在被重写?而当它以另一个应用的样子回来时,你该怎么做?** + +## 先说我这边的情况,因为细节才是这件事的关键 + +这个应用是一个自托管阅读服务器。浏览器端是 hash 路由的 Vue SPA,服务端是 Kotlin + Spring Boot,配置按用户存成磁盘上的 JSON。而我专门为它的一条能力搭了一整套管线:**HTTP 语音合成**。阅读器会把朗读请求代理到你配置的 URL,也就是说音色不是应用自带的——我的指向 n8n 的两个 webhook,由它们去换取短期 Azure / Google 凭据并合成音频。语音选择器里那 9 个引擎是这么来的,不是应用自带的。 + +此外,应用的镜像外面还有我自己的一层 nginx 网关容器:对外落地页、社交分享卡片、中英切换、以及一层英文界面补丁,全在那里,不在应用镜像里。当初做这个决定是为了品牌,而正是它让整件事从头到尾都很平静——后面我会回到这点。 + +## 我去找升级路径的时候,发现了什么 + +三个选项,没有一个叫「升级」: + +| 选项 | 它实际是什么 | 我为什么没选 | +|---|---|---| +| 官方镜像 | Docker Hub 上的 `hectorqin/reader` | 没了。仓库返回 404,`docker pull` 直接失败 | +| 还在维护的 fork | `changshengyu/reader`,版本 `2.5.4` | 基于最后一个完全开源的快照。它的朗读只用浏览器自带的 `speechSynthesis`,没有 HTTP 语音。它的整个历史里没有任何 `httpTTS` 字样,`/reader3/httpTts` 也是 404。我那 9 个引擎会全部消失 | +| 别人重新打包的镜像 | `liangnianzhi/reader.hectorqin:latest-20250525` | **这就是我现在跑的。** 唯一还能拉取、并且保留了 HTTP 语音的 3.x 构建。最后更新 2025-09-05,一共三个标签,发布者不是原作者 | + +我把那个标签钉死,把数据目录打包备份,把源码镜像到自己的 Git 服务器上——至少我依赖的代码得存在于我能控制的地方。然后把那句决定未来任何镜像是否有资格的话写了下来:**它是否还讲我这条管线所实现的 TTS 协议?** + +这就是当时的处境:一个跑在「官方仓库已被删除」的镜像上的服务,靠着某个陌生人重新打包的构建活着。 + +## 然后上游回来了 + +以下数据于 2026-10-06 直接取自 GitHub API 与镜像仓库: + +| 指标 | 数值 | +|---|---| +| 仓库 | `hectorqin/reader` —— 活着,AGPL-3.0,默认分支 `main` | +| Star / Fork | 11,036 / 5,471 | +| 最后推送 | 2026-10-02 | +| 提交数 | **233** —— 而最早的一条是 `chore: 初始化仓库`,日期 **2026-09-16** | +| release / tag | **0 / 0** | +| Docker Hub | 仍然 **404** | + +2021 年那段历史还在,但已经断开了。`main` 上是 233 个提交,最早一条的日期是 2026-09-16;旧分支仍然存在,但只剩**一个提交,日期 2026-06-22**,提交信息就是 `commit`,而它的 README 全文只有一个词——`deleted`。两个分支**没有共同祖先**——这就是「先清空、再重来」在 git 里的样子。 + +而这 233 个提交里的代码,不是我原来那个代码库的延续。它是另一个应用,只是恰好沿用了同一个名字: + +| | 我现在跑的(3.x) | 上游现在的样子 | +|---|---|---| +| 运行时 | Kotlin,Spring Boot + Vert.x | TypeScript,Node | +| 端口 | 8080 | 5888 | +| 数据 | `/storage/data`,按用户存 JSON | `/data`,SQLite(`reader.db`) | +| 配置 | 环境变量 + 每用户 JSON 文件 | 管理后台界面,存进数据库 | +| 镜像 | Docker Hub,命名空间已删除 | `cnb.cool/hectorqin/reader:main` | +| 范围 | 只有书 | 书 **和** 电影、剧集、音乐、有声书、OPDS、OpenList、PWA、Android 客户端 | + +表里有三个细节值得单独拎出来,因为它们各自都有一个后果: + +**镜像仓库搬去了一个大多数人从没拉过东西的平台。** 官方 compose 里写的是 `image: ${READER_IMAGE:-cnb.cool/hectorqin/reader:main}`,旁边一行注释解释了原因:CI 只发布**分支和提交标签,刻意不发布 `:latest`**。也就是说默认配置跟的是一个会动的分支,唯一稳定的引用是一个 commit SHA。 + +**配置离开了环境变量。** 业务设置——HTTP 语音接口、扫描行为、登录有效期、对外 URL、允许的浏览器来源、WebDAV——现在都在管理后台里,持久化进数据库。文档说明:首次升级时「旧版业务环境变量会被导入一次」,并且已存在的数据库值永远优先。这是一次性的导入加一条优先级规则,正是你希望在副本上验证、而不是在线上实例上发现的东西。 + +**HTTP 语音回来了,只是换了个地方。** 新版本重新提供了 HTTP 语音上游的配置:合成 URL、token、voices URL、超时、缓存上限,还有连接测试和试听,全部在管理后台里配。而我的 n8n webhook 实现的协议,是我照着旧版构建自己设计的。这两个形状是否匹配,现在是一个需要用实验回答的问题,不是查文档就能回答的问题。 + +## 没人提醒你的部分:重写版是一个新应用 + +本能反应是把「上游复活了,还多了影音支持和 Android 客户端」读成「我等的升级到了」。并不是。一次重写会同时改变数据格式、部署面和配置模型——这意味着要做的是**一场带 schema 边界的迁移**,而不是 `docker pull` 加一次重启。 + +让我决定慢下来的,是项目自己的进度记录。不要拿厂商的营销页当状态报告,去看它自己写的东西,你会看到作者在列**没做完**的事情: + +- 旧数据**自动迁移和首次接入向导都还没实现**; +- **镜像拉取与真实容器升级演练从未执行过**,因为构建机上没有跑 Docker 引擎。 + +这是一份诚实得罕见的文档,也是整个仓库里最有用的一个文件。重写的作者在告诉我:升级路径写好了,但没人走过。如果连他们都没走过,我当然不会在工作日下午、在我读者正在使用的实例上、在没有数据副本的情况下走去试。 + +## 我现在会把一个依赖交给线上服务之前做的事 + +1. **仓库健康不等于产物健康。** `pushed_at`、star、fork 说明**源码**还活着;对你要跑的那个确切标签执行 `docker pull`,才能说明**你部署的东西**还在。两个都要查,并读一遍 compose 看它到底指向哪个镜像仓库——我这个现在指向一个我本周之前从没打开过的域名。 +2. **「没有 release、没有 tag」是一条部署事实。** 零 tag 意味着每次升级要么写死一个提交哈希,要么跟一个会动的分支。把那个 SHA 记进自己的笔记,上游不会为你记。 +3. **你输不起的东西,就镜像一份——源码和镜像都要。** 一个钉在别人命名空间里的标签,是一种「那个陌生人账号别出事」的依赖。我活下来的 3.x 源码现在在我自己的 Git 服务器上,重写版也是。 +4. **先比形状,再比功能。** 端口、挂载路径、变量名、数据库引擎、配置存放位置。如果这些大多变了,就把它当成一个新产品,按迁移来规划。 +5. **你重建不了的部件,放在你控制不了的镜像之外。** 我的落地页、分享卡片、语言切换和翻译层,是同一条 stack 里的另一个容器。正因为如此,上游这次重写没有打扰到任何一个读者——应用镜像怎么换,都碰不到前门。 +6. **读维护者的「还没做」清单,而不是功能清单。** 功能清单是销售页,未完成清单才是风险登记表。 +7. **如果你把它当成对外服务来跑,读一下许可证。** 这个是 AGPL-3.0,如果你拿它给付费用户提供服务、而不是自己用,值得认真读一遍。 +8. **「仓库被归档或被清空」不等于「项目被放弃」。** 有好几个月,「这个项目死了吗」的诚实答案是「是」——README 就写着 `deleted`,而且它说的是实话。然后有人重新开始了,换了门语言,而诚实的答案在名字不变的情况下变了。 + +## 结果 + +书库在跑,跑在我钉住的那个构建上,读者完全无感——这本来就是目标,而且它一直成立。变的是:「我们被困在一个没人管的镜像上」从一句含糊的担忧,变成了一个有方案的具体问题: + +- 数据目录已复制,新镜像自带的 `backup` / `verify` / `restore` 命令先**对着副本**跑,确认没问题才碰线上卷; +- TTS 协议要拿我现有的 webhook 实测,因为一旦对不上,我丢掉的就是朗读这个功能; +- 旧镜像标签留着做回滚,而且无论走哪条路,源码现在都在我自己的服务器上; +- 前门不在讨论范围内,因为它在另一个容器里,换镜像够不着它。 + +真正有用的教训不是「要钉版本」——那个我早就做了。而是:**「这个项目还活着吗」有三个答案,而它们可以互相矛盾**。仓库可以活着,而镜像已被删除;README 可以写着 `deleted`,而重写版已经开工四周;版本号可以纹丝不动,而运行时、端口、数据库和配置模型在底下全换了一遍。这三件事要分别去查,否则你迟早会为一个「已经不再以你测试过的形态存在」的应用规划升级。 + +--- + +**你在替别人跑自托管服务,但不确定底下的东西还有没有人管?** 这正是我在做的审计:依赖与镜像健康度、升级可行性,以及随之而来的迁移方案。 + +[WhatsApp +60 12-797 2969](https://wa.me/60127972969) · +[me@hoelee.com](mailto:me@hoelee.com?subject=Self-hosted%20dependency%20audit) · +[hoelee.com](https://hoelee.com) +```` + +### 🇬🇧 英文版原文 (English Markdown Primary) +````markdown +--- +title: "The Upstream Was Deleted, Then Came Back as a Rewrite" +description: "My production reading service runs a build whose official Docker Hub repo returns 404. Then upstream came back — 233 commits, a new language, no releases. How to tell dead from rewriting." +pubDate: 2026-10-06 +category: devops +tags: ["docker", "self-hosting", "upstream", "maintenance", "registry"] +ogImage: "/og/the-upstream-was-deleted-then-came-back-rewritten.jpg" +banner: "/banners/the-upstream-was-deleted-then-came-back-rewritten.jpg" +draft: false +--- + +`docker pull hectorqin/reader` returns **404**. That is the project my +production reading service runs on: a small invite-only library I host for +my family and a handful of paying readers, serving books every day, with a +text-to-speech pipeline I built on top of it so the read-aloud button speaks +in proper neural voices. + +The 404 is not the interesting part. On **2026-09-16** that same repository +was re-initialised from scratch — the commit message is `chore: 初始化仓库`, +"initialise repository" — and sixteen days later it carried **233 commits**, +a different language, a different port, a different database engine and a +different container registry. The project I depend on did not die. It was +**replaced by a rewrite** under the same name, the same URL and the same +11,036 stars. + +So: **how do you tell whether an upstream project is dead — and what do you +do when it comes back as a different application?** + +## The setup, because the details are why this mattered + +The app is a self-hosted reading server. Hash-routed Vue SPA in the browser, +Kotlin and Spring Boot on the server, per-user JSON config on disk, and one +feature I had deliberately built a whole pipeline around: **HTTP +text-to-speech**. The reader proxies read-aloud requests to a URL you +configure, so the voices are not baked into the app — mine point at two n8n +webhooks that mint short-lived Azure and Google credentials and synthesise +the audio. Nine engines show up in the voice picker because of that, not +because the app shipped them. + +I also run my own nginx gateway container in front of the app — the public +landing page, the social card, the bilingual switch and an English-UI layer +all live there rather than inside the app's image. That decision, made for +branding reasons, is the reason this whole incident stayed boring. I'll come +back to it. + +## What I found when I went looking for an upgrade + +Three options, and none of them was "upgrade": + +| Option | What it actually is | Why I didn't take it | +|---|---|---| +| The official image | `hectorqin/reader` on Docker Hub | Gone. The repository returns 404; `docker pull` fails | +| The maintained fork | `changshengyu/reader`, pinned at `2.5.4` | Built on the last fully open snapshot. Its read-aloud uses the browser's own `speechSynthesis` only — no HTTP speech. No `httpTTS` string anywhere in its history, and `/reader3/httpTts` 404s on it. My nine engines would vanish | +| A rebuild published by someone else | `liangnianzhi/reader.hectorqin:latest-20250525` | **This is what I run.** The only still-pullable 3.x build that kept HTTP speech. Last updated 2025-09-05, three tags total, published by a user who is not the original author | + +I pinned that tag, tarred up the data directory, and mirrored the source +into my own Git server so the code I depend on existed somewhere I control. +Then I wrote down the one line that decides whether any future image is even +a candidate: **does it still speak the TTS protocol my pipeline +implements?** + +That was the state of things: a running service on an image whose official +home had been deleted, surviving as somebody's rebuild. + +## Then upstream came back + +Verified on 2026-10-06, straight from the GitHub API and the registry: + +| Signal | Value | +|---|---| +| Repo | `hectorqin/reader` — alive, AGPL-3.0, default branch `main` | +| Stars / forks | 11,036 / 5,471 | +| Last push | 2026-10-02 | +| Commits | **233** — and the oldest is `chore: 初始化仓库`, dated **2026-09-16** | +| Releases / tags | **0 / 0** | +| Docker Hub | still **404** | + +The 2021 history is there but disconnected. `main` carries 233 commits and +its oldest is dated 2026-09-16; the old branch survives as a **single commit +dated 2026-06-22** whose message is just `commit`, and whose entire README is +the one word `deleted`. The two branches share **no common ancestor** — which +is what a wipe followed by a fresh start looks like in git. (`created_at` +still reads 2021-08-13, because GitHub keeps that field when a repository is +re-populated; the history is what tells you the truth.) + +And the code behind those 233 commits is not my app's codebase continued. It +is a different application that happens to keep the name: + +| | What I run (3.x) | What upstream is now | +|---|---|---| +| Runtime | Kotlin, Spring Boot + Vert.x | TypeScript, Node | +| Port | 8080 | 5888 | +| Data | `/storage/data`, per-user JSON | `/data`, SQLite (`reader.db`) | +| Configuration | environment variables + per-user JSON files | the admin UI, persisted in the database | +| Container image | Docker Hub, namespace deleted | `cnb.cool/hectorqin/reader:main` | +| Scope | books | books **and** movies, series, music, audiobooks, OPDS, OpenList, PWA, an Android client | + +Three details are worth pulling out of that table, because each one has a +consequence: + +**The registry moved to a platform most of us have never pulled from.** The shipped compose file uses `image: ${READER_IMAGE:-cnb.cool/hectorqin/reader:main}`, and a comment explains that CI publishes **branch and commit tags and deliberately does not publish `:latest`**. So the default configuration tracks a moving branch, and the only stable reference is a commit SHA. + +**Configuration left the environment.** Business settings — the HTTP speech endpoint, scan behaviour, login lifetimes, the public URL, allowed browser origins, WebDAV — now live in the admin UI and persist in the database. The docs note that on first upgrade "legacy business environment variables are imported once", and that existing database values always win. That is a one-shot import with a precedence rule, which is exactly the kind of thing you want to test on a copy instead of discovering on your live instance. + +**HTTP speech came back — in a different place.** The new version documents an HTTP speech upstream again, with a synthesis URL, a token, a voices URL, a timeout and a cache limit, plus a connection test and audio preview, all configured in the admin UI. My n8n webhooks implement a protocol I designed against the old build's expectations. Whether those two shapes match is now an empirical question, not a documentation question. + +## The part nobody warns you about: a rewrite is a new application + +The instinct is to read "upstream is alive again, with media support and an +Android client" as *my upgrade arrived*. It isn't. A rewrite changes the +data format, the deployment surface and the configuration model at the same +time — which means the work is a migration with a schema boundary in it, not +a `docker pull` and a restart. + +What convinced me to slow down was the project's own progress note. Read it +for yourself rather than taking a vendor's marketing page as the status +report, and you find the authors listing what is **not** done: + +- legacy data **auto-migration and a first-run setup wizard are not implemented**; +- the **image pull and the real container upgrade drill were never executed**, because the Docker engine was not running on the build machine. + +That is unusually honest documentation, and it is the single most useful +file in the repository. The people writing the rewrite are telling me the +upgrade path has been written but not walked. If they haven't walked it, I'm +certainly not walking it on the instance my readers are using, on a Tuesday, +without a copy of the data. + +## What I do now, before trusting any dependency with a running service + +1. **Repository health is not artifact health.** `pushed_at`, stars and +forks tell you the *source* is alive. `docker pull` on the exact tag you run +tells you the *thing you deploy* still exists. Check both, and read the +compose file to see which registry it names — mine now points at a domain I +had never opened before this week. 2. **"No releases, no tags" is a +deployment fact.** Zero tags means every upgrade is a commit hash or a +moving branch. Write the SHA in your own notes, because the upstream will +not. 3. **Mirror anything you cannot afford to lose — the source *and* the +image.** A pinned tag in someone else's namespace is a dependency on that +stranger's account staying alive. My surviving 3.x source sits in my own Git +server now, and so does the rewrite. 4. **Compare the shape before the +features.** Port, volume paths, variable names, database engine, where +configuration lives. If most of those moved, treat the new version as a new +product and plan a migration. 5. **Keep what you can't rebuild outside the +image you don't control.** My landing page, social card, language switch and +translation layer are a separate container in the same stack. That is why a +rewrite landing upstream did not disturb a single reader — the front door +cannot be broken by an app image swap. 6. **Read the maintainer's "not done +yet" list, not the feature list.** The feature list is a sales page; the +unfinished list is the risk register. 7. **Check the licence if you run it +as a service.** This one is AGPL-3.0, which is worth reading properly if you +host it for paying users rather than just yourself. 8. **An archived or +wiped repository is not the same as an abandoned project.** For months the +honest answer to "is this project dead?" was yes — the README said `deleted` +and meant it. Then somebody started again, in another language, and the +honest answer changed without the name changing. + +## The result + +The library is up, on the build I pinned, with readers unaffected — that was +always the goal, and it never stopped being true. What changed is that +"we're stranded on an orphaned image" became a known quantity with a plan: + +- the data directory is copied, and the new image's own `backup` / `verify` / `restore` commands get run **against the copy** before anything touches the live volume; +- the TTS protocol gets tested against my existing webhooks, because if it doesn't match, the read-aloud feature is the thing I lose; +- the old image tag stays present for rollback, and I now have the source on my own server either way; +- the front door stays out of scope, because it lives in a different container and an image swap cannot reach it. + +And the useful lesson is not "pin your versions", which I already did. It is +that **the question "is this project alive?" has three answers, and they can +disagree**: the repository can be alive while the image is deleted; the +README can say `deleted` while a rewrite is four weeks into existence; and +the version number can stay the same while the runtime, the port, the +database and the configuration model all change underneath it. Check each +one separately, or you will eventually plan an upgrade for an application +that no longer exists in the shape you tested. + +--- + +**Running a self-hosted app for other people, and not sure whether the thing underneath it is still supported?** That's the kind of audit I do — dependency and image health, upgrade feasibility, and the migration plan that comes with it. + +[WhatsApp +60 12-797 2969](https://wa.me/60127972969) · +[me@hoelee.com](mailto:me@hoelee.com?subject=Self-hosted%20dependency%20audit) +· [hoelee.com](https://hoelee.com) +```` + +--- + +## 文章 06 / 11:Unraid 停止阵列时卡死的真相:Swapfile 锁住挂载点 — 附修复方案 +- **Slug**: `unraid-stop-array-hangs-on-swapfile` +- **英文标题**: Why Unraid Hangs When You Stop the Array With a Swapfile — and the Fix +- **分类**: `devops` | **发布日期**: 2026-09-15 +- **线上地址**: https://blog.hoelee.com/posts/unraid-stop-array-hangs-on-swapfile/ (EN) | https://blog.hoelee.com/posts/zh/unraid-stop-array-hangs-on-swapfile/ (ZH) +- **本篇审核状态**: ⏳ 待审核 (Pending) + +### ✍️ 顾问审阅意见区 (Review Feedback) +```text +【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 +【事实与数字核对】: +【人设与用词卫生】: +【CRO与转化建议】: +``` + +### 🇨🇳 中文版原文 (Chinese Markdown Twin) +````markdown +--- +title: "Unraid 停止阵列时卡死的真相:Swapfile 锁住挂载点 — 附修复方案" +description: "Unraid 停止阵列时一直卡在卸载磁盘:btrfs RAID1 上的 8GB swapfile 通过 loop 设备锁住 /mnt/cache。根因分析、/boot/config/stop 陷阱、两个 User Scripts 彻底修复。" +pubDate: 2026-09-15 +category: devops +blueprint: self-hosted-infrastructure +blueprintLayer: L1-compute-storage-network +tags: [unraid, swap, btrfs, zram, docker, user-scripts] +ogImage: /og/zh-unraid-stop-array-hangs-on-swapfile.jpg +banner: /banners/unraid-stop-array-hangs-on-swapfile.jpg +draft: false +--- + +我给 Unraid 服务器加了 8 GB swapfile。缓存池是 btrfs RAID1,而内核不允许 +swapfile 直接建在多设备 btrfs 文件系统上,所以走了 loop 设备这个标准变通方 +案。Swap 生效了,内存压力降了,一切正常——直到有一天我点了「停止阵列」。 + +WebUI 永远停在 **"Retry unmounting user shares…"**。缓存池就是卸不掉。 +Docker 已停、虚拟机已关、共享已卸载——`umount /mnt/cache` 依然每 5 秒报一 +次 *target is busy*,无限循环。唯一出路是重启。 + +这篇文章讲清楚三件事:为什么会这样;我中途踩的坑(`/boot/config/stop` 在 +你点「停止」时**根本不会运行**);以及两个脚本的修复方案——之后每次停止/启 +动都干净利落。 + +## 问题本身(按你会搜索的方式来描述) + +如果你是搜索进来的,你大概率在搜: + +- *"unraid stop array stuck retry unmounting user shares"* +- *"umount /mnt/cache target is busy unraid"* +- *"unraid swapfile stop array hang"* +- *"unraid 停止阵列 卡住"* + +同一个 bug。一句话版本:**swapfile(或它的 loop 设备)被内核 swap 子系统 +持有打开,而 Unraid 的停止阵列流程里没有任何一步会先关掉 swap 再卸载磁 +盘。** 挂载点忙,是因为内核自己在用它——除非有人执行 `swapoff`,否则它会 +一直用下去。而没有人执行。 + +## 我试过的方案,以及为什么都失败 + +### 尝试 1:重启后再停阵列——照样卡死 + +意料之中。swapfile 配置在 `/boot/config/go` 里,每次开机都会重建 loop 设 +备并启用 swap,每次停止都撞同一堵墙。至少这证明了问题是确定性的,不是偶 +发进程卡住。 + +### 尝试 2:在 `/boot/config/stop` 里写 `swapoff` + +这是最经典的陷阱,Unraid 官方文档让它看起来就是正确答案。`stop` 脚本的存 +在意义就是「磁盘卸载前跑清理」——它确实会运行,**但只在完整关机或重启 +时**。 + +我在自己的机器上验证过(Unraid 7.1.4):`/boot/config/stop` 由 +`rc.local_shutdown` 调用,而后者在 `rc.6` 里。在 WebUI 点**停止**走的是完 +全不同的路径——`emhttpd` 触发一系列 *event*——`rc.6` 根本不参与。没有关 +机,就没有 `stop` 脚本,就没有 `swapoff`。阵列停止照样卡死。 + +### 尝试 3:搞清楚 GUI「停止」到底做了什么 + +真正的答案在这里。Unraid 的事件调度器(`emhttp_event`)在阵列停止时按文 +档化顺序执行钩子脚本: + +```text +stopping → stopping_libvirt → stopping_docker → stopping_svcs + → unmounting_disks → stopping_array → stopped +``` + +两个关键事实: + +1. 卸载发生在 `unmounting_disks`。**任何 swapoff 必须在 `stopping_svcs` + 或更早触发**——比卸载早一个事件。 +2. 这些事件正是 **User Scripts** 插件暴露出来的调度选项(「At Stopping of + Array」= `stopping_svcs`,「At First Array Start only」= + `disks_mounted`)。不需要写新代码——自动化接口本来就在那里。 + +### 隐蔽的部分:`/proc/swaps` 对 loop swap 说谎 + +这是让「看起来正确」的清理脚本也会失败的坑。我的 `/boot/config/go` 原来 +是这样配置 swap 的(btrfs RAID1 标准写法): + +```bash +# /boot/config/go — 原始(停止时会卡的)配置 +mkdir -p /mnt/cache +MOUNTPOINT=/mnt/cache +SWAPFILE=${MOUNTPOINT}/swapfile + +# 等待缓存池挂载 +while [ ! -f "${SWAPFILE}" ]; do + sleep 1 +done + +# btrfs RAID1 拒绝直接 swapfile:loop 设备 + NOCOW +chattr +C "${SWAPFILE}" +LOOPDEV=$(losetup -f) +losetup -p 100 "${LOOPDEV}" "${SWAPFILE}" +swapon -p 1 "${LOOPDEV}" +``` + +现在看内核在活动状态下报告的内容: + +```console +$ cat /proc/swaps +Filename Type Size Used Priority +/dev/loop0 partition 8388604 0 -2 + +$ swapon --show +NAME TYPE SIZE USED PRIO +/dev/loop0 partition 8G 0B -2 +``` + +**文件名是 `/dev/loop0`,不是 `/mnt/cache/swapfile`。** 所以这样的清理脚 +本: + +```bash +# 错误 — 对 loop swap 静默失效 +grep -q '/mnt/cache/swapfile' /proc/swaps && swapoff /mnt/cache/swapfile +``` + +……什么都匹配不到,什么都关不掉,然后你又一次卡在停止阵列。必须*先*解析 +loop 设备——`losetup -j <文件>` 就是干这个的——再 `swapoff` 那个 loop 设 +备,最后卸载它。ZRAM Compressed Memory 插件的源码注释几乎一字不差地记录 +了同一个 bug:*"for loop-backed swap, /proc/swaps lists /dev/loopN, not +the image path — a plain grep never matches, so swapoff never ran and the +loop device kept the pool busy forever."*(loop 型 swap 在 /proc/swaps 里显 +示为 /dev/loopN 而不是镜像路径——普通 grep 永远匹配不到,swapoff 从未执 +行,loop 设备让缓存池永远忙碌。) + +## 修复方案:两个 User Scripts + +大多数 Unraid 机器已经装了 [User +Scripts](https://forums.unraid.net/topic/48286-plugin-ca-user-scripts/) +插件。创建两个脚本: + +**脚本 1 —「Array Stop Swapoff」**——调度选 **At Stopping of Array**(在 +`stopping_svcs` 触发,比卸载早一个事件): + +```bash +#!/bin/bash +# 先释放所有 swap,再只卸载【我们的】swapfile 背后的 loop 设备。 +swapoff -a 2>/dev/null +for l in $(losetup -j /mnt/cache/swapfile 2>/dev/null | awk -F: '{print $1}'); do + losetup -d "$l" 2>/dev/null +done +``` + +`losetup -j`(「哪个 loop 设备挂在这个文件上?」)是关键一步——它不受 +`/proc/swaps` 命名谎言的影响。而且只卸载*我们自己的* loop 设备很重要:机 +器上可能还有别的 loop 设备(挂载的 ISO、其他镜像),它们必须在停止阵列时 +存活下来。 + +**脚本 2 —「Array Start Swapon」**——调度选 **At First Array Start +only**(在 `disks_mounted` 触发): + +```bash +#!/bin/bash +# 缓存池挂载后重建 loop swap。 +[ -f /mnt/cache/swapfile ] || exit 0 +LOOP=$(losetup -f) +losetup -p 100 "$LOOP" /mnt/cache/swapfile && swapon -p 1 "$LOOP" +``` + +为什么选「First Array Start only」而不是普通的「At Startup of the +Array」?因为开机时 `/boot/config/go` 也会运行并配置一次 swap。开机后的 +*第一次*阵列启动由 `go` 负责;这个脚本真正管的是**不重启、纯 GUI 停止 → +启动的循环**——而 `go` 永远看不到这种场景。(在我的配置里,我把 swap 那段 +从 `go` 里整个移除了,让 User Script 成为唯一事实来源——一处配置,两条路 +径都覆盖。) + +之后:停止 → 缓存池第一次尝试就干净卸载。启动 → swap 恢复。多次停止/启动 +循环和重启后都验证通过。 + +## 我会做得不一样的地方 + +**1. 不要把 swap 放在已经快死的盘上。** 我的缓存池是一对后来确认在静默损 +坏数据的 NVMe(SMART 全绿,读取却返回全零块)。8 GB swapfile 放在那里意 +味着对我即将更换的硬件持续写入磨损——而且它正是在迁移期间卡住我阵列停止 +的元凶。swap 的位置要匹配磁盘健康状况,而不是图方便。 + +**2. CPU 够用时,压缩内存 swap 优于磁盘 swap。** 这台机器的最终方案是 +[ZRAM Compressed +Memory](https://forums.unraid.net/topic/196763-new-plugin-created-zram/) +插件:Tier-1 swap 放在 zstd 压缩的 RAM 块设备里。两个好处: + +- **卡死在结构上变得不可能。** zram 设备不是挂载点,`umount /mnt/cache` + 永远看不见它,停止时无需释放任何东西。(如果你启用它的 Tier-2 磁盘 + swapfile,插件也自带正确的 `event/stopping` 钩子,用的正是 + `losetup -j` 这个修复。) +- **swap 换入换出是微秒级 CPU 操作而不是磁盘 I/O**——在现代多核 CPU 上, + 压缩相对 NVMe 延迟几乎免费,而且被换出的页面在 RAM 里省约 3:1 空间。 + +一个我用惨痛教训学到的注意事项:插件的自动大小(RAM 的 50%)在我 62 GB +内存、已用 90% 的机器上给了一个 **31.3 GB** 的 zram 设备。那个数字是*未压 +缩上限*——实际 RAM 消耗 = 容量 ÷ 压缩比,所以装满的 31.3 GB zram 可能吃掉 +10–30 GB 我本来就稀缺的空闲内存。在接近满载的机器上,zram 要固定且保守地 +设置大小(我改成 8 GB——原来 swapfile 的大小——swappiness 150),让它缓冲 +OOM 而不是和 OOM 抢内存。 + +**3. swap 只能推迟 OOM,治不了 OOM。** 我内存压力的诚实根因是虚拟机内存 +分配,不是缺 swapfile。swap 买来了余量、让宿主机在峰值时活了下来——但真正 +的修复是给虚拟机合理分配内存。 + +## 结果 + +停止阵列从「永远卡死、强制重启」变成「第一次尝试就干净卸载」,swap 在停止/ +启动循环之间自动存活,无需人工干预。修复总量:两个 shell 脚本,跑在一个早 +就装好的插件里。贵的部分是知道该把它们放在事件序列的**哪个位置**——以及 +`/proc/swaps` 不会告诉你 loop swap 的真相。 + +如果你的 Unraid 阵列拒绝停止,而你配置过任何形式的 swap——文件、loop 或其 +他——在 root shell 里执行 `swapoff -a` 会立刻释放它,诊断就此确认。然后在 +下次重启抹掉你的记忆之前,把它自动化。 + +--- + +*你也有需要这种深度调试的自托管环境吗——Unraid、Docker、反向代理、NAS 迁 +移?这是我的本行:[网站设计与开发](https://hoelee.com)是主业,自托管基础 +设施是我钻研最深的领域。欢迎通过 +[WhatsApp](https://wa.me/60127972969) 或 +[邮件](mailto:me@hoelee.com?subject=Unraid%20infrastructure%20help)联系 +我。* +```` + +### 🇬🇧 英文版原文 (English Markdown Primary) +````markdown +--- +title: "Why Unraid Hangs When You Stop the Array With a Swapfile — and the Fix" +description: "My Unraid array stop hung forever at unmounting disks because an 8 GB btrfs swapfile pinned /mnt/cache. Root cause, the /boot/config/stop trap, and two User Scripts that fix it." +pubDate: 2026-09-15 +category: devops +blueprint: self-hosted-infrastructure +blueprintLayer: L1-compute-storage-network +tags: [unraid, swap, btrfs, zram, docker, user-scripts] +ogImage: /og/unraid-stop-array-hangs-on-swapfile.jpg +banner: /banners/unraid-stop-array-hangs-on-swapfile.jpg +draft: false +--- + +I added an 8 GB swapfile to my Unraid server — my cache pool is a btrfs RAID1, +and the kernel refuses a swapfile that lives directly on a multi-device btrfs +filesystem, so it goes through a loop device, the standard workaround. Swap +worked. Memory pressure dropped. Everything was fine… until the day I stopped +the array. + +The WebUI sat on **"Retry unmounting user shares…"** forever. The cache pool +would not release. Docker was stopped, VMs were shut down, shares were +unmounted — and still, `umount /mnt/cache` failed with *target is busy*, +every five seconds, indefinitely. The only way out was a reboot. + +This is the story of finding out why, the trap I fell into on the way +(`/boot/config/stop` does **not** run when you click Stop), and the two-script +fix that survives every stop/start cycle since. + +## The problem, phrased the way you'd Google it + +If you landed here from a search, you're probably typing one of these: + +- *"unraid stop array stuck retry unmounting user shares"* +- *"umount /mnt/cache target is busy unraid"* +- *"unraid swapfile stop array hang"* +- *"unraid won't stop array after adding swap"* + +Same bug. The short version: **a swapfile — or its loop device — is held open +by the kernel's swap subsystem, and Unraid's array-stop sequence has no step +that turns swap off before it unmounts disks.** The mount is busy because the +kernel itself is using it, and it will keep using it until someone runs +`swapoff`. Nobody does. + +## What I tried, and why it failed + +### Attempt 1: reboot, stop array again — hung again + +Obviously. The swapfile was still configured in `/boot/config/go`, so every +boot recreated the loop device and enabled swap on it. Every stop hit the same +wall. At least this confirmed it was deterministic, not a one-off stuck +process. + +### Attempt 2: put a `swapoff` in `/boot/config/stop` + +This is the classic trap, and the Unraid docs make it look like the right +answer. The `stop` script exists precisely for "run cleanup before disks go +away" — and it does run, **but only during a full shutdown or reboot**. + +I checked on my own box (Unraid 7.1.4): `/boot/config/stop` is invoked by +`rc.local_shutdown`, which is called from `rc.6`. Clicking **Stop** in the +WebUI goes through a completely different path — `emhttpd` fires a series of +*events* — and `rc.6` is never involved. No shutdown, no `stop` script, no +`swapoff`. The array stop still hung. + +### Attempt 3: read what the GUI Stop actually does + +This is where the real answer lives. Unraid's event dispatcher (`emhttp_event`) +runs hook scripts in a documented sequence when the array stops: + +```text +stopping → stopping_libvirt → stopping_docker → stopping_svcs + → unmounting_disks → stopping_array → stopped +``` + +Two facts matter: + +1. The unmount happens at `unmounting_disks`. **Any swapoff must fire at + `stopping_svcs` or earlier** — one event before the unmount. +2. These events are exactly what the **User Scripts** plugin exposes as + schedule options ("At Stopping of Array" = `stopping_svcs`, "At Startup of + the array" / "At First Array Start only" = `array_started` / + `disks_mounted`). No new code needed — the automation surface already + exists. + +### The subtle part: `/proc/swaps` lies about loop-backed swap + +Here's the gotcha that makes even a "correct-looking" cleanup script fail. +My `/boot/config/go` set swap up like this (the standard btrfs-RAID1 recipe): + +```bash +# /boot/config/go — the original (broken-on-stop) setup +mkdir -p /mnt/cache +MOUNTPOINT=/mnt/cache +SWAPFILE=${MOUNTPOINT}/swapfile + +# Wait for the cache pool to be mounted +while [ ! -f "${SWAPFILE}" ]; do + sleep 1 +done + +# Btrfs RAID1 rejects direct swapfiles: loop device + NOCOW +chattr +C "${SWAPFILE}" +LOOPDEV=$(losetup -f) +losetup -p 100 "${LOOPDEV}" "${SWAPFILE}" +swapon -p 1 "${LOOPDEV}" +``` + +Now look at what the kernel reports while that's active: + +```console +$ cat /proc/swaps +Filename Type Size Used Priority +/dev/loop0 partition 8388604 0 -2 + +$ swapon --show +NAME TYPE SIZE USED PRIO +/dev/loop0 partition 8G 0B -2 +``` + +**The filename is `/dev/loop0`, not `/mnt/cache/swapfile`.** So a cleanup +script like this one: + +```bash +# WRONG — silently does nothing for loop-backed swap +grep -q '/mnt/cache/swapfile' /proc/swaps && swapoff /mnt/cache/swapfile +``` + +…matches nothing, swaps nothing off, and you're back to the hang. You have to +resolve the loop device *first* — `losetup -j ` does exactly that — then +`swapoff` the loop device, then detach it. The ZRAM Compressed Memory plugin +documents this same bug in its source comment, almost word for word: *"for +loop-backed swap, /proc/swaps lists /dev/loopN, not the image path — a plain +grep never matches, so swapoff never ran and the loop device kept the pool +busy forever."* + +## The fix: two User Scripts + +[User Scripts](https://forums.unraid.net/topic/48286-plugin-ca-user-scripts/) +is already installed on most Unraid boxes. Create two scripts: + +**Script 1 — "Array Stop Swapoff"** — schedule: **At Stopping of Array** +(fires at `stopping_svcs`, one event before the unmount): + +```bash +#!/bin/bash +# Release ALL swap, then detach only the loop device backing OUR swapfile. +swapoff -a 2>/dev/null +for l in $(losetup -j /mnt/cache/swapfile 2>/dev/null | awk -F: '{print $1}'); do + losetup -d "$l" 2>/dev/null +done +``` + +`losetup -j` ("which loop device is attached to this file?") is the key move — +it's immune to the `/proc/swaps` naming lie. And detaching *only* our loop +device matters: a box can have other loop devices (mounted ISOs, other images) +that must survive an array stop. + +**Script 2 — "Array Start Swapon"** — schedule: **At First Array Start only** +(fires at `disks_mounted`): + +```bash +#!/bin/bash +# Re-create the loop-backed swap after the cache pool mounts. +[ -f /mnt/cache/swapfile ] || exit 0 +LOOP=$(losetup -f) +losetup -p 100 "$LOOP" /mnt/cache/swapfile && swapon -p 1 "$LOOP" +``` + +Why "First Array Start only" and not plain "At Startup of the Array"? Because +`/boot/config/go` also runs at boot and would set swap up a second time. The +*first* array start after boot is covered by `go`; this script matters for the +**GUI stop → start cycle with no reboot in between** — which `go` never sees. +(In my setup I moved the swap block out of `go` entirely so the User Script is +the single source of truth — one place, both paths.) + +After this: Stop → cache unmounts cleanly on the first try. Start → swap is +back. Verified across multiple stop/start cycles and reboots. + +## What I'd do differently + +**1. Don't put swap on a disk that's already dying.** My cache pool is a pair +of NVMe drives I've since confirmed are silently corrupting data (reads +returning all-zero blocks despite clean SMART). An 8 GB swapfile there meant +constant write wear on hardware I was about to replace — and it was the very +thing pinching my array stops during the migration. Match swap location to +disk health, not convenience. + +**2. Prefer compressed RAM over disk swap when you have the CPU for it.** The +endgame on this box was the [ZRAM Compressed +Memory](https://forums.unraid.net/topic/196763-new-plugin-created-zram/) +plugin: Tier-1 swap lives in a zstd-compressed RAM-backed block device. Two +wins: + +- **The hang becomes structurally impossible.** A zram device is not a mount. + `umount /mnt/cache` can never see it, so there's nothing to release at stop + time. (The plugin *also* ships a proper `event/stopping` hook with the + `losetup -j` fix, if you enable its Tier-2 disk swapfile.) +- **Swap-in/out is microseconds of CPU work instead of disk I/O** — on a + modern many-core CPU, compression is nearly free relative to even NVMe + latency, and you save ~3:1 on the RAM the swapped pages occupy. + +One caveat I learned the hard way: the plugin's auto-size (50% of RAM) gave me +a **31.3 GB** zram device on a 62 GB host that was already 90% full. That +number is an *uncompressed ceiling* — real RAM cost is capacity ÷ compression +ratio, so a full 31.3 GB zram could eat 10–30 GB of the very RAM I was short +of. On a nearly-full host, size zram fixed and modest (I went to 8 GB, the old +swapfile size, swappiness 150) so it buffers OOM instead of competing with it. + +**3. Swap delays OOM; it doesn't cure it.** The honest root cause of my memory +pressure was VM RAM budgets, not a missing swapfile. Swap bought headroom and +kept the host alive during spikes — but the real fix was right-sizing guests. + +## The result + +Array stop went from *"hangs forever, forced reboot"* to *clean unmount on the +first attempt*, and swap now survives stop/start cycles without manual +intervention. Total fix: two shell scripts in a plugin that was already +installed. The expensive part was knowing **where** in the event sequence to +put them — and that `/proc/swaps` won't tell you the truth about loop-backed +swap. + +If your Unraid array refuses to stop and you have any swap configured — file, +loop, or otherwise — `swapoff -a` from a root shell will release it +immediately, and you've confirmed the diagnosis. Then automate it before the +next reboot wipes your memory of how. + +--- + +*Run a self-hosted stack that needs this kind of debugging — Unraid, Docker, +reverse proxies, NAS migrations? I do this for a living: [website design & +development](https://hoelee.com) is my main work, and self-hosted +infrastructure is where I go deep. Reach me on +[WhatsApp](https://wa.me/60127972969) or +[email](mailto:me@hoelee.com?subject=Unraid%20infrastructure%20help).* +```` + +--- + +## 文章 07 / 11:用 CDP 自动化上传百兆视频到 YouTube:跨越 DevTools 内存墙的 Docker 归档法 +- **Slug**: `uploading-large-videos-to-youtube-via-cdp` +- **英文标题**: Uploading 100MB+ Videos to YouTube via CDP: The Docker Archive Pattern +- **分类**: `devops` | **发布日期**: 2025-08-22 +- **线上地址**: https://blog.hoelee.com/posts/uploading-large-videos-to-youtube-via-cdp/ (EN) | https://blog.hoelee.com/posts/zh/uploading-large-videos-to-youtube-via-cdp/ (ZH) +- **本篇审核状态**: ⏳ 待审核 (Pending) + +### ✍️ 顾问审阅意见区 (Review Feedback) +```text +【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 +【事实与数字核对】: +【人设与用词卫生】: +【CRO与转化建议】: +``` + +### 🇨🇳 中文版原文 (Chinese Markdown Twin) +````markdown +--- +title: "用 CDP 自动化上传百兆视频到 YouTube:跨越 DevTools 内存墙的 Docker 归档法" +description: "了解如何使用 Docker Archive API 将大型视频直接送入容器文件系统,再通过 CDP 秒级挂载,彻底避免将百兆文件经由 WebSocket 慢速传输挤爆浏览器。" +pubDate: 2025-08-22 +updatedDate: 2026-10-22 +category: devops +tags: ["docker", "cdp", "playwright", "youtube", "portainer", "automation"] +ogImage: "/og/zh-uploading-large-videos-to-youtube-via-cdp.jpg" +banner: "/banners/uploading-large-videos-to-youtube-via-cdp.jpg" +draft: false +--- + +在前端自动化与爬虫开发中,通过无头浏览器或 Chrome DevTools Protocol(CDP)来提交表单、抓取数据或上传几百 KB 的图片通常十分顺畅。然而,当你试图在自动化流程中将一个 100MB 以上的高清 1080P 视频通过远程 CDP 自动上传到 YouTube 时,常规的浏览器自动化方案几乎一定会崩溃。 + +本文记录这个让远程自动化频繁掉线的内存陷阱,以及如何通过轻量优雅的 Docker 归档模式(Docker Archive Pattern)实现百兆大视频的稳定秒级注入。 + +> **TL;DR** —— 不要把上百兆字节塞进 CDP 的 WebSocket。Docker Engine API 的 `PUT /containers/{id}/archive?path=…`(这里走 Portainer)把文件打成 tar 直接解进 Chrome 容器的文件系统,再用 `DOM.setFileInputFiles` 把**容器内路径**交给网页。千兆局域网下 130 MB 落盘 1.89 秒。这一篇是 [全自动 MV 生成流水线](/posts/zh/how-i-built-an-automated-music-video-pipeline/) 的落盘那一半;渲染层相关的转场与低频抽动排查见 [排查 Remotion 视频抽搐](/posts/zh/debugging-remotion-video-jitter/)。 + +--- + +## 1. 什么时候该用哪种文件上传方案 + +在动手写代码前,先理清四种常见方案的适用边界: + +| 方案 | 适合场景 | 权衡与取舍 | +|---|---|---| +| **Playwright `setInputFiles()`** | 同一台机器上的本地 Chrome 实例 | 挂接系统原生文件选择器。跨远程 WebSocket 传输大文件极易内存溢出或超时。 | +| **CDP `DOM.setFileInputFiles`** | 文件已经存在于 Chrome 宿主机/容器内部 | 耗时仅 2 毫秒,网络零内存开销,但本身不具备跨机器传文件的能力。 | +| **Docker Archive API (`/archive`)** | 把文件注入已有容器,免配 SSH/NFS/卷挂载 | 原生 tar 流式导入,快速自包含,适合带外落盘。 | +| **YouTube Data API v3** | 后台纯无头服务,拥有 Google Cloud 服务凭据 | 支持官方断点续传,但每日免费配额极紧(每次上传消耗 1600 单位,每天最多传 6 个视频),且很多 YouTube Studio 独占设置(如特定多语种 CC 字幕、音频轨道)API 无法完全覆盖。 | + +### 为什么这里选择 CDP 而不是官方 Data API? +YouTube Data API 默认每天只有 10,000 单位配额,上传一个视频扣除 1,600 单位,一天上传 6 个视频就会触发限流配额耗尽。此外,官方 API 对外挂多语种字幕的授权和上传要求频繁更新的 OAuth2 授权圈子。在已有登录态的自托管 Chrome 容器中通过 CDP 驱动,不仅零配额限制,还能 100% 保持与人工在 YouTube Studio 点击完全一致的行为体验。 + +--- + +## 2. 50MB 远程浏览器协议陷阱 + +在控制本地 Chrome 时,Playwright 或 Puppeteer 使用 `page.setInputFiles("input[type=file]", local_path)`。浏览器直接从当前机器的物理磁盘中读取文件句柄,操作极其平稳。 + +但在自托管私有基础设施或生产部署中,为了让 YouTube、电商等带有登录态的账号 7x24 小时保持在线且不污染日常桌面,我们通常将 Chrome 运行在 Synology NAS 或 Linux 服务器的 Docker 容器中。 + +当我们在外部工作站或 CI 流水线上运行脚本,试图跨网络通过远程 CDP 将视频推给容器里的浏览器时,问题接踵而至: +1. Playwright 会尝试通过 WebSocket 协议将巨大的二进制文件转为 Base64 或分片推流; +2. 庞大的数据帧直接挤爆 WebSocket 协议栈缓冲区,两端内存激增; +3. 远程浏览器随之报出 `Target closed` 崩溃退出,或者由于帧超时直接断开连接。 + +即使你费尽心思调大 WebSocket 参数,跨协议在网络上传输上百兆视频依然极其脆弱。 + +--- + +## 3. 破局思路:本地文件路径直接注入 + +核心思路的转变其实非常直观:**如果视频文件本身就已经保存在容器内部的磁盘里,Chrome 根本不需要走 WebSocket 网络把数据传过来。** + +当 `/config/Downloads/video.mp4` 已经落在容器文件系统内时,CDP 提供了一个原生且完全不消耗协议内存的底层指令: + +```python +cdp = context.new_cdp_session(page) +doc = cdp.send("DOM.getDocument") +file_node = cdp.send("DOM.querySelector", { + "nodeId": doc["root"]["nodeId"], + "selector": "input[type='file']", +}) + +# 耗时仅需 2 毫秒,且在浏览器 WebSocket 上传输 0 字节: +cdp.send("DOM.setFileInputFiles", { + "files": ["/config/Downloads/video.mp4"], + "nodeId": file_node["nodeId"], +}) +``` + +于是,真正的工程问题转变为:**如何无需繁琐的 SSH 密钥或挂载庞大卷,就能将一个 130MB 的文件在 2 秒内送入容器内部?** + +--- + +## 4. Portainer Docker Archive 归档注入法(生产强化版实现) + +每个 Docker 守护进程原生暴露了一个容器归档接口: +`PUT /containers/{id}/archive?path=/path/in/container` + +在 Synology NAS 或 unRaid 环境下,Portainer 会将此 Docker socket API 封装在统一的 API Key 鉴权之后: + +`PUT http://:9000/api/endpoints/2/docker/containers/{container_id}/archive?path=/config/Downloads` + +以下是带有完整异常捕获、入参校验与安全权限的生产级 Python 脚本: + +```python +import io +import os +import tarfile +import urllib.error +import urllib.request + +PORTAINER_KEY = os.environ.get("PORTAINER_API_KEY", "") +PORTAINER_BASE = "http://192.168.1.1:9000/api/endpoints/2/docker" +CONTAINER_ID = "2dc0fb6a11c7" # 目标 Chrome 容器 ID + +def stage_file_to_container(local_path: str, dest_filename: str) -> None: + if not PORTAINER_KEY: + raise ValueError("未检测到 PORTAINER_API_KEY 环境变量") + if not os.path.exists(local_path): + raise FileNotFoundError(f"本地文件不存在: {local_path}") + + size = os.path.getsize(local_path) + tar_stream = io.BytesIO() + + # 在内存中打包 tar(对于拥有 16GB+ RAM 的工作站,100-200MB 媒体文件完全安全可控) + with tarfile.open(fileobj=tar_stream, mode="w") as tar: + with open(local_path, "rb") as f: + ti = tarfile.TarInfo(name=dest_filename) + ti.size = size + # 0o644:文件属主可读写,其他组只读(严禁赋予全局可写 0o666/0o777) + ti.mode = 0o644 + tar.addfile(ti, f) + + tar_stream.seek(0) + data = tar_stream.read() + + endpoint = f"{PORTAINER_BASE}/containers/{CONTAINER_ID}/archive?path=/config/Downloads" + req = urllib.request.Request( + endpoint, + data=data, + headers={ + "X-Api-Key": PORTAINER_KEY, + "Content-Type": "application/x-tar", + }, + method="PUT", + ) + + try: + with urllib.request.urlopen(req, timeout=120) as resp: + if resp.status not in (200, 204): + raise RuntimeError(f"Archive PUT 请求失败,HTTP 状态码: {resp.status}") + print(f"成功将 {dest_filename} ({size / (1024 * 1024):.2f} MB) 注入容器!") + except urllib.error.HTTPError as e: + body = e.read().decode("utf-8", errors="replace") + raise RuntimeError(f"Portainer 接口返回错误 {e.code}: {body}") from e +``` + +### 运维注意事项与安全清单 +1. **客户端 RAM 内存开销**:虽然 Chrome 端彻底消除了内存尖刺,但 `io.BytesIO()` 会在当前 Python 脚本进程中驻留整份 tar 镜像。如果要处理数 GB 的大型视频归档,应先将 `.tar` 写入临时文件,并通过 `requests` 或 `urllib3` 以流式分块形式上传。 +2. **目标目录必须预先存在**:Docker Archive API 是直接解包到 `?path=` 指向的目录中。如果目标容器内部缺失 `/config/Downloads` 目录,接口会直接返回 404/500,而不会自动创建父级目录。 +3. **API Key 与 CDP 端口暴露风险**:Portainer API Key 与未鉴权的 Chrome DevTools 端口(默认 `9222` 或 `9242`)都拥有宿主或容器等效的最高执行权限。切勿将这两个端口直接映射到公网 IP(`0.0.0.0`),务必严格限制在内网隔离桥或套在双向 TLS / Authentik SSO 之后。 + +### 实测性能读数 +在千兆局域网环境下实测: +- **128.85 MB 视频成片(.mp4)**:从发起请求到容器解包就绪,耗时 **1.89 秒**(固态硬盘存储); +- **Chrome 容器内存占用**:所有浏览器标签页均观察不到额外内存峰值; +- **WebSocket 流量**:DevTools 协议通道 0 字节负载。 + +--- + +## 5. YouTube Studio 上传流程自动化 + +当视频和自定义封面都已安静地躺在容器内部的 `/config/Downloads/` 下,Playwright 只需要通过 CDP 驱动页面向导: + +1. **挂载主视频**:获取主上传框 `input[type='file']`,调用 `DOM.setFileInputFiles` 传入容器视频路径; +2. **填充标题与描述**:定位 contenteditable 输入区域,自动输入预生成的 SEO 标题与详细简介; +3. **挂载封面缩略图**:通过 `DOM.getDocument` 重新拉取动态注入的 DOM 树,获取 `input[type='file']#file-loader` 节点,挂载 `/config/Downloads/cover.jpg`; +4. **受众选择**:勾选 `VIDEO_MADE_FOR_KIDS_NOT_MFK`; +5. **跳过向导检查**:连续点击 `#next-button` 进入发布选项; +6. **公开可见性与发布**:选中 `PUBLIC`,点击 `#done-button` 即可完成发布。 + +因为文件在容器磁盘上本地可读,YouTube Studio 以最饱满的网络带宽直推谷歌服务器,全程无一次断流或卡顿。 + +--- + +## 6. 核心总结 + +- **严禁在 CDP 的 WebSocket 通道传输大型文件**:远程浏览器不是为了在内存中缓冲几百兆媒体流而设计的; +- **带外落盘先行**:使用 Docker Archive PUT 接口,利用 Docker 原生机制以极高速度直接将文件推入容器文件系统; +- **容器内部路径秒挂载**:通过 CDP 的 `DOM.setFileInputFiles` 直接指定容器路径,实现零内存损耗、零失败率的文件绑定。 +```` + +### 🇬🇧 英文版原文 (English Markdown Primary) +````markdown +--- +title: "Uploading 100MB+ Videos to YouTube via CDP: The Docker Archive Pattern" +description: "Learn how to stage large video files inside a Dockerized Chrome container using the Docker Archive API, then attach them through CDP without sending the entire file over the browser WebSocket." +pubDate: 2025-08-22 +updatedDate: 2026-10-22 +category: devops +tags: ["docker", "cdp", "playwright", "youtube", "portainer", "automation"] +ogImage: "/og/uploading-large-videos-to-youtube-via-cdp.jpg" +banner: "/banners/uploading-large-videos-to-youtube-via-cdp.jpg" +draft: false +--- + +Automating web uploads via headless browser or Chrome DevTools Protocol (CDP) works seamlessly for small JSON payloads, forms, and occasional screenshots. But when you attempt to upload a 100MB+ 1080p video file to YouTube through a remote browser session, standard browser automation approaches quickly collapse. + +Here is the exact trap that breaks remote CDP uploads, why browser memory limits fight you, and the lightweight Docker Archive pattern that makes large-file uploads rock-solid. + +> **TL;DR** — Do not push megabytes through the CDP WebSocket. `PUT /containers/{id}/archive?path=…` on the Docker Engine API (here via Portainer) tars the file straight into the Chrome container's filesystem, then `DOM.setFileInputFiles` hands the *container path* to the page input. 130 MB staged in 1.89 s on a gigabit LAN. This is the staging half of our [music-video pipeline](/posts/how-i-built-an-automated-music-video-pipeline/); the rendering and visual transition tuning is covered in [debugging Remotion video jitter](/posts/debugging-remotion-video-jitter/). + +--- + +## 1. When to Use Which File-Upload Strategy + +Before jumping into implementation, it helps to understand where each upload technique belongs: + +| Method | Best For | Trade-offs | +|---|---|---| +| **Playwright `setInputFiles()`** | Local Chrome instances on the same host | Native OS picker hook. Fails or spikes memory over remote WebSockets. | +| **CDP `DOM.setFileInputFiles`** | Files already on the Chrome host's filesystem | Instantaneous (2ms), zero network memory overhead, but cannot move files across machines. | +| **Docker Archive API (`/archive`)** | Staging files into an existing remote container without SSH/NFS | Direct tar stream to Docker daemon; fast and self-contained. | +| **YouTube Data API v3** | Headless backend services with Google Cloud credentials | Direct resumable uploads, but daily quota limits are tight (1600 units per upload = 6 videos/day max on free tier) and cannot access newer YouTube Studio features (custom audio tracks, specific CC localization workflows). | + +### Why CDP Over YouTube Data API? +YouTube's official Data API imposes a 10,000-unit daily default quota limit. A single video upload consumes 1,600 units, meaning you hit quota exhaustion after just 6 videos a day. Furthermore, uploading multi-language `.srt` tracks and custom video localization through the Data API requires complex OAuth2 consent scopes that expire frequently. + +By driving an already-authenticated Chrome instance in Docker via CDP, we operate under standard browser sessions with zero quota walls. + +--- + +## 2. The 50MB Remote Browser Pitfall + +When controlling a local Chrome instance, Playwright or Puppeteer attaches files using `page.setInputFiles("input[type=file]", local_path)`. The browser reads the file from your local disk and passes the handle directly to the OS file picker. + +However, in a self-hosted on-premise or production setup, you frequently run Chrome inside an isolated Docker container on a NAS or server to keep your authenticated session alive 24/7 without exposing your daily desktop. + +When your automation script runs on a different workstation or runner and tries to push a video over a remote CDP connection: +1. Playwright attempts to base64-encode or stream the file buffer over the WebSocket protocol. +2. The WebSocket frame exceeds protocol buffers or consumes massive memory on both ends. +3. The remote browser crashes with `Target closed`, or CDP drops the socket due to frame size timeouts. + +Even if you increase the WebSocket chunk size, pushing a 130MB file over CDP is excruciatingly slow and fragile. + +--- + +## 3. The Reframe: Local File Injection + +The key realization is simple: **Chrome inside the container doesn't need the file pushed over the wire if the file already exists on its internal filesystem.** + +If the file `/config/Downloads/video.mp4` already sits inside the container, CDP provides a native, zero-memory command that requires no file transfer at all: + +```python +cdp = context.new_cdp_session(page) +doc = cdp.send("DOM.getDocument") +file_node = cdp.send("DOM.querySelector", { + "nodeId": doc["root"]["nodeId"], + "selector": "input[type='file']", +}) + +# Takes 2 milliseconds and transfers ZERO bytes over the browser socket: +cdp.send("DOM.setFileInputFiles", { + "files": ["/config/Downloads/video.mp4"], + "nodeId": file_node["nodeId"], +}) +``` + +The real question becomes: **How do you get a 130MB file into the container filesystem without SSH keys, volume mounts, or slow SFTP?** + +--- + +## 4. The Portainer Docker Archive API (Hardened Implementation) + +Every Docker daemon exposes a container archive endpoint: +`PUT /containers/{id}/archive?path=/path/in/container` + +If you manage your Docker host with Portainer (standard in Synology and unRaid homelabs), Portainer proxies this Docker socket endpoint behind an API key: + +`PUT http://:9000/api/endpoints/2/docker/containers/{container_id}/archive?path=/config/Downloads` + +Here is a tested, production-ready staging script with proper error handling, parameter validation, and secure file modes: + +```python +import io +import os +import tarfile +import urllib.error +import urllib.request + +PORTAINER_KEY = os.environ.get("PORTAINER_API_KEY", "") +PORTAINER_BASE = "http://192.168.1.1:9000/api/endpoints/2/docker" +CONTAINER_ID = "2dc0fb6a11c7" # Target Chrome container ID + +def stage_file_to_container(local_path: str, dest_filename: str) -> None: + if not PORTAINER_KEY: + raise ValueError("PORTAINER_API_KEY environment variable is not set") + if not os.path.exists(local_path): + raise FileNotFoundError(f"Local source file not found: {local_path}") + + size = os.path.getsize(local_path) + tar_stream = io.BytesIO() + + # Build tar in memory (safe for 100-200MB payloads on workstations with 16GB+ RAM) + with tarfile.open(fileobj=tar_stream, mode="w") as tar: + with open(local_path, "rb") as f: + ti = tarfile.TarInfo(name=dest_filename) + ti.size = size + # 0o644: owner read/write, group/others read-only (avoid world-writable 0o666/0o777) + ti.mode = 0o644 + tar.addfile(ti, f) + + tar_stream.seek(0) + data = tar_stream.read() + + endpoint = f"{PORTAINER_BASE}/containers/{CONTAINER_ID}/archive?path=/config/Downloads" + req = urllib.request.Request( + endpoint, + data=data, + headers={ + "X-Api-Key": PORTAINER_KEY, + "Content-Type": "application/x-tar", + }, + method="PUT", + ) + + try: + with urllib.request.urlopen(req, timeout=120) as resp: + if resp.status not in (200, 204): + raise RuntimeError(f"Archive PUT failed with HTTP {resp.status}") + print(f"Staged {dest_filename} ({size / (1024 * 1024):.2f} MB) in container successfully.") + except urllib.error.HTTPError as e: + body = e.read().decode("utf-8", errors="replace") + raise RuntimeError(f"Portainer Archive API error {e.code}: {body}") from e +``` + +### Operational Caveats & Security Checklist +1. **Client RAM Footprint**: While Chrome experiences zero memory pressure, `io.BytesIO()` buffers the 130MB tar archive in the Python process memory. For multi-gigabyte video dumps, write the `.tar` to a temporary file and stream it using `requests` or `urllib3` chunked uploads. +2. **Pre-existing Destination Directory**: The Docker Archive API extracts *into* the directory specified by `?path=`. If `/config/Downloads` does not exist in the container image, the API returns HTTP 404/500 rather than creating the parent folders. +3. **API Key & CDP Exposure**: Both the Portainer API key and the unauthenticated Chrome DevTools port (default `9222` or `9242`) grant root-level execution capability. Never bind these ports to public IPs (`0.0.0.0`). Keep them strictly on an isolated internal bridge or behind mutual-TLS / Authentik SSO. + +### Measured Performance +On a local 1 Gbps LAN: +- **128.85 MB video file (`.mp4`)**: Transferred and extracted inside the container in **1.89 seconds** (single run, warm container, SSD target on Synology NAS). +- **Chrome container memory consumption**: 0 MB RAM spike across all browser tabs. +- **WebSocket overhead**: 0 bytes transferred over DevTools Protocol. + +--- + +## 5. YouTube Studio Upload Flow Automation + +Once the video and custom thumbnail are staged in `/config/Downloads/`, the Playwright script navigates to `https://studio.youtube.com/`, triggers the upload modal, and executes the wizard: + +1. **Attach Video**: Call `DOM.setFileInputFiles` on the primary `input[type='file']`. +2. **Title & Description**: Click `div[contenteditable="true"][aria-label*="title"]` and type the title; use `.fill()` on the description area. +3. **Attach Thumbnail**: Refresh the DOM with `DOM.getDocument` to discover the newly mounted `input[type='file']#file-loader` and inject `/config/Downloads/cover.jpg`. +4. **Audience Setting**: Check `VIDEO_MADE_FOR_KIDS_NOT_MFK`. +5. **Wizard Steps**: Click `#next-button` through Elements and Checks. +6. **Visibility**: Select `PUBLIC` and click `#done-button`. + +Because the file was already on disk inside the container, YouTube Studio reads the stream locally, achieving maximum upload bandwidth without dropping a single frame. + +--- + +## 6. Summary + +- **Never stream large binaries over WebSocket CDP**. Remote browsers are not designed to buffer multi-hundred-megabyte payloads in memory. +- **Stage files out-of-band**: Use Docker Archive PUT to drop files onto the container filesystem in seconds. +- **Inject via filesystem path**: Call `DOM.setFileInputFiles` with the container path for instantaneous, zero-overhead file attachments. +```` + +--- + +## 文章 08 / 11:如何在押注前验证一个开源依赖:我用的六项检查 +- **Slug**: `vetting-an-open-source-dependency-before-you-bet-on-it` +- **英文标题**: How I Vet an Open-Source Dependency Before Betting On It +- **分类**: `devops` | **发布日期**: 2026-09-29 +- **线上地址**: https://blog.hoelee.com/posts/vetting-an-open-source-dependency-before-you-bet-on-it/ (EN) | https://blog.hoelee.com/posts/zh/vetting-an-open-source-dependency-before-you-bet-on-it/ (ZH) +- **本篇审核状态**: ⏳ 待审核 (Pending) + +### ✍️ 顾问审阅意见区 (Review Feedback) +```text +【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 +【事实与数字核对】: +【人设与用词卫生】: +【CRO与转化建议】: +``` + +### 🇨🇳 中文版原文 (Chinese Markdown Twin) +````markdown +--- +title: "如何在押注前验证一个开源依赖:我用的六项检查" +description: "六项检查,专门抓出「文档说得漂亮、代码里其实没有」的仓库:用 grep 找功能、读文档头部标注的目标分支、看清付费档位门槛,以及收款通道在不在你的国家能用。" +pubDate: 2026-09-29 +category: devops +blueprint: sme-digital-suite +blueprintLayer: L4-managed-ops-handover +tags: ["open-source", "due-diligence", "oidc", "self-hosting", "docker"] +ogImage: "/og/zh-vetting-an-open-source-dependency-before-you-bet-on-it.jpg" +banner: "/banners/vetting-an-open-source-dependency-before-you-bet-on-it.jpg" +draft: false +--- + +有人给我一份 1306 行的伙伴系统架构规格书。读起来像一份计划:前后一致、交叉引用、语气笃定。它指定一个自托管的开源引擎作为归因与佣金层,并且假定了那个引擎的三件事——它支持 OIDC,所以我现有的身份提供方能登录伙伴;它的佣金规则覆盖业务需要的五种形态;它的白标功能已经上线。 + +十分钟的 `curl` 加 `grep` 之后,三件里有两件是假的,第三件只对了一半。 + +这没什么稀奇。README 描述的是**产品**,仓库描述的是**软件**。这两者之间的落差,正是集成项目死掉的地方——而且在写任何代码之前,测量这个落差很便宜。 + +## 问题,写成我真的会去搜的那句话 + +**我怎么知道一个开源项目真的做了它文档宣称的事,然后才在它上面开始建东西?** + +规格书是**关于别的软件**的一种主张。规格书越漂亮,它的假设就越像事实——这一份引用了来源、定义了稳定 ID、还画了一张「真源矩阵」。它唯一没做的事,就是核对链条下游那个引擎到底有没有实现被指派给它的功能。所以在安装任何东西之前,我去找那几个具体功能。 + +## 我一开始试的,以及为什么不够 + +**一、把 README 从头读到尾。** 它把流水线卖得很好:`click → identity → event → attribution → commission → payout`。但它一次都没说这个应用讲哪种认证协议。对一个你**必须要有**的功能来说,沉默不是中立——只是当页面其他部分都很有说服力时,一个「没被提到」很容易被眼睛滑过去。 + +**二、上网搜。** 好几条查询都没返回能用的结果。这个项目才几个月大,SEO 面很薄。对软件来说这没关系——源码**就是**文档。只是意味着阅读必须在仓库里进行,而不是在博客文章里。 + +**三、看到一份 78 KB 的功能设计文档,就假定功能已上线。** 它标着「FINAL, post-review」,列了三位评审,还带着日期。我把它当成了证据。这是三个推断里最糟的一个,也是最容易核对的一个。 + +## 真正定案的六项检查 + +### 1. 先看仓库的生命体征,再看任何功能宣称 + +```bash +curl -s -H "User-Agent: hermes" https://api.github.com/repos// \ + | grep -E '"created_at"|"pushed_at"|"stargazers_count"|"forks_count"|"open_issues_count"|"archived"|"spdx_id"' +``` + +返回的是:MIT、创建于 2026-04-23、最后推送 2026-09-10、8 个 star、3 个 fork、15 个 open issue、未归档。翻译过来就是:**真实、还在动、但非常小**——单一厂商,而且它同时卖托管档。现在我在开始评它的功能之前,先知道了我愿意把多少生意压在它身上。 + +### 2. 用 grep 去找功能,而不是用读的 + +```bash +grep -in 'oidc\|sso\|saml' README.md ARCHITECTURE.md docs/*.md | wc -l +``` + +零命中。这个应用用的是它自己的 magic-link 会话和按身份签发的 API key;它根本不讲 OIDC。就这一行输出,砍掉了计划里的一个阶段——「把门户挂到我们 SSO 后面」——否则这一步会在几周后才浮现,而且是在集成到一半、伙伴已经被邀请进来的时候。**用读的方式去找一个找不到的功能,就是你失去一个下午的方式;grep 让「不存在」这件事变得响亮。** + +### 3. 读功能文档最上方那行「目标分支」 + +```bash +head -5 docs/white-label-custom-domains.md +``` + +`Target branch: multi-tenant`。这份文档描述的是**另一个分支**上的设计,不是你默认会安装的那个分支——它写的是在途工作,所以功能不在你会装下来的代码里。一份有评审、有日期、看起来已经完成的设计文档,完全可能描述着尚未上线的东西。这不是不诚实,设计文档本来就是这个样子。 + +### 4. 读数据模型,不要读功能清单 + +佣金那一节只列了两种规则类型——`percent`(带续期标记)与 `fixed`。业务规格书列了五种。这个落差不是 bug,而是我必须在**配置层**做的建模工作,不能指望产品自带: + +| 规格书假设 | 引擎实际有的 | +|---|---| +| 首单奖励 | 对首个事件用一条 `fixed` 规则 | +| 按事件区分(`lead` vs `invoice_paid`) | 一个 campaign 一条规则——所以:两个 campaign | +| 续期佣金 | `percent` + `recurring: true` | +| 百分比 | `percent` ✅ | +| 固定金额 | `fixed` ✅ | + +两种规则原语,五种行为——能做,但前提是你**一开始**就照这个设计,而不是在实现途中才发现。 + +### 5. 看清你需要的那项功能被锁在哪一档 + +同一个技术栈里还有个数据库工具,它的版本对照表很直白: + +| 我需要的功能 | Community(免费) | Enterprise(付费) | +|---|---|---| +| API token,好让我自动化 | ✅ | ✅ | +| SSO / OIDC | ❌ | ✅ | +| 页面设计器、隐藏品牌、双因素 | ❌ | ✅ | + +我想给「伙伴看到的那个门」用的东西(SSO)在商业门后面;而我想用来做自动化的东西(API token)是免费的。在围绕它做设计**之前**,先弄清每项需求落在墙的哪一侧。 + +### 6. 核对收款通道在你的国家能不能用 + +它的打款模型是 `stripe_connect | manual`,而自托管模式被写成「operator manages out-of-band」——也就是钱由你自己搬。Stripe Connect 不是马来西亚企业付钱给伙伴的方式,所以就是这一行决定了整个部署形态:自托管模式、手工打款、事件由我自己的订单系统推送过去,而不是依赖它内置的支付集成。这一行从来不会出现在营销页上,而它比任何功能都重要。 + +### 然后:在你需要之前,先问「兜底方案」 + +「如果我需要的功能不在,怎么办?」针对缺失的 SSO,答案是:不要把登录做进应用里,把登录放到应用**前面**。authentik 的 proxy provider 存在的意义就是保护「不支持 OIDC、SAML 或 LDAP 等原生认证协议的应用」,并且向上游注入 `X-authentik-username` 和 `X-authentik-groups` 头,于是反向代理就能承担准入判断。这就把「不支持 SSO」从一条否决理由,变成了一个下午的配置工作。 + +## 如果重来,我会怎么做 + +- **先写需求清单,再去找它。** 五行——**我**需要的功能——然后就搜这几个。从 README 的功能列表出发,等于用厂商的考卷给软件打分。 +- **把「文档存在」和「功能上线」当成两件不同的事。** 去读那行目标分支。 +- **用 grep,不要用读的。** 证明「有」很便宜;你要猎的是「没有」。 +- **在决定之前先定兜底**,这样一个缺失的功能就只是一次设计调整,而不是一场意外。 +- **把 commit 钉住。** 这个项目的 README 自己写着 API「stable but unversioned」,而且仓库里没有任何 OpenAPI 描述。没有可以编译期对齐的契约,那么 commit hash **就是**契约——我用到的端点要记进我自己的文档,升级前跑一遍回归。 + +## 结果 + +六个假设在大概十分钟的 `curl` 和 `grep` 里被修正,而当时一行集成代码都还没写。项目依然可行——只是换了形状:没有 OIDC、手工打款、钉住 commit,以及一份不再依赖某个未合并分支上功能的计划。 + +那份规格书乐观并没有错。它错在**没被验证过**——而这是整个项目里最便宜的修补项。 + +--- + +**你正在自托管技术栈上建东西,想在集成之前找人看一眼那些功能到底在不在?** 这正是我在做的复核工作。 + +[WhatsApp +60 12-797 2969](https://wa.me/60127972969) · +[me@hoelee.com](mailto:me@hoelee.com?subject=Open-source%20dependency%20review) · +[hoelee.com](https://hoelee.com) +```` + +### 🇬🇧 英文版原文 (English Markdown Primary) +````markdown +--- +title: "How I Vet an Open-Source Dependency Before Betting On It" +description: "Six checks that catch a repo which doesn't do what its docs claim — grep for the feature, read the doc's target branch, check the tier gate and the payment rail." +pubDate: 2026-09-29 +category: devops +blueprint: sme-digital-suite +blueprintLayer: L4-managed-ops-handover +tags: ["open-source", "due-diligence", "oidc", "self-hosting", "docker"] +ogImage: "/og/vetting-an-open-source-dependency-before-you-bet-on-it.jpg" +banner: "/banners/vetting-an-open-source-dependency-before-you-bet-on-it.jpg" +draft: false +--- + +I was handed a 1,300-line architecture spec for a partner program. It read like a +plan: consistent, cross-referenced, confident. It named a self-hosted +open-source engine as the attribution and commission layer, and it assumed three +things about that engine — that it spoke OIDC so my existing identity provider +could log partners in, that its commission rules covered the five shapes the +business needed, and that its white-label feature was shipped. + +Ten minutes of `curl` and `grep` later, two of those were false and the third was +half-true. None of that is unusual. The README describes the *product*; the +repository describes the *software*. The gap between those two is exactly where +integration projects die — and it is cheap to measure before you write any code. + +## The problem, phrased as the question I'd actually search for + +**How do I know an open-source project does what its documentation claims before +I build on it?** + +A spec is a claim *about other software*. The more polished the spec, the more its +assumptions read like facts — this one cited sources, defined stable IDs, and had +a source-of-truth matrix. What it never did was check whether the engine down the +chain implemented the features being assigned to it. So before installing +anything, I went looking for those specific features. + +## What I tried first, and why it wasn't enough + +**1. Read the README end to end.** It sells the pipeline well: +`click → identity → event → attribution → commission → payout`. It never once +says which authentication protocol the app speaks. For a feature you *need*, +silence isn't neutral — but an absent mention is easy to skim past when the rest +of the page is convincing. + +**2. Searched the web.** Several of my queries returned nothing usable. The +project is a few months old and its SEO surface is thin. For software that's +fine — the source *is* the documentation. It just means the reading has to happen +in the repo, not in a blog post. + +**3. Found a 78 KB feature design doc and assumed the feature shipped.** It was +labelled "FINAL, post-review", listed three reviewers, and carried a date. I took +that as proof. That was the worst inference of the three, and the easiest to check. + +## The six checks that actually settled it + +### 1. Read the repo's vital signs before any feature claim + +```bash +curl -s -H "User-Agent: hermes" https://api.github.com/repos// \ + | grep -E '"created_at"|"pushed_at"|"stargazers_count"|"forks_count"|"open_issues_count"|"archived"|"spdx_id"' +``` + +What came back: MIT, created 2026-04-23, last push 2026-09-10, 8 stars, 3 forks, +15 open issues, not archived. Read the same as: **real, still moving, and very +small** — one vendor, which also sells a hosted tier. Now I know how much of my +business I want resting on it *before* I start grading its features. + +### 2. Grep for the feature instead of reading for it + +```bash +grep -in 'oidc\|sso\|saml' README.md ARCHITECTURE.md docs/*.md | wc -l +``` + +Zero hits. The app authenticates with its own magic-link sessions and +per-persona API keys; it does not speak OIDC at all. That one line of output +killed a phase of the plan — "put the portal behind our SSO provider" — which +would otherwise have surfaced weeks later, mid-integration, with a partner +already invited. Reading for a feature you can't find is how you lose an +afternoon; grepping makes the absence loud. + +### 3. Read the target branch line at the top of a feature doc + +```bash +head -5 docs/white-label-custom-domains.md +``` + +`Target branch: multi-tenant`. The doc is a design for a branch that is not the +default branch — it describes work in flight, so the feature is not in the code +you would install. A finished-looking document with reviewers and dates can +document something unshipped. That isn't dishonesty; it's what design docs are. + +### 4. Read the data model, not the feature list + +The commission section named exactly two rule types — `percent` (with a recurring +flag) and `fixed`. The business spec had enumerated five. That gap isn't a bug; +it's a modelling job I'd have to do in configuration instead of expecting from +the product: + +| Spec assumed | What the engine actually has | +|---|---| +| first-order bonus | a `fixed` rule on the first event | +| event-specific rules (`lead` vs `invoice_paid`) | one rule per campaign — so: two campaigns | +| recurring commission | `percent` + `recurring: true` | +| percentage | `percent` ✅ | +| fixed | `fixed` ✅ | + +Two rule primitives, five behaviours — workable, but only if you design for it up +front instead of discovering it during implementation. + +### 5. Check which paid tier gates the feature you need + +For the database tool in the same stack, the edition table was blunt: + +| Feature I needed | Community (free) | Enterprise (paid) | +|---|---|---| +| API tokens, so I can automate it | ✅ | ✅ | +| SSO / OIDC | ❌ | ✅ | +| Page designer, hide branding, 2FA | ❌ | ✅ | + +The thing I wanted for the partner-facing door (SSO) sits behind the commercial +gate, while the thing I wanted for automation (an API token) is free. Knowing +which side of the wall each requirement falls on changes the design — before +you've designed around it. + +### 6. Check that the money rail works in your country + +The payout model was `stripe_connect | manual`, and self-hosted mode was +documented as "operator manages out-of-band" — i.e. you move the money yourself. +Stripe Connect is not how Malaysian businesses pay partners, so that one line +decided the entire deployment shape: self-host mode, manual payouts, and event +ingestion pushed from my own order system rather than leaning on the provider's +payment integration. That line is never on a marketing page, and it mattered more +than any feature. + +### Then: ask the fallback question before you need it + +"What if the feature I need isn't there?" For the missing SSO the answer was: +don't put login in the app, put it in front of the app. authentik's proxy +provider exists to protect "applications that do not support native +authentication protocols such as OIDC, SAML, or LDAP", and it injects +`X-authentik-username` and `X-authentik-groups` headers upstream, so the reverse +proxy can do the gating. That turned "no SSO support" from a disqualification +into an afternoon of config. + +## What I'd do differently + +- **Write the requirement list first, then go look for it.** Five lines — the + features *I* need — and search for those. Starting from the README's feature + list means grading the software on the vendor's exam. +- **Treat "a doc exists" as different from "a feature ships".** Read the branch + line. +- **Grep, don't read.** Presence is cheap to prove; absence is the thing you're + hunting. +- **Decide the fallback before the decision**, so a missing feature becomes a + design change rather than a surprise. +- **Pin the commit.** This project's README says its API is "stable but + unversioned" and there is no OpenAPI description anywhere in the tree. There's + no contract to compile against, so the commit hash *is* the contract — the + endpoints I use go into my own docs, and upgrades get a regression pass. + +## The result + +Six assumptions corrected in about ten minutes of `curl` and `grep`, before a +single line of integration code existed. The project stayed viable — but +reshaped: no OIDC, manual payouts, a pinned commit, and a plan that no longer +depends on a feature sitting on an unmerged branch. + +The spec wasn't wrong to be optimistic. It was wrong to be unverified, and that's +the cheapest thing on the whole project to fix. + +--- + +**Building on a self-hosted stack, and want a second pair of eyes on whether +those features will actually be there when you integrate?** That's the kind of +review I do. + +[WhatsApp +60 12-797 2969](https://wa.me/60127972969) · +[me@hoelee.com](mailto:me@hoelee.com?subject=Open-source%20dependency%20review) · +[hoelee.com](https://hoelee.com) +```` + +--- + +## 文章 09 / 11:SMART 显示健康,RAID 却在悄悄损坏数据 +- **Slug**: `when-smart-says-healthy-but-your-raid-is-corrupting-data` +- **英文标题**: When SMART Says Healthy and Your RAID Is Silently Corrupting Data +- **分类**: `devops` | **发布日期**: 2026-09-16 +- **线上地址**: https://blog.hoelee.com/posts/when-smart-says-healthy-but-your-raid-is-corrupting-data/ (EN) | https://blog.hoelee.com/posts/zh/when-smart-says-healthy-but-your-raid-is-corrupting-data/ (ZH) +- **本篇审核状态**: ⏳ 待审核 (Pending) + +### ✍️ 顾问审阅意见区 (Review Feedback) +```text +【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 +【事实与数字核对】: +【人设与用词卫生】: +【CRO与转化建议】: +``` + +### 🇨🇳 中文版原文 (Chinese Markdown Twin) +````markdown +--- +title: "SMART 显示健康,RAID 却在悄悄损坏数据" +description: "两块看起来完全健康的 NVMe 组成的 btrfs RAID1 阵列,静默地把 Windows 虚拟机喂成了全零字节。我靠校验和取证抓住它——但根因(M.2 转接卡链路故障 vs 批次缺陷)至今仍未定论,现在两块盘测试都干净。" +pubDate: 2026-09-16 +category: devops +blueprint: self-hosted-infrastructure +blueprintLayer: L1-compute-storage-network +tags: [unraid, btrfs, nvme, raid, storage, data-loss, troubleshooting] +ogImage: /og/zh-when-smart-says-healthy-but-your-raid-is-corrupting-data.jpg +banner: /banners/when-smart-says-healthy-but-your-raid-is-corrupting-data.jpg +--- + +所有存储指南都告诉你同一件事:相信 SMART、检查事件日志、相信你的文件系统。我的硬件不这么想。2026 年 9 月,一个 btrfs RAID1 阵列——两块企业级 NVMe 盘镜像,我用每个能想到的工具查它都说**「健康」**——却在悄悄地把我的 Windows 11 虚拟机喂成全零字节。不是看得见的故障,是静默损坏。 + +下面是完整故事:损坏是怎么浮现的、哪个校验和出卖了它——以及为什么最终定论如今变得不确定。 + +> **更新(2026-09-16):根因至今未定论。** 下面的「两块盘都换」是我当时的判断,但后来一次不相关的故障让我不得不重新审视。现在两块 NVMe 测试都干净,而最强的头号嫌疑是两块盘共用的那块 **M.2 转接卡**——转接卡上的链路层故障,恰好会复现我当初归咎于硬盘的那种「两块盘关联地吐出全零」的损坏。SMART 对链路故障完全无感,所以无法排除它。我在一篇配套文章里写了那次警醒(一颗「死掉的」SATA SSD 其实只是坏线)。先读下面的原始分析,再看更正——然后还有**续集**:两周后同一个全零指纹出现在**完全不同的硬盘堆栈**上,这次终于挖出了根因。见[《换了不同的硬盘,同样的损坏又来了——真凶是 TRIM,不是 SSD》](/posts/zh/the-cause-was-trim-not-the-ssds/)。 + +## 更新:为什么我不再怪两块盘 + +这篇文章发出后,有两件事改变了我的想法。 + +**1. 现在两块盘测试都是干净的。** 在当前条件下,两块 PM9A3 读写都正常。如果它们带着 9 月还在活跃损坏数据的批次级缺陷,应该会挂掉一轮持续的写入+校验(`verify=crc32c`)泡测——但它们没有。 + +**2. 链路故障才是真正的教训。** 就在这次事故之后,我在另一颗盘上撞见了**完全相同**的故障签名(一颗 Seagate IronWolf 110 狂报 `WRITE FPDMA QUEUED` 超时、`mkfs` 失败、然后静默——教科书般的「死盘」)。结果是坏在 **SATA 数据线**上。一条不稳定的链路会复现下面我归咎于硬件的每一个症状:在算出 CRC 之前就已丢掉的超时 I/O、真的丢掉的页面,以及——如果两个 RAID1 成员共用同一块有问题的 **M.2 转接卡**或插槽——两块盘关联地损坏。这是唯一一个不需要任何硬盘缺陷、却能解释「两个成员用同一种方式撒谎」的答案。 + +所以我没法再诚实地断言「盘有问题」。它们可能一直好好的,损坏可能来自它们共同坐着的 **M.2 转接卡**。注意:**这并不代表这次事故是虚惊一场**——真实数据确实读不回来过,无论根因是什么,我都把它移走、迁移数据、并逐字节验证过。但正确的教训是「先排除链路,再给盘判死刑」,而不是「同批次盘不可信」。 + +完整的链路对盘排查,请看 **["我差点把这颗 SSD 送修——真正坏的是 SATA 数据线"](/posts/zh/that-dying-ssd-was-just-a-bad-sata-cable/)**。 + +## 原始分析(保留供透明考量) + +下面是我*当时*得出的结论。这是当时证据下最站得住的解读,而且可能仍然是对的——只是我无法排除别的可能——但请把它当作事故报告来读,而不是最终定论。 + +## 为什么这件事重要 + +损坏状态的磁盘是最糟的存储故障,因为它最容易漏掉: + +- **SMART 看起来完美。** 零媒体错误、几乎满余量,而且是能扛企业级写入负载的盘。 +- **阵列有冗余。** btrfs RAID1 把每个块镜像到两块盘上。当**两个成员**用同一种方式撒谎时,冗余毫无意义。 +- **故障是静默的。** 数组状态没有红色警告、没有硬盘报错、没有硬件事件——只有虚拟机读回垃圾,直到备份恢复成了唯一的选择。 + +如果你的数据在一切看起来都正常的时候悄悄坏掉,「备份」就不是偏执——它是全部。这次事故让我明白:一条**可测试、可验证的恢复**胜过任何阵列状态屏幕。 + +## 环境 + +- **unRaid 7.x**,Intel i9-13900K,Windows 11 虚拟机是主力工作站(GPU 直通)。 +- **缓存池:** 两块 **Samsung PM9A3 3.84TB** NVMe 组 **btrfs RAID1**。而且两块是**同一生产批次**(同一个控制器/固件版本 `GDC7702Q`)。 +- Windows 虚拟机的虚拟磁盘(`vdisk1.img`、`vdisk2.img`)就在这个池的 `domains/` 共享里,另外还有 **Docker 数据根目录**。 +- 虚拟磁盘**没有**设 `NOCOW`——所以每次读取都会被 btrfs 校验和验证。也正因为这个,我最后才抓得住它。 + +## 症状 + +我开始发现缓存读取慢得离谱,主机命令也卡住:`cat`、读 `/proc/loadavg`、甚至 `docker image ls` 都在超时。那块坏 NVMe 正以 **45–75 MB/s** 被狂读,每次读都塞满整台主机的 I/O。本该几秒跑完的 `docker system prune` 直接挂死。 + +然后真正的麻烦来了:Windows 虚拟机开始狂报读错误,回来的是**错的**数据——满文件的全零字节、guest 里的校验和失败,最后主力 VM 直接引导不了。 + +## 取证:`csum 0x8941f998` + +btrfs 在读校验失败时会往内核日志记一条校验和不匹配。同一个值反复出现: + +```text +btrfs: checksum verify failed on wanted 0x8941f998 found +``` + +这个特定值是最重要的线索。**`0x8941f998` 就是一整块零字节的 CRC32C。** 它每次都出现、跨越互不相关的文件和 inode,绝不是巧合。正在发生的不是随机比特腐烂,而是盘**稳定地返回全零块**,而这些零填充的读取正是 btrfs 校验失败的对象: + +- 验证一下:零填充块的 `crc32c` 就等于 `0x8941f998`。 +- 同一个值反复出现 → 读取是**确定性**地吐出空数据,不是偶尔翻几个比特。 + +两块虚拟磁盘都中招(`vdisk1.img` inode 2358574、`vdisk2.img` inode 2362817),正好对上「存储层在把零当成被请求的数据返回」的图景。 + +## 破绽:永远不生效的「自愈」 + +btrfs RAID1 本应自愈:一个成员坏块、从镜像重建、写回好数据。但我一遍遍 scrub、重读同一块(仍然全零的)数据后发现,**重写根本不落地**。每次重建「成功」后,立刻重读同一 extent 又吐出零。 + +这是关键区别: + +- 一块**只读不出来**的盘是读问题——自愈应该能从镜像救回来。 +- 一块**连回调也无脑吞垃圾存进去**的盘是**写或控制器**问题——镜像救不了你,因为两条路径都对同一个错误答案达成一致。 + +当自愈重写一直不生效,你就不在「坏一个扇区」的范畴了,而是「这块盘在写入上撒谎」——RAID 冗余救不了。 + +## 为什么两块盘都得换(我当时的推理) + +> 这是当初「都换掉」决定的依据。动手前先读上面更新里的更正——一块共用的 M.2 转接卡链路故障,在无需任何硬盘缺陷的情况下也能对上这份证据。 + +数据指向的是**同批次盘的硬件缺陷**,而不是磨损或一次性的偶发事件: + +- SMART 干净(0 媒体错误、几乎满余量,`nvme0` 大约写了 586 TiB——对能扛企业级负载的盘来说算重负载但仍正常)。 +- 两块盘**同批次、同控制器/固件**(`GDC7702Q`)。 +- 损坏以**相关的方式**同时命中两个 RAID1 成员——镜像「死一块也能幸存」的整个意义,因为两块盘正以同一种方式一起死掉而完全失效。 + +面对批次级的关联缺陷,留下那块「看起来健康」的盘当幸存成员是假省心。**我从备份恢复了 Windows 虚拟机,然后把两块盘都换掉。** + +## 我同时做的事:把数据迁出那个池 + +在换盘之前,任何还值得读的数据都得搬出这个坏池——而且要**验证**,不能想当然: + +- **Docker 数据根目录**迁出缓存:`docker` 挪到 `/mnt/user/docker`(在 `disk1` 上,overlay2)。整棵树通过**路径、大小、mtime** 逐文件比对、并与字节对比交叉验证,共 **3,997,569** 个文件。 +- 缓存的 `isos/`、`system/`、`swapfile` 搬到 `disk1`;`isos/`(约 13 GB)用 `diff -rq` 检查 → **EXIT=0**,无差异。 +- 所有搬走的文件都在**删除缓存副本之前**先跟源比对过——没验证过的副本绝不删。 + +因为存在读侧损坏(全零块)和写侧损坏(自愈不落地),那个池里的任何东西,没有镜像、没有校验和、没有新鲜备份可对照,我就一律不信任。 + +## 如果重来我会怎么做 + +1. **在需要它之前就先测试恢复虚拟机备份。** 我当时确认了备份存在,但损坏事故不是该第一次学恢复流程的时候。定时做的测试恢复既能发现备份问题,也能发现静默的存储损坏。 +2. **把同批次的两块盘当成一块盘。** 两块 PM9A3 同批次同固件。对需要长期搭档的缓存池(任何 RAID1)这是关联失效风险——优先选不同批次的盘,或者至少在信任镜像前把这对盘狠狠测一遍。 +3. **主动检测,而不是被动祈祷。** 正是 btrfs 校验和让它在噪声里浮出来。不开 `NOCOW` 意味着文件系统在验证每一次读取;一个带校验的数据池,就是「当场抓住并恢复」和「把损坏文件带出去几个月」之间的分水岭。 +4. **别用 SMART 判断闪存。** 一块看起来健康却照样损坏的 NVMe,事件计数什么也说明不了——固件级的缺陷可以躲过所有 SMART 属性。 + +## 结果 + +一台 Windows 虚拟机从备份恢复、数据安全迁出那个坏池、Docker 数据根目录也搬了家——**外加一条事后再推翻的教训。** 我当时换掉了两块盘,但现在我没法确定它们就是元凶:证据同样支持一块共用的 **M.2 转接卡**链路故障,而且现在两块盘测试都干净。(完整排查见 **["我差点把这颗 SSD 送修——真正坏的是 SATA 数据线"](/posts/zh/that-dying-ssd-was-just-a-bad-sata-cable/)**。) + +事故被控制住,是因为损坏被校验和抓住了、而不是在里面泡了几个星期——这一点无论根因是什么都成立。但更诚实的教训,比「把盘换掉」这句要更广、也更不戏剧化: + +1. **一块「正在损坏」的盘,并不等于盘本身坏了。** 在给硬件判死刑前,先排除链路:重新插拔/更换线材、换到别的口/转接卡/插槽,重跑*相同*的失败操作。如果故障跟着**口/转接卡**走,那就是连接的问题。 +2. **SMART 看不见链路故障。** 零媒体错误和几乎满余量,对一条不稳定的线材或转接卡毫无意义——超时在算出 CRC 之前就把 I/O 丢了。 +3. **同批次盘共用一条通道,无论谁坏都是共享失效风险。** 不管损坏来自盘还是转接卡,一对盘坐同一条故障路径上,就是穿着两个序列号的单点故障。 +4. **给你的数据加校验、并提前测试恢复备份。** 把数星期静默损坏变成一次被控制住的事故的,是这一点——不是我那部分诊断。 + +--- +```` + +### 🇬🇧 英文版原文 (English Markdown Primary) +````markdown +--- +title: "When SMART Says Healthy and Your RAID Is Silently Corrupting Data" +description: "A btrfs RAID1 pool on two healthy-looking NVMe drives quietly corrupted a Windows VM. How I caught it with a checksum forensic — and why the root cause (M.2 riser link fault vs batch defect) is still uncertain, with both drives now testing clean." +pubDate: 2026-09-16 +category: devops +blueprint: self-hosted-infrastructure +blueprintLayer: L1-compute-storage-network +tags: [unraid, btrfs, nvme, raid, storage, data-loss, troubleshooting] +ogImage: /og/when-smart-says-healthy-but-your-raid-is-corrupting-data.jpg +banner: /banners/when-smart-says-healthy-but-your-raid-is-corrupting-data.jpg +--- + +Every storage guide tells you the same thing: trust SMART, check the event +log, and believe your filesystem. My hardware disagreed. In September 2026 a +btrfs RAID1 pool — two mirrored enterprise NVMe drives that said **"healthy"** +in every tool I could run — was quietly feeding my Windows 11 VM all-zero +bytes. Not visibly failing. Silently corrupting. + +This is the full story: how the corruption surfaced, and the checksum that +gave it away. + +> **Update (2026-09-16): the root cause turned out to be uncertain.** The +> "replace both drives" verdict below was my best diagnosis at the time, but a +> later, unrelated failure taught me to question it. Both NVMe drives now test +> clean, and the strongest remaining suspect is the **M.2 riser** both drives +> were plugged into — a link-layer fault on the riser reproduces exactly the +> correlated, all-zero corruption I blamed on the drives. SMART is silent to +> link faults, so it can't rule one out. I describe that wake-up call (a "dead" +> SATA SSD that was just a bad cable) in a companion post. Read the original +> analysis, then the correction — and then the *sequel*: two weeks later the +> same all-zero fingerprint appeared on a **completely different drive stack**, +> and this time the root cause surfaced. See [The Corruption Came Back on +> Different Drives — the Cause Was TRIM, Not the SSDs](/posts/the-cause-was-trim-not-the-ssds/). + +## Update: why I no longer blame the drives + +Two things changed my mind after this post went up. + +**1. The drives test clean now.** Under current conditions both PM9A3s read and +write correctly. If they carried a batch-level defect that was actively +corrupting in September, I'd expect them to fail a sustained write+verify +(`verify=crc32c`) soak — they don't. + +**2. A link fault was the real lesson all along.** Right after this incident I +hit the *same* failure signature on a different drive (a Seagate IronWolf 110 that threw +`WRITE FPDMA QUEUED` timeouts, failed `mkfs`, and went silent — textbook +"dead SSD"). It turned out to be the **SATA cable**. A flaky link reproduces +every symptom I blamed on hardware below: timeouts dropped before a CRC is +computed, real pages lost, and — if both RAID1 members share the same +faulty **M.2 riser** or slot — *correlated* corruption across both drives. +That's the one explanation that fits "both members lied the same way," and it +doesn't require any drive defect at all. + +So I can't honestly say "the drives were bad." They may have been perfectly +fine, and the corruption may have come from the **M.2 riser** they both sat +on. Note that **this does not make the incident a false alarm**: real data +*could not be read back*, and whatever the cause, I removed it, migrated the +data, and verified every byte. But the correct lesson is "rule out the link +before condemning the drive," not "same-batch drives are untrustworthy." + +The full link-vs-drive detective work is in **["I Was About to RMA This SSD — +the Fault Was a SATA Cable"](/posts/that-dying-ssd-was-just-a-bad-sata-cable/)**. + +## The original analysis (kept for transparency) + +What follows is what I concluded *at the time*. It was the most defensible +reading of the evidence available, and it may still be right for reasons I +can't rule out — but read it as the incident report it is, not the final +verdict. + +## Why this matters + +A corrupting disk is the worst kind of storage failure because it's the +easiest to miss: + +- **SMART looked perfect.** Zero media errors, ~100% spare, on drives rated + for heavy enterprise write loads. +- **The pool had redundancy.** btrfs RAID1 mirrored every block across two + drives. Redundancy means nothing when *both* members lie the same way. +- **The failure was silent.** No red warning in the Unraid array status, no + failing drive, no hardware event — just VM reads slowly returning garbage + until a backup restore became the only option. + +If your data only gets corrupted when nothing looks wrong, "backup" is not +paranoia — it's the entire ballgame. This incident is why a testable, +verified restore beats any array status screen. + +## The setup + +- **unRaid 7.x** on an Intel i9-13900K, with a Windows 11 VM as the primary + workstation (GPU passed through). +- **Cache pool:** two **Samsung PM9A3 3.84 TB** NVMe drives in **btrfs RAID1**. + Both from the **same production batch** (same controller/firmware + revision, `GDC7702Q`). +- The Windows VM's virtual disks (`vdisk1.img`, `vdisk2.img`) lived on that + pool, in the `domains/` share — plus **Docker's data root**. +- The VM's vdisks were **not** `NOCOW` — so every read was validated against + a btrfs checksum. That setting ended up being the reason I caught it at all. + +## The symptom + +I started noticing cache reads were crawling, and host commands were stalling: +`cat`, reading `/proc/loadavg`, even `docker image ls` were timing out. The +corrupt NVMe was being hammered at **45–75 MB/s of reads**, and every read +saturating the drive stalled the whole host's I/O. A `docker system prune` +that should have finished in seconds just hung. + +Then the real problem surfaced: the Windows VM began throwing read errors and +data that came back was **wrong** — files that were full of zero bytes, +checksum failures in the guest, and ultimately an unbootable primary VM. + +## The forensic: `csum 0x8941f998` + +On btrfs, when a read fails verification the kernel logs a checksum mismatch +for the affected extent. The same value kept recurring: + +```text +btrfs: checksum verify failed on wanted 0x8941f998 found +``` + +That specific value was the first real clue. **`0x8941f998` is the CRC32C of +a block of zeros.** It has to be — it came up every time, across unrelated +files and inodes. What was happening wasn't random bit rot; the drive was +returning **all-zero blocks**, consistently, and those zero-filled reads were +exactly what btrfs was failing to verify: + +- Check the value: `crc32c` of a zero-filled extent matches `0x8941f998`. +- It's the same value again and again → reads were **deterministically** + producing empty data, not occasionally flipping bits. + +Two VM vdisks were affected (`vdisk1.img` inode 2358574, `vdisk2.img` inode +2362817), which fit the picture: a storage layer was returning zeros instead +of the data it was asked to read. + +## The tell: self-heal "fixes" that never stuck + +btrfs RAID1 is supposed to be self-healing: read a bad block on one member, +reconstruct it from the mirror, and rewrite the good data back. But as I +scrubbed and re-read the same (still all-zero) data, it became clear the +**rewrites were not sticking**. Each rebuild "succeeded" and the very next +read of the same extent produced zeros again. + +That's the critical distinction: + +- A drive that only **fails to read** is a read problem — self-heal should + recover it from the mirror. +- **A drive that also accepts and silently stores garbage** is a *write* or + *controller* problem — the mirror can't save you, because both paths agree + on the wrong answer. + +When self-heal rewrites keep not sticking, you're no longer in "one bad +sector" territory. You're in "the device is lying about writes" territory, +and RAID redundancy won't help. + +## Why both drives had to go (my reasoning at the time) + +> This was the basis for the original "replace both" decision. Read the +> correction in the Update above before acting on it — a shared M.2 riser +> link fault also fits this evidence without any drive being defective. + +The data pointed at a **hardware defect in the same-batch drives**, not a +wear or one-off event: + +- SMART was clean (0 media errors, ~100% spare, and `nvme0` had written + roughly 586 TiB — heavy, but on a drive rated for enterprise workloads). +- The two drives were **same-batch, same controller/firmware** (`GDC7702Q`). +- Corruption hit **both** RAID1 members in correlated fashion — the whole + point of mirroring (survive one drive dying) failed because both were dying + the same way, in lockstep. + +With a correlated, batch-level defect, keeping one "healthy-looking" drive as +the surviving member is a false economy. **I restored the Windows VM from +backup and replaced both drives.** + +## What I did in parallel: move the data off that pool + +Before the drives were replaced, anything still worth reading had to come off +the failing pool — and it had to be **verified**, not assumed: + +- **Docker's data root** moved off the cache: `docker` was relocated to + `/mnt/user/docker` (on `disk1`, overlay2). The whole tree was verified by + matching **path, size, and mtime** for all **3,997,569 files** against a + byte-comparison. +- The cache's `isos/`, `system/`, and `swapfile` moved to `disk1`; the + `isos/` set (~13 GB) was checked with `diff -rq` → **EXIT=0**, no + differences. +- Everything moved was compared against the source **before** the cache copy + was deleted — never delete a copy you haven't verified. + +The read-side corruption (all-zero blocks) and the write-side corruption +(self-heal not sticking) meant I trusted nothing from that pool without a +mirror, a checksum, or a fresh backup to compare against. + +## What I'd do differently + +1. **Test-restore the VM backup before needing it.** I'd verified backups + existed, but a corruption incident is not the time to first learn your + restore procedure. A scheduled test-restore catches both backup failure + *and* silent storage corruption. +2. **Treat same-batch drives as one drive.** Both PM9A3s came from the same + batch with the same firmware. For a married cache pool (or any RAID1) + that's a correlated-failure risk — prefer drives of different production + batches or at least hammer-test the pair before trusting a mirror. +3. **Detect, don't just hope.** btrfs checksums are what surfaced this + through the noise. The `NOCOW`-less vdisk config meant the filesystem was + validating every read; a pool of checksummed data is the difference + between "caught it and restored" and "shipped corrupted files for months". +4. **Don't trust SMART for flash.** For a healthy-looking NVMe that still + corrupts, the event count says nothing — the firmware-level defect can be + invisible to every SMART attribute. + +## The result + +One Windows VM restored from backup, the data safely off the failing pool, and +Docker's data root relocated — **plus a lesson I had to un-learn after the +fact.** I replaced both drives, but I can no longer be certain they were the +cause: the evidence fits a shared **M.2 riser** link fault just as well, and +both drives test clean now. (Full detective work in ["I Was About to RMA This +SSD — the Fault Was a SATA Cable"](/posts/that-dying-ssd-was-just-a-bad-sata-cable/).) + +The incident was contained because corruption was caught by checksums, not +wallowed in for weeks — that part stands regardless of cause. But the honest +lesson is broader and less dramatic than "replace the drives": + +1. **A "corrupting" drive isn't proof the drive is bad.** Before condemning + hardware, rule out the link: reseat/swap the cable, move to a different + port/riser/slot, and rerun the *same* failing operation. If the fault + follows the **port/riser**, it's the connection. +2. **SMART can't see link faults.** Zero media errors and ~100% spare say + nothing about a flaky cable or riser — timeouts drop I/O before a CRC is + even computed. +3. **Same-batch drives sharing a channel is a shared-failure risk either + way.** Whether the corruption was the drives or the riser, a married pair + on one faulty path is a single point of failure wearing two serial numbers. +4. **Checksum your data and test-restore your backups.** That — not the part + diagnosis — is what turned a weeks-long silent corruption into a contained + incident. + +--- +```` + +--- + +## 文章 10 / 11:为什么容器里的 Chrome 会忘记标签页 —— 以及我是怎么修好的 +- **Slug**: `why-chrome-forgets-its-tabs-in-a-container` +- **英文标题**: Why Chrome Forgets Its Tabs in a Container — And How I Fixed It +- **分类**: `devops` | **发布日期**: 2026-09-29 +- **线上地址**: https://blog.hoelee.com/posts/why-chrome-forgets-its-tabs-in-a-container/ (EN) | https://blog.hoelee.com/posts/zh/why-chrome-forgets-its-tabs-in-a-container/ (ZH) +- **本篇审核状态**: ⏳ 待审核 (Pending) + +### ✍️ 顾问审阅意见区 (Review Feedback) +```text +【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 +【事实与数字核对】: +【人设与用词卫生】: +【CRO与转化建议】: +``` + +### 🇨🇳 中文版原文 (Chinese Markdown Twin) +````markdown +--- +title: "为什么容器里的 Chrome 会忘记标签页 —— 以及我是怎么修好的" +description: "Chrome 的「继续上次浏览」在 Docker 容器里根本不会生效:三次失败的尝试、真正的原因,以及最后管用的 70 行守护脚本。" +pubDate: 2026-09-29 +category: devops +tags: [docker, chrome, cdp, persistence, synology, self-hosting] +ogImage: /og/zh-why-chrome-forgets-its-tabs-in-a-container.jpg +banner: /banners/why-chrome-forgets-its-tabs-in-a-container.jpg +draft: false +--- + +我在 NAS 上的 Docker 容器里跑着一个真正的 Google Chrome。它不是爬虫实例,也不是截图服务 —— 是我真的在用的浏览器:登录着那些绝不该交给无头机器人的账号,可以从任何设备通过网页桌面看着它操作,需要自动化的时候还能用 Chrome DevTools Protocol (CDP) 驱动它。 + +它一直很好用,只有一个例外:**每次容器重启,浏览器回来时只剩一个空白标签页。** + +Chrome 明明有专门对付这件事的设置 ——「继续浏览上次打开的网页」。它一直是开着的,却毫无作用。下面就是三次失败的尝试、真正的原因、路上踩到的两颗地雷,以及最后真正让重启变得可用的那七十来行守护脚本。 + +## 为什么这件事值得认真对待 + +当容器里的浏览器就是你的工作台时,标签页就是状态本身:填了一半的表单、正在编辑的商品上架页、筛选到指定日期的仪表盘、客户基础设施的三个页面 —— 那些就是工作。浏览器一启动停在空白页,意味着每次重启后的头十分钟都在重建你本来就有的上下文。 + +这个问题我查过不止一次,网上能搜到的只有「把 `restore_on_startup` 设上」这类建议,而那套建议一进容器就失效。如果你也撞上了同一堵墙,这篇文章就是这堵墙的解释。 + +## 我的环境 + +Synology NAS 上的一个 Docker stack,里面两个浏览器(真 Chrome 加 Brave),各自挂在自己的 SSO 网关后面: + +| 组件 | 取值 | +|---|---| +| 镜像 | `lscr.io/linuxserver/chrome` —— 真正的 Google Chrome 154 | +| 桌面 | Selkies 网页桌面,容器 `3000`/`3001` → 宿主 `3030`/`3031` | +| 自动化 | CDP 暴露在 `http://:9232/json/version` | +| Profile | bind mount,容器内路径 `/config/profile` | +| 启动参数 | `--remote-debugging-port=9222 --user-data-dir=/config/profile --restore-last-session` | + +Profile 是 bind mount,所以登录态、cookie、历史记录在容器重建后确实都还在 —— 那部分从来没坏过。丢掉的只有**会话**(当时开着哪些标签页)。 + +## 尝试一:那个启动参数 + +Chromium 有一个听起来正合适的开关:`--restore-last-session`,文档说法是「在**意外退出**后恢复上次的会话」。 + +我通过镜像的 CLI 环境变量加上它,并且确认它确实传到了运行中的进程上 —— 因为这类镜像的命令行是包装脚本拼出来的: + +```bash +docker exec chrome sh -c 'tr "\0" " " < /proc/$(pgrep -f "google-chrome --" | head -1)/cmdline' | tr ' ' '\n' | grep -E 'restore|user-data-dir|remote-debug' +# --remote-debugging-port=9222 +# --user-data-dir=/config/profile +# --restore-last-session +``` + +重启。空白页。参数在,只是它没有任何「愿意恢复」的东西。 + +## 尝试二:直接改 profile 里的配置 + +Chrome 把「继续浏览上次打开的网页」存在 profile 的 `Preferences` JSON 里,字段是 `session.restore_on_startup: 1`。于是我停掉容器,直接把这两个值改了: + +```python +import json +p = '/config/profile/Default/Preferences' +d = json.load(open(p)) +d.setdefault('session', {})['restore_on_startup'] = 1 # 1 = restore last session +d.setdefault('profile', {})['exit_type'] = 'Normal' +json.dump(d, open(p, 'w')) +``` + +这就是网上最流行的那套做法,而它「半成功」了:下次启动后,Chrome **保留**了文件里的 `restore_on_startup: 1` —— 然后照样打开空白页。它没有保留的是我写的 `exit_type`:启动时它已经把那个值改回了 `Crashed`。 + +这次改写反而是第一条真正的线索。Chrome 把启动状态当成安全边界 —— 劫持者最想改的那些设置(主页、搜索引擎、启动页面)会跟另一个文件 `Secure Preferences` 做 MAC 校验。所以,磁盘上被改过的值,并不自动等于 Chrome 会遵守的值。 + +## 尝试三:托管策略 + +让浏览器行为具备权威性的正式办法是**托管策略**(managed policy),它不受上面那套 MAC 校验约束。在 Linux 上,Chrome 读取 `/etc/opt/chrome/policies/managed/*.json`: + +```json +{ "RestoreOnStartup": 1 } +``` + +动手之前有两个细节:Chrome **会忽略**运行浏览器的那个用户可写的策略文件,所以必须是 `root:root` 加 `644`;而在 Synology 的共享目录上,某些目录即使 `sudo` 也会拒绝执行 `chmod`,所以别假设你改成功了,去确认当前的实际权限。 + +挂进容器,启动后确认文件在位: + +```bash +docker exec chrome sh -c 'ls -l /etc/opt/chrome/policies/managed/; cat /etc/opt/chrome/policies/managed/hoeleepolicy.json' +# -rw-r--r-- 1 root root 28 hoeleepolicy.json +# { "RestoreOnStartup": 1 } +``` + +重启。还是空白页。 + +## 尝试四:先证明「退出是不干净的」 + +到这一步,问题已经不是「我该用哪个设置」,而是「容器停掉的时候,这个浏览器到底看到了什么」。 + +Chrome 的会话恢复机制需要一个它认为**被中断、或可续接**的会话:只有在正常退出时,它才会把 `Current Session` 落成 `Last Session`。于是我改用最温和的方式收掉浏览器 —— 通过 CDP 让它自己优雅退出,而不是把容器从它脚下抽走: + +```python +# browser-level target from /json/version +ws.send(json.dumps({"id": 1, "method": "Browser.close", "params": {}})) +``` + +Chrome 确实退出了 —— 然后桌面会话在几秒内又把它拉了起来,`exit_type` 立刻回到 `Crashed`。 + +这就是全部的机关,它一次性解释了前面三次失败:**这个浏览器从来没有干净退出过。** 你停容器时,桌面会话被一起拆掉,浏览器跟着被杀。没有干净退出,就没有 `Last Session` 的落盘,也就没有任何东西可供「继续上次浏览」或 `RestoreOnStartup` 策略去恢复。那个参数、那个首选项、那条策略其实都在正常工作 —— 只是它们手上空无一物。 + +数据其实一直都在。那段时间 profile 的会话目录每隔几秒就在写: + +``` +-rw------- 1 hoelee users 40722 Session_13434833255312492 +-rw------- 1 hoelee users 58879 Tabs_13434833757632480 +-rw------- 1 hoelee users 79361 Tabs_13434833833646133 +``` + +## 修法:别再去配置它,开始替它记住 + +如果浏览器记不住自己的会话,那就让容器替它记住。两件事,都很小: + +1. **启动时**:等浏览器起来,如果它一个真正的页面都没打开,就把上次的网址重新打开。 +2. **之后一直**:每 60 秒把当前打开的页面地址快照一次。 + +这就是一段从镜像的容器初始化钩子拉起的后台脚本。我实际在跑的版本,去掉无关部分后是这样: + +```python +#!/usr/bin/env python3 +"""Restore last session's tabs on start, then snapshot open tabs every 60s.""" +import json, os, time, urllib.parse, urllib.request + +CDP = "http://127.0.0.1:9222" # loopback inside the container +STORE = "/config/tabs-last.txt" # lives in the persistent profile mount + +def open_tabs(): + """http(s) page URLs, or None when the browser isn't answering yet.""" + try: + with urllib.request.urlopen(CDP + "/json/list", timeout=5) as r: + tabs = json.load(r) + except Exception: + return None + return [t.get("url", "") for t in tabs + if t.get("type") == "page" and t.get("url", "").startswith("http")] + +saved = [u.strip() for u in open(STORE)] if os.path.exists(STORE) else [] + +# 1) restore — wait up to 3 minutes for the browser to come up +if saved: + for _ in range(60): + if open_tabs() is not None: + break + time.sleep(3) + if open_tabs() == []: # nothing but a blank new tab + for url in saved[:20]: + req = urllib.request.Request( + CDP + "/json/new?" + urllib.parse.quote(url, safe=""), method="PUT") + urllib.request.urlopen(req, timeout=10).read() + time.sleep(0.7) + +# 2) snapshot — write even an empty list, so "I closed everything" is respected +while True: + time.sleep(60) + tabs = open_tabs() + if tabs is None: + continue + tmp = STORE + ".tmp" + open(tmp, "w").write("\n".join(tabs) + ("\n" if tabs else "")) + os.replace(tmp, STORE) # atomic; a kill can't truncate it +``` + +两个设计选择值得抄走: + +- **只在浏览器确实空空如也时才恢复。** 万一将来某个 Chrome 版本自己会恢复标签页,这段脚本就会让路,而不是把每个标签页再复制一遍。 +- **快照是原子的,而且允许为空。** 先写临时文件再 `os.replace`,意味着写到一半被杀也不会留下半截列表;而空列表是有意义的数据 —— 它表示你主动关掉了全部标签页,所以下次启动就该保持空白。 + +拉起它的初始化钩子: + +```sh +#!/bin/sh +# clear stale singleton state (see below) +rm -f /config/profile/Singleton* 2>/dev/null +# long-running, so background it or you block container init +/usr/bin/env python3 /custom-cont-init.d/tabs_keeper.py >> /config/tabs-keeper.log 2>&1 & +exit 0 +``` + +### 地雷一:残留的 `Singleton*` 会让 Chrome 干脆不启动 + +测试重启的过程中,我撞上了一个比空白页更糟的故障:容器**健康地**起来了,里面却没有浏览器。没有 `google-chrome` 进程、CDP 不通、中继容器的健康检查报 `unhealthy`,日志里除了桌面启动之外什么都没有。 + +原因在 profile 里的 `SingletonLock`/`SingletonSocket`/`SingletonCookie` 这几个符号链接 —— 它们记录了「这个 profile 属于主机 *h* 上的进程 *n*」。而容器里的 PID 会跨重启复用,于是下一次启动可能发现自己这个 PID 已经被「占用」,于是立刻退出。在容器启动时、浏览器拉起之前把它们删掉就是解法,这也是上面钩子里那句 `rm -f` 存在的原因。 + +### 地雷二:`custom-cont-init.d` 只执行**可执行**文件,而且用 bash 执行 + +LinuxServer 的镜像会执行 `/custom-cont-init.d` 下的每个文件,但前提是它可执行,并且是用 `/bin/bash` 执行。也就是说,你放进去的 Python 文件**绝不能**带执行位,否则会被喂给 bash 然后以 2 退出: + +``` +[custom-init] tabs_keeper.py: executing... +[custom-init] tabs_keeper.py: exited 2 +``` + +可行的分工是:`.sh` 钩子设 `755`,把常驻任务放到后台;同目录的 `.py` 设 `644`。另外,任何不会立刻返回的东西都必须后台化,否则容器初始化会一直等它。 + +## 顺带带出来的管道陷阱 + +守护脚本是走 loopback 上的 CDP 跟 Chrome 说话的,所以它不需要任何端口。但如果你还想从另一台机器驱动这个浏览器,就会多出一个容器 —— 因为 Chrome ≥ 136 把 devtools 端点钉在 `127.0.0.1:9222`,并且忽略 `--remote-debugging-address`。标准做法是让一个 `socat` 边车共用浏览器的网络命名空间: + +```yaml +chrome-relay: + image: alpine/socat + network_mode: service:chrome # must share the browser's netns + command: socat TCP-LISTEN:9223,fork,reuseaddr TCP:127.0.0.1:9222 + healthcheck: + test: ["CMD-SHELL", "nc -z 127.0.0.1 9222 || exit 1"] +``` + +端口映射**不**写在中继上(它自己没有独立命名空间),而是写在浏览器服务上:`9232:9223`。 + +这个边车有一个你必须记住的行为:**重启浏览器,中继会跟着死。** 它当初所在的命名空间被重建了,socat 进程还活着、套接字却已经失效,于是 CDP 报 `connection reset`,而容器看起来一切正常。按这个顺序收拾: + +```bash +docker restart chrome && docker restart chrome-relay # order matters +``` + +上面那条健康检查的作用,就是把这种静默故障变成一个看得见的 `unhealthy`。如果你打算自己驱动容器里的浏览器,客户端那一侧我单独写过一篇:[Scraping a Bot-Walled Marketplace With a Warm Browser Session](/posts/scraping-bot-walled-marketplace-warm-browser-session/)。 + +## 如果重来一次 + +- **先确认进程能不能干净退出,再考虑相信任何「启动时恢复」的机制。** 我在一个前提条件(浏览器能察觉到的退出)根本不存在的情况下,连试了三种配置。一次 `Browser.close` 测试就能让整个排查过程坍缩。 +- **不要手改浏览器首选项。** 它们会跟 `Secure Preferences` 做 MAC 校验;磁盘上一个看起来合理的值,并不等于 Chrome 会遵守的值。需要权威性就用托管策略 —— 并且去验证策略真的加载了,而不是假设文件放进去就够了。 +- **确认谁有权限写那条策略。** `root:root`、`644`,放在 `/etc/opt/chrome/policies/managed` 下才是对的形状;用户可写的策略文件会被静默忽略。 +- **把「浏览器在跑」和「容器在跑」当成两个不同的问题。** 残留 singleton 那次故障,从外面看就是一个健康的容器。 +- **与其让软件记住状态,不如自己存快照。** 任何关闭路径上带强杀的软件 —— 容器、kiosk、桌面会话 —— 都不是依赖「干净退出」记账的好地方。一个 60 秒一次、原子写入的快照很无聊,但它管用。 + +## 结果 + +- 真实的容器重启之后,两个浏览器各自 **2/2 个标签页**都恢复了(守护日志里是 `restored 2/2 tabs`),重启后再用 CDP 复核过 +- 同一批重启里,登录态、cookie 和 `localStorage` 都确认存活 —— 持久化 profile 从来不是问题所在 +- 三个 stack(两个浏览器加一个试验品)合并成一个,并且靠中继的健康检查,把唯一那个「重启顺序」陷阱由静默变成看得见 + +## 你的业务需要这个吗? + +如果你想要一个始终登录着的浏览器 —— 跑在你自己的硬件上、任何地方都能访问、挂在 SSO 后面、标签页状态能扛住重启,还带一个能给你脚本用的 CDP 端点 —— 那正是我在跑、也在维护的这套东西。 + +**WhatsApp: [+60 12-797 2969](https://wa.me/60127972969)** · **Email: [me@hoelee.com](mailto:me@hoelee.com?subject=Self-hosted%20container%20browser)** · **[hoelee.com](https://hoelee.com)** + +网站设计与开发是我的主业;自托管基础设施与自动化是另外一半。 +```` + +### 🇬🇧 英文版原文 (English Markdown Primary) +````markdown +--- +title: "Why Chrome Forgets Its Tabs in a Container — And How I Fixed It" +description: "Chrome's \"continue where you left off\" never fires inside a Docker container. The three fixes that failed, the real root cause, and the 70-line keeper that works." +pubDate: 2026-09-29 +category: devops +tags: [docker, chrome, cdp, persistence, synology, self-hosting] +ogImage: /og/why-chrome-forgets-its-tabs-in-a-container.jpg +banner: /banners/why-chrome-forgets-its-tabs-in-a-container.jpg +draft: false +--- + +I run a real Google Chrome inside a Docker container on my NAS. It is not a scraping instance and not a screenshot service — it is a browser I actually use: signed into the accounts a headless bot should never touch, watchable through a web desktop from any device, and drivable over the Chrome DevTools Protocol when I want to automate part of a job. + +It works well, with one exception. **Every time the container restarts, the browser comes back with a single blank tab.** + +Chrome has a setting for exactly this — "Continue where you left off". It was already enabled. It did nothing. What follows is three fixes that failed, the actual root cause, the two landmines I hit on the way, and the ~70-line keeper that finally made restarts survivable. + +## Why this matters + +When a container browser is your workspace, the tabs *are* the state. Half-finished forms, a marketplace listing in progress, a dashboard filtered to the right date range, three tabs open on a customer's infrastructure — that is the work. A browser that opens on `about:blank` means the first ten minutes after every restart are spent rebuilding context you already had. + +I looked for this answer more than once and found nothing but "set `restore_on_startup`" advice that does not survive contact with a container. If you have hit the same wall, this is the wall explained. + +## The setup + +A single Docker stack on a Synology NAS, two browsers in it (real Chrome and Brave), each behind my own SSO gate: + +| Piece | Value | +|---|---| +| Image | `lscr.io/linuxserver/chrome` — real Google Chrome 154 | +| Desktop | Selkies web desktop, container `3000`/`3001` → host `3030`/`3031` | +| Automation | CDP published at `http://:9232/json/version` | +| Profile | a bind mount, `/config/profile` inside the container | +| Launch flags | `--remote-debugging-port=9222 --user-data-dir=/config/profile --restore-last-session` | + +The profile is a bind mount, so the logins, cookies and history genuinely do persist across a container rebuild — that part was never broken. Only the *session* (which tabs were open) was lost. + +## Attempt 1: the flag + +Chromium ships a switch that sounds like the answer: `--restore-last-session`. It is documented as "restore the last session *after an unexpected exit*". + +I added it via the image's CLI env var and confirmed it was actually applied to the running process, because these images build the command line from a wrapper script: + +```bash +docker exec chrome sh -c 'tr "\0" " " < /proc/$(pgrep -f "google-chrome --" | head -1)/cmdline' | tr ' ' '\n' | grep -E 'restore|user-data-dir|remote-debug' +# --remote-debugging-port=9222 +# --user-data-dir=/config/profile +# --restore-last-session +``` + +Restart. Blank tab. The flag was there; it just had nothing it was willing to restore. + +## Attempt 2: edit the profile's preferences + +Chrome stores "Continue where you left off" in the profile's `Preferences` JSON as `session.restore_on_startup: 1`. So I stopped the container and edited it directly, along with the `exit_type` marker: + +```python +import json +p = '/config/profile/Default/Preferences' +d = json.load(open(p)) +d.setdefault('session', {})['restore_on_startup'] = 1 # 1 = restore last session +d.setdefault('profile', {})['exit_type'] = 'Normal' +json.dump(d, open(p, 'w')) +``` + +This is the classic advice you will find online, and it half-worked: after the next boot, Chrome had **kept** `restore_on_startup: 1` in the file — and still opened a blank tab. What it did not keep was my `exit_type`: it had already rewritten that to `Crashed` at startup. + +That rewrite turned out to be the first real clue. Chrome treats startup state as a security boundary — the settings a hijacker would most like to change (homepage, search provider, startup pages) are MAC-checked against a separate `Secure Preferences` file. A value edited on disk does not automatically become a value Chrome obeys. + +## Attempt 3: a managed policy + +The supported way to force browser behaviour is a **managed policy**, which is authoritative and not subject to that MAC check. On Linux, Chrome reads `/etc/opt/chrome/policies/managed/*.json`: + +```json +{ "RestoreOnStartup": 1 } +``` + +Two details before you bother: Chrome ignores a policy file that is writable by the user running the browser, so it needs `root:root` and mode `644` — and on a Synology share, `chmod` refuses to run even under `sudo` for some directories, so verify the mode you already have instead of assuming you changed it. + +Mounted into the container, verified present after boot: + +```bash +docker exec chrome sh -c 'ls -l /etc/opt/chrome/policies/managed/; cat /etc/opt/chrome/policies/managed/hoeleepolicy.json' +# -rw-r--r-- 1 root root 28 hoeleepolicy.json +# { "RestoreOnStartup": 1 } +``` + +Restart. Blank tab. Still. + +## Attempt 4: prove the exit is ungraceful + +At this point the question stopped being "which setting do I need" and became "what does this browser actually see when the container stops". + +Chrome's restore machinery needs a session it considers *interrupted or resumable*. It rolls `Current Session` into `Last Session` on a clean exit. I asked the CDP endpoint to close the browser gracefully instead of pulling the container out from under it: + +```python +# browser-level target from /json/version +ws.send(json.dumps({"id": 1, "method": "Browser.close", "params": {}})) +``` + +Chrome exited — and the desktop session relaunched it within seconds. `exit_type` was back to `Crashed` immediately. + +That is the whole trick, and it explains all three failures: **the browser never exits cleanly.** When you stop the container, the desktop session is torn down and the browser is killed with it. No clean exit means no `Last Session` rollover, which means there is nothing for "continue where you left off" — or a `RestoreOnStartup` policy — to restore. The flag, the preference and the policy were all working correctly and all had nothing to work with. + +The data was never missing. The profile's session directory was being written continuously, seconds apart, the whole time: + +``` +-rw------- 1 hoelee users 40722 Session_13434833255312492 +-rw------- 1 hoelee users 58879 Tabs_13434833757632480 +-rw------- 1 hoelee users 79361 Tabs_13434833833646133 +``` + +## The fix: stop configuring, start keeping + +If the browser cannot be trusted to remember its own session, the container can remember it instead. Two jobs, both tiny: + +1. **On start**: wait for the browser, and if it came up with no real page open, re-open the URLs it had last time. +2. **Forever after**: every 60 seconds, snapshot the open page URLs. + +That is a background script launched from the image's container-init hook. The version I run, trimmed to the useful parts: + +```python +#!/usr/bin/env python3 +"""Restore last session's tabs on start, then snapshot open tabs every 60s.""" +import json, os, time, urllib.parse, urllib.request + +CDP = "http://127.0.0.1:9222" # loopback inside the container +STORE = "/config/tabs-last.txt" # lives in the persistent profile mount + +def open_tabs(): + """http(s) page URLs, or None when the browser isn't answering yet.""" + try: + with urllib.request.urlopen(CDP + "/json/list", timeout=5) as r: + tabs = json.load(r) + except Exception: + return None + return [t.get("url", "") for t in tabs + if t.get("type") == "page" and t.get("url", "").startswith("http")] + +saved = [u.strip() for u in open(STORE)] if os.path.exists(STORE) else [] + +# 1) restore — wait up to 3 minutes for the browser to come up +if saved: + for _ in range(60): + if open_tabs() is not None: + break + time.sleep(3) + if open_tabs() == []: # nothing but a blank new tab + for url in saved[:20]: + req = urllib.request.Request( + CDP + "/json/new?" + urllib.parse.quote(url, safe=""), method="PUT") + urllib.request.urlopen(req, timeout=10).read() + time.sleep(0.7) + +# 2) snapshot — write even an empty list, so "I closed everything" is respected +while True: + time.sleep(60) + tabs = open_tabs() + if tabs is None: + continue + tmp = STORE + ".tmp" + open(tmp, "w").write("\n".join(tabs) + ("\n" if tabs else "")) + os.replace(tmp, STORE) # atomic; a kill can't truncate it +``` + +Two design choices worth copying: + +- **Restore only when the browser came up empty.** If a future Chrome version *does* restore its own tabs, the keeper stays out of the way instead of duplicating every tab. +- **The snapshot is atomic and may be empty.** Writing through a temp file plus `os.replace` means a container killed mid-write cannot leave a truncated list, and an empty snapshot is meaningful data: it means you closed everything on purpose, so the next start should stay empty. + +The container-init hook that runs it: + +```sh +#!/bin/sh +# clear stale singleton state (see below) +rm -f /config/profile/Singleton* 2>/dev/null +# long-running, so background it or you block container init +/usr/bin/env python3 /custom-cont-init.d/tabs_keeper.py >> /config/tabs-keeper.log 2>&1 & +exit 0 +``` + +### Landmine 1: a stale `Singleton*` stops Chrome from starting at all + +While testing restarts I hit a worse failure than a blank tab: the container came up **healthy with no browser in it**. No `google-chrome` process, CDP dead, the relay's healthcheck reporting `unhealthy`, nothing in the logs beyond the desktop starting. + +The cause is the profile's `SingletonLock`/`SingletonSocket`/`SingletonCookie` symlinks. They encode "this profile is owned by PID *n* on host *h*" — and inside a container, PIDs are reused across restarts, so the next boot can find its own PID already claiming the profile and exit immediately. Deleting them at container start, before the browser launches, is the fix. It is also why that `rm -f` sits in the hook above. + +### Landmine 2: `custom-cont-init.d` only runs *executable* files — and runs them with bash + +The LinuxServer images execute every file in `/custom-cont-init.d`, but only if it is executable, and each one through `/bin/bash`. Which means a Python file you drop in there must **not** be executable, or it gets fed to bash and exits 2: + +``` +[custom-init] tabs_keeper.py: executing... +[custom-init] tabs_keeper.py: exited 2 +``` + +The split that works: a `.sh` hook at `755` that backgrounds the long-running work, and the `.py` next to it at `644`. And anything that does not return immediately has to be backgrounded, or container init waits on it forever. + +## The plumbing trap that came with it + +The keeper talks to Chrome over CDP on loopback, which is why it needs no ports. If you also want to drive the browser from another machine, there is one more container in the picture, because Chrome ≥ 136 pins its devtools endpoint to `127.0.0.1:9222` and ignores `--remote-debugging-address`. The standard workaround is a `socat` sidecar sharing the browser's network namespace: + +```yaml +chrome-relay: + image: alpine/socat + network_mode: service:chrome # must share the browser's netns + command: socat TCP-LISTEN:9223,fork,reuseaddr TCP:127.0.0.1:9222 + healthcheck: + test: ["CMD-SHELL", "nc -z 127.0.0.1 9222 || exit 1"] +``` + +The port mapping does **not** go on the relay (it has no namespace of its own) — it goes on the browser service: `9232:9223`. + +That sidecar has one behaviour you have to internalise: **restart the browser and the relay dies with it.** The namespace it was living in is rebuilt underneath it, socat keeps running and its sockets stop working, so CDP answers with `connection reset` while the container still looks fine. Fix the symptoms in this order: + +```bash +docker restart chrome && docker restart chrome-relay # order matters +``` + +The healthcheck above is what turns a silent failure into a visible `unhealthy` flag. If you want to drive a container browser yourself, I wrote the client side up separately in [Scraping a Bot-Walled Marketplace With a Warm Browser Session](/posts/scraping-bot-walled-marketplace-warm-browser-session/). + +## What I'd do differently + +- **Determine whether the process can exit cleanly before trusting any "restore on startup" mechanism.** I spent three attempts configuring a feature whose precondition — an exit the browser notices — was never met. One `Browser.close` test would have collapsed the whole search. +- **Don't hand-edit browser preferences.** They are MAC-checked against `Secure Preferences`; a plausible-looking value on disk is not a value Chrome obeys. If you need a switch to be authoritative, use a managed policy — and verify the policy is loaded instead of assuming the file is enough. +- **Check who is allowed to write the policy.** A root-owned `644` file in `/etc/opt/chrome/policies/managed` is the shape; a user-writable one is ignored silently. +- **Treat "the browser is running" and "the container is running" as different questions.** The stale-singleton failure looked like a healthy container from the outside. +- **Snapshot state instead of asking software to remember it.** Anything with a hard kill in its shutdown path — containers, kiosks, desktop sessions — is a poor place to rely on clean-exit bookkeeping. A 60-second atomic snapshot is boring, and it works. + +## The result + +- Tabs restored **2/2 on both browsers** across a real container restart (`restored 2/2 tabs` in the keeper log), verified over CDP afterwards +- Logins, cookies and `localStorage` confirmed surviving the same restarts — the persistent profile was never the problem +- Three stacks (two browsers plus a throwaway experiment) collapsed into one, with the relay's healthcheck making the one restart-order trap visible instead of silent + +## Want this for your business? + +If you want a browser that stays logged in — running on your own hardware, reachable from anywhere, behind SSO, with tab state that survives restarts and a CDP endpoint your scripts can drive — that is the setup I run and maintain. + +**WhatsApp: [+60 12-797 2969](https://wa.me/60127972969)** · **Email: [me@hoelee.com](mailto:me@hoelee.com?subject=Self-hosted%20container%20browser)** · **[hoelee.com](https://hoelee.com)** + +Website design and development is my main line of work; self-hosted infrastructure and automation is the other half of it. +```` + +--- + +## 文章 11 / 11:Telegram 机器人通知为什么发不出去:IPv6、DNS 和一个折腾了一整天的 400 +- **Slug**: `why-telegram-bot-notifications-die` +- **英文标题**: Why Telegram Bot Notifications Die: IPv6, DNS, and a 400 That Took a Day +- **分类**: `devops` | **发布日期**: 2026-03-25 +- **线上地址**: https://blog.hoelee.com/posts/why-telegram-bot-notifications-die/ (EN) | https://blog.hoelee.com/posts/zh/why-telegram-bot-notifications-die/ (ZH) +- **本篇审核状态**: ⏳ 待审核 (Pending) + +### ✍️ 顾问审阅意见区 (Review Feedback) +```text +【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 +【事实与数字核对】: +【人设与用词卫生】: +【CRO与转化建议】: +``` + +### 🇨🇳 中文版原文 (Chinese Markdown Twin) +````markdown +--- +title: "Telegram 机器人通知为什么发不出去:IPv6、DNS 和一个折腾了一整天的 400" +description: "一次排障记录:一个跑在 Docker 里的 Telegram 监控机器人,sendPhoto 一直返回 nginx/1.30.1 的 400,但 getMe 却正常——根因是只返回 IPv6 的 DNS 应答、一个写错的 extra_hosts IP,以及一个用 join 拼接破坏了 JPEG 二进制数据的 multipart body。" +pubDate: 2026-03-25 +updatedDate: 2026-09-09 +category: devops +blueprint: ai-agent-automation +blueprintLayer: L1-deterministic-orchestration +tags: [docker, telegram, python, dns, ipv6, debugging, portainer] +ogImage: /og/zh-why-telegram-bot-notifications-die.jpg +banner: /banners/why-telegram-bot-notifications-die.jpg +--- + +我跑着一个小监控机器人,专门盯着 Carousell 上新上架的商品,一旦有新品就通过 +Telegram 通知我。有一天它突然不再通知了。容器本身是健康的,爬虫也照常往 +NocoDB 里归档商品——但每一条通知都以日志里那三个字符宣告失败: + +``` +telegram sendPhoto failed: 400 ... nginx/1.30.1 +``` + +`nginx/1.30.1` 这个字符串,成了我接下来一整天排障的"反派"。这是一个看似 +微不足道的 bug,实际却是由三个问题层层堆叠而成的故事——以及下一次我会 +如何更快地逐个定位它们。 + +## 问题本身 + +这个机器人有两件事要做:**采集**商品,以及**通知**我。采集正常,通知挂了。 +日志显示 `400 Bad Request`,并指向一个自称 `nginx/1.30.1` 的服务器。 + +我的第一反应很教科书:**网络里有什么东西在拦截请求。** 因为 +`nginx/1.30.1` 这个 header 跟我印象里的 Telegram API 对不上——而且一个 +带 HTML 响应体的 400(Telegram 就算出错也返回 JSON)看起来就像本地反向 +代理或 VPN 网关在请求还没离开机器之前就把它拒掉了。 + +这种假设很省力,但也常常是错的。下面说说我到底发现了什么。 + +## 我尝试了什么,以及为什么每个都失败了 + +### 第一轮:一定是 DNS / IPv6 + +我先在容器里跑了 `getMe`——它能通。然后又跑了 `sendMessage`——它挂了。 +同一个 token、同一个容器,一个方法通、一个方法挂。 + +线索藏在两个端点的解析方式里: + +``` +# 容器内部 +$ getent hosts api.telegram.org +2001:67c:4e8:f004::9 api.telegram.org +``` + +容器把 `api.telegram.org` 解析成了**只有 IPv6**——一条 `AAAA` 记录, +没有 `A` 记录。而容器跑在一个 **没有 IPv6 连通性的** Docker bridge +网络上。于是每个需要访问 `api.telegram.org` 的请求,都在试图连接一个 +它根本走不到的 IPv6 地址。 + +修复看起来很简单:用 `extra_hosts` 把 IPv4 地址钉死。我照做了,DNS +应答变得完全符合预期: + +``` +149.154.167.220 api.telegram.org +``` + +结果通知**还是失败**,同一个 400。我那得意的修复啥也没改变。 + +### 第二轮:我选错了 IP + +这里有一个值得记住的教训:我是**凭记忆**硬编码了 `149.154.167.220`。 +等我终于去查公共解析器时,`api.telegram.org` 真正的 `A` 记录并不是它: + +``` +149.154.166.110 api.telegram.org # DNS 实际返回的 +149.154.167.220 api.telegram.org # 我硬编码的 +``` + +`167.220` 确实**在** Telegram 的 IP 段内(`149.154.160.0/20`),所以它 +并不是"别人的服务器"这种错——但它不是当前活跃的端点,bot-API 的流量打到 +它上面的行为是不可预测的。我把它换成 `166.110`,仍然失败。所以 IP 也 +不是全部原因。 + +### 第三轮:同样的命令,两个相反的结果 + +这是整个事情开始变得诡异的一刻。在同一个容器里,几乎同一秒: + +- **常驻的监控进程**(`PID 1`)→ `sendPhoto` 失败,400 +- 一个**新起的 `docker exec` 进程**跑着完全相同的代码 → `sendPhoto` + 成功,200 + +同一个容器、同样的代码、同样的 payload、同一秒。 + +我逐一排除了 token、chat_id、caption 里的 emoji、Unicode 引号、图片格式、 +环境变量、以及图片 URL 本身——我把那张图下载下来测过,是一张完全合法的 +JPEG。两条路径的代码没有任何差别。 + +当你撞上这种"输入相同、输出相反"的矛盾时,答案通常是:**输入其实并不 +相同**。但找到那个差异,还需要我再换一次思路。 + +### 第四轮:`nginx/1.30.1` 就是 Telegram + +我重新读了原始的 400 响应,而不是去猜。响应是一张 HTML 的 +"400 Bad Request" 页面,`Server` 头是 `nginx/1.30.1`。 + +**那个 nginx 就是 Telegram 自家的边缘服务器。** Telegram 的 API 背后就是 +nginx(版本 1.30.1),当一个请求在到达它们应用层**之前**就已经畸形时, +nginx 会自己回一张 400 页面——没有 JSON,也没有友好的错误码。 + +这一下彻底改变了整个视角。请求并没有被拦截,而是**确实到达了 Telegram, +然后被 Telegram 的 nginx 以"畸形"为由拒绝了**。 + +而那个畸形的东西,正是我一直没仔细看的部分:`sendPhoto` 的 multipart +请求体。 + +## 修复 + +我最初的代码是这样拼 multipart 请求体的——正是那种"看着显然没问题"、 +实则埋下微妙 bug 的一行: + +```python +body = b"\r\n".join(body_lines) +``` + +这个 `join` 看起来很省事,但 JPEG 是**二进制数据**。它的字节里本身就包含 +`\r\n` 这样的字节序列,出现在图片数据中间。用 `\r\n` 作为分隔符去 join, +就把本该是图片 payload 的字节给破坏了。Telegram 收到的是一个 multipart +边界被破坏的请求体,于是它的 nginx 在 bot API 还没来得及解析之前就回了个 +400。 + +正确的做法是逐字段拼装 body,让二进制数据保持原样: + +```python +boundary = "----tg" + token_hex(8) + +parts = [] +parts.append(f"--{boundary}\r\n".encode()) +parts.append(b'Content-Disposition: form-data; name="chat_id"\r\n\r\n') +parts.append(f"{chat_id}\r\n".encode()) + +parts.append(f"--{boundary}\r\n".encode()) +parts.append(b'Content-Disposition: form-data; name="caption"\r\n\r\n') +parts.append(f"{caption}\r\n".encode()) + +parts.append(f"--{boundary}\r\n".encode()) +parts.append( + b'Content-Disposition: form-data; name="photo"; ' + b'filename="image.jpg"\r\nContent-Type: image/jpeg\r\n\r\n' +) +parts.append(image_bytes) # ← 二进制保持二进制 +parts.append(b"\r\n") + +parts.append(f"--{boundary}--\r\n".encode()) + +body = b"".join(parts) # join 的是字节块,不是行 +``` + +区别在于用 `b"".join(parts)` 而不是 `b"\r\n".join(...)`:每一块本身就是 +一个带完整边框的片段,我们只是把它们的字节**原样拼接**,而不是在 +**每个元素之间**都插入一个分隔符。 + +还有一个更高层的修复值得点名:**别再让 Telegram 替你去下载图片。** 我 +早期的代码是把图片当作 *URL* 传过去,让 Telegram 自己去抓: + +```python +tg("sendPhoto", {"photo": image_url, "caption": caption}) +``` + +这意味着 Telegram 的服务器得主动去访问源 CDN——如果那个 CDN 不稳定、 +或者对 Telegram 的爬虫做了地域封锁,你就会得到本地根本无法复现的间歇性 +失败。自己先把图片下载下来、再上传字节,就消除了一整类的不稳定因素, +还给了你在发送前校验字节的机会。 + +## 如果重来一次我会怎么做 + +1. **读原始响应,而不是读假设。** `nginx/1.30.1` 在日志里躺了好几个小时, + 我却在追一个根本不存在的中间人。在凭空捏造拦截者之前,先查清楚那个 + header 到底属于谁。 +2. **对硬编码的 IP 用实时解析器验证。** 记忆不是 DNS。`dig +short + api.telegram.org` 只要三秒钟,就能省掉我整整一轮。 +3. **把"输入相同、输出相反"当成谎言。** 输入从来就不相同——两个进程在某 + 个我没看到的地方有差异。诚实的做法是去 diff 字节,而不是 diff 代码。 +4. **永远不要用文本分隔符去手工拼接二进制数据。** 把文本和 JPEG 混在一起 + 做 `b"\r\n".join()`,迟早会出破坏 bug。 + +## 结果 + +multipart 修复之后,监控机器人在下一个 tick 就真正把通知发出去了—— +图片和文字都在。我还一并加了一个重试队列:一条失败的通知会保持"未发送" +状态,30 秒后自动重试,而不是悄无声息地消失。整件事耗掉了大半天的功夫, +但它变成了那种我这辈子不会再踩第二次的坑。 + +--- + +*这个机器人是我个人的项目,但教训可以推广到任何依赖外发通知的服务。如果你 +有一个监控、抓取,或者需要可靠地触达用户的告警管线,我们可以聊聊。* + +**我搭建可靠的监控与通知管线——Telegram/WhatsApp 告警、抓取器,以及背后的 +基础设施。** 告诉我你要监控什么、通知要发到哪里: + +- [WhatsApp 联系 →](https://wa.me/60127972969?text=Hi%20Hoelee%2C%20I%20need%20a%20monitoring%2Fnotification%20pipeline) +- [Email 联系 →](mailto:me@hoelee.com?subject=Monitoring%20%2F%20notification%20pipeline) +- [hoelee.com](https://www.hoelee.com) +```` + +### 🇬🇧 英文版原文 (English Markdown Primary) +````markdown +--- +title: "Why Telegram Bot Notifications Die: IPv6, DNS, and a 400 That Took a Day" +description: "A debugging story: a Dockerized telegram monitor whose sendPhoto calls returned 400 from nginx/1.30.1 while getMe worked fine — an IPv6-only DNS answer, a wrong extra_hosts IP, and a multipart join that corrupted JPEG bytes." +pubDate: 2026-03-25 +updatedDate: 2026-09-09 +category: devops +blueprint: ai-agent-automation +blueprintLayer: L1-deterministic-orchestration +tags: [docker, telegram, python, dns, ipv6, debugging, portainer] +ogImage: /og/why-telegram-bot-notifications-die.jpg +banner: /banners/why-telegram-bot-notifications-die.jpg +--- + +I run a small monitoring bot that watches Carousell for newly-listed +listings and pings me on Telegram when something fresh appears. One day it +stopped pinging. The container was healthy, the scraper was still archiving +listings into NocoDB — but every notification died with the same three +characters in the log: + +``` +telegram sendPhoto failed: 400 ... nginx/1.30.1 +``` + +That string, `nginx/1.30.1`, became the villain of a day-long debugging +session. This is the story of how a deceptively small bug turned out to be +three separate problems stacked on top of each other — and how I'd find each +one faster next time. + +## The problem + +The bot had two jobs: **collect** listings, and **notify** me. Collection +worked. Notification didn't. The log said `400 Bad Request` and pointed at a +server identifying itself as `nginx/1.30.1`. + +My first assumption was textbook: **something in the network is intercepting +the request.** `nginx/1.30.1` is not a header I associated with Telegram's +API. A 400 with an HTML body (Telegram returns JSON even on errors) smelled +like a local reverse proxy or a VPN gateway rejecting traffic before it ever +left the machine. + +Assumptions like that are cheap. They're also wrong a lot. Let me walk +through what I actually found. + +## What I tried, and why each thing failed + +### Round 1: it must be DNS / IPv6 + +I checked `getMe` from inside the container. It worked. Then I checked +`sendMessage`. It failed. Same token, same container, one method up, one down. + +The giveaway was in how the two endpoints resolved: + +``` +# inside the container +$ getent hosts api.telegram.org +2001:67c:4e8:f004::9 api.telegram.org +``` + +The container resolved `api.telegram.org` to **IPv6 only** — a single `AAAA` +record and no `A` record. The container ran on a Docker bridge network with +**no IPv6 connectivity**. So every request that needed `api.telegram.org` was +trying to reach an IPv6 address it had no route to. + +The fix looked obvious: pin the IPv4 address with `extra_hosts`. I did, and +the DNS answer became exactly what I expected: + +``` +149.154.167.220 api.telegram.org +``` + +And the notifications **still failed.** Same 400. My proud fix did nothing. + +### Round 2: I picked the wrong IP + +Here's a mistake worth remembering: I hard-coded `149.154.167.220` from +memory. When I finally queried a public resolver, the real `A` record for +`api.telegram.org` was different: + +``` +149.154.166.110 api.telegram.org # what DNS actually says +149.154.167.220 api.telegram.org # what I hard-coded +``` + +`167.220` is *inside* Telegram's IP range (`149.154.160.0/20`), so it's not +"wrong" in the sense of being somebody else's server — but it's not the +active endpoint, and bot-API traffic to it behaved unpredictably. I switched +to `166.110`. It still failed. So the IP wasn't the whole story either. + +### Round 3: the same command, two different outcomes + +This was the moment the whole thing got weird. Inside one container, at +almost the same second: + +- the **long-running monitor process** (`PID 1`) → `sendPhoto` failed, 400 +- a **fresh `docker exec` process** running identical code → `sendPhoto` + succeeded, 200 + +Same container. Same code. Same payload. Same second. + +I ruled out token, chat_id, emoji in the caption, Unicode quotes, image +format, environment variables, and the image URL itself — I download-tested +the photo and it was a perfectly valid JPEG. Nothing in the code differed +between the two paths. + +When you hit a contradiction like that — "identical inputs, opposite +outputs" — the answer is usually that the inputs *aren't* identical. But +finding the difference took one more frame change. + +### Round 4: `nginx/1.30.1` is Telegram + +I re-read the raw 400 response instead of assuming. The response was an HTML +"400 Bad Request" page, and the `Server` header was `nginx/1.30.1`. + +**That nginx is Telegram's own edge.** Telegram's API sits behind nginx +(version 1.30.1), and when a request is malformed *before* it reaches their +application layer, nginx itself answers with a plain 400 page — no JSON, no +friendly error code. + +That reframed everything. The request wasn't being intercepted. It was +**reaching Telegram, and Telegram's nginx was rejecting it as malformed.** + +And the malformed thing was the one part I hadn't scrutinized: the +`sendPhoto` multipart body. + +## The fix + +My original code built the multipart body like this — the kind of +"obviously fine" line that ships a subtle bug: + +```python +body = b"\r\n".join(body_lines) +``` + +That `join` looks convenient, but a JPEG is **binary data**. Its bytes include +`\r\n` byte sequences in the middle of the image data. Joining with `\r\n` +as the delimiter corrupts the exact bytes that are supposed to be the image +payload. Telegram receives a body whose multipart boundaries are broken, so +its nginx rejects the request with a 400 before the bot API ever parses it. + +The correct approach is to assemble the body field by field, keeping binary +data untouched: + +```python +boundary = "----tg" + token_hex(8) + +parts = [] +parts.append(f"--{boundary}\r\n".encode()) +parts.append(b'Content-Disposition: form-data; name="chat_id"\r\n\r\n') +parts.append(f"{chat_id}\r\n".encode()) + +parts.append(f"--{boundary}\r\n".encode()) +parts.append(b'Content-Disposition: form-data; name="caption"\r\n\r\n') +parts.append(f"{caption}\r\n".encode()) + +parts.append(f"--{boundary}\r\n".encode()) +parts.append( + b'Content-Disposition: form-data; name="photo"; ' + b'filename="image.jpg"\r\nContent-Type: image/jpeg\r\n\r\n' +) +parts.append(image_bytes) # ← binary stays binary +parts.append(b"\r\n") + +parts.append(f"--{boundary}--\r\n".encode()) + +body = b"".join(parts) # join bytes, not lines +``` + +The difference is `b"".join(parts)` instead of `b"\r\n".join(...)`: each part +is already a complete chunk with its own framing, and we concatenate them +verbatim rather than inserting a delimiter *between every element*. + +There's a second, higher-level fix worth naming: **stop asking Telegram to +download the image for you.** My earlier code passed the image as a *URL* and +let Telegram fetch it: + +```python +tg("sendPhoto", {"photo": image_url, "caption": caption}) +``` + +That means Telegram's servers have to reach out to the source CDN — and if +that CDN is flaky or geo-blocks Telegram's crawlers, you get intermittent +failures that are impossible to reproduce locally. Downloading the image +yourself, then uploading the bytes, removes an entire class of flakiness and +gives you a chance to validate the bytes before you send them. + +## What I'd do differently + +1. **Read the raw response, not the assumption.** `nginx/1.30.1` sat in logs + for hours while I chased phantom proxies. Look up who owns the header + before inventing a man-in-the-middle. +2. **Verify a hard-coded IP against a live resolver.** Memory is not DNS. + `dig +short api.telegram.org` takes three seconds and would have saved me + a whole round. +3. **Treat "identical inputs, opposite outputs" as a lie.** The inputs were + never identical — the two processes differed somewhere I wasn't looking. + The honest move is to diff the bytes, not the code. +4. **Never hand-join binary data with a text delimiter.** `b"\r\n".join()` on + a mix of text and JPEG is a corruption bug waiting to happen. + +## The result + +After the multipart fix, the monitor pushed a real notification through on +the next tick — image and all. I also folded in a retry queue so a failed +notification stays marked un-sent and is retried 30 seconds later instead of +silently vanishing. The whole episode cost the better part of a day, but it +turned into exactly the kind of bug I'll never trip over twice. + +--- + +*The bot is a personal project, but the lesson generalizes to any service +that relies on outbound notifications. If you've got a monitor, a scraper, or +an alert pipeline that needs to reach people reliably, let's talk.* + +**I build reliable notification and monitoring pipelines — Telegram/WhatsApp +alerts, scrapers, and the infrastructure around them.** Tell me what you need +to watch and where you need it delivered: + +- [WhatsApp me →](https://wa.me/60127972969?text=Hi%20Hoelee%2C%20I%20need%20a%20monitoring%2Fnotification%20pipeline) +- [Email me →](mailto:me@hoelee.com?subject=Monitoring%20%2F%20notification%20pipeline) +- [hoelee.com](https://www.hoelee.com) ```` --- diff --git a/docs/consultant-review/batches/batch-03.md b/docs/consultant-review/batches/batch-03.md index d8c67a3..0af7d74 100644 --- a/docs/consultant-review/batches/batch-03.md +++ b/docs/consultant-review/batches/batch-03.md @@ -2,9 +2,9 @@ > **批次编号**:`Batch-03` > **包含文章数**:11 篇 -> **本批次总字符量**:171,890 字(严格限制 < 200,000 字) +> **本批次总字符量**:167,652 字(严格限制 < 200,000 字) > **模式**:BILINGUAL -> **生成时间**:2026-10-27 03:02:03 +> **生成时间**:2026-10-27 04:23:31 # 外部顾问审阅前置须知与工程背景规范 @@ -39,25 +39,25 @@ ## 本批次文章目录索引 -1. [case-studies] **代码只让一个 AI 改:我是如何避开多 Agent 协同踩坑的「单写多审」架构** (`the-single-writer-rule-for-coding-agents`) — ~20,184 字符 -2. [case-studies] **什么时候该让 AI 操控物理鼠标(以及什么时候绝对不要用)** (`when-to-give-your-agent-physical-clicks`) — ~10,447 字符 -3. [case-studies] **为什么我要做视频精读知识库:把收藏夹吃灰的短视频变成可检索笔记** (`why-i-built-a-video-knowledge-base`) — ~8,631 字符 -4. [case-studies] **为什么你的无头浏览器不是万能爬虫** (`why-your-headless-browser-cant-scrape-everything`) — ~11,856 字符 -5. [devops] **一个字符让我的 authentik CSS 静默失效** (`authentik-css-greater-than-bug`) — ~14,691 字符 -6. [devops] **验证完全正确的 Forward-Auth 网关——其实并未上线** (`authentik-forward-auth-gate-wasnt-live`) — ~25,254 字符 -7. [devops] **Authentik 从 2025.8 升级到 2026.8:那些没人提醒你会坏掉的部分** (`authentik-major-upgrade-gotchas`) — ~17,725 字符 -8. [devops] **不用界面管理 CyberPanel:逆向一个没有文档的 v2 API** (`automating-cyberpanel-without-the-ui`) — ~13,718 字符 -9. [devops] **Docker 报告退出码 0,内核却早已执行 OOM-Kill** (`docker-reported-exit-0-the-oom-killer-disagreed`) — ~15,666 字符 -10. [devops] **每个播放器都在同一个视频上卡顿,而文件本身是无辜的** (`every-player-stuttered-the-file-was-fine`) — ~11,805 字符 -11. [devops] **加固 Tor 洋葱服务:真正重要的是什么** (`hardening-a-tor-onion-service`) — ~21,913 字符 +1. [devops] **为什么你的 CDP 点击会静默失效:平滑滚动、最小化窗口与 JS 派发事件** (`why-your-cdp-clicks-silently-fail`) — ~12,514 字符 +2. [devops] **Prometheus 明明有数据,Grafana 面板却全是 No data 的原因** (`why-your-grafana-dashboard-shows-no-data`) — ~11,212 字符 +3. [devops] **你的“磁盘将满”告警在说谎:别再按百分比告警** (`your-disk-full-alert-is-lying`) — ~8,912 字符 +4. [engineering] **浏览器翻译没有 API:我给一个纯中文网页应用加上了英文模式** (`adding-english-mode-to-a-chinese-only-web-app`) — ~18,070 字符 +5. [engineering] **排查 Remotion 视频抽搐:为什么在背景图挂载音频低频 Scale 会毁了转场** (`debugging-remotion-video-jitter`) — ~15,111 字符 +6. [engineering] **把字体嵌进 PDF,让它在任何机器上都长一样** (`embedding-fonts-so-a-pdf-looks-the-same-everywhere`) — ~11,465 字符 +7. [engineering] **那个把静默丢失更新变成 409 的 JPA 字段:@Version 乐观锁** (`jpa-version-field-lost-update`) — ~19,575 字符 +8. [engineering] **把 CodeIgniter 4 应用从 IIS 迁移到 OpenLiteSpeed** (`migrating-codeigniter-iis-to-openlitespeed`) — ~23,361 字符 +9. [engineering] **用「热浏览器会话」爬取有反爬墙的电商网站** (`scraping-bot-walled-marketplace-warm-browser-session`) — ~16,928 字符 +10. [engineering] **JavaScript 文件静默失效的两种方式:而页面看上去一切正常** (`two-ways-a-javascript-file-stops-working-and-looks-fine`) — ~11,294 字符 +11. [engineering] **逐页验证一份 19 页的 PDF 报告** (`verifying-a-pdf-report-page-by-page`) — ~19,210 字符 --- -## 文章 01 / 11:代码只让一个 AI 改:我是如何避开多 Agent 协同踩坑的「单写多审」架构 -- **Slug**: `the-single-writer-rule-for-coding-agents` -- **英文标题**: The Single-Writer Rule: Orchestrating Coding Agents Without Multi-Agent Chaos -- **分类**: `case-studies` | **发布日期**: 2026-08-26 -- **线上地址**: https://blog.hoelee.com/posts/the-single-writer-rule-for-coding-agents/ (EN) | https://blog.hoelee.com/posts/zh/the-single-writer-rule-for-coding-agents/ (ZH) +## 文章 01 / 11:为什么你的 CDP 点击会静默失效:平滑滚动、最小化窗口与 JS 派发事件 +- **Slug**: `why-your-cdp-clicks-silently-fail` +- **英文标题**: Why Your CDP Clicks Silently Fail: Smooth Scroll, Minimised Windows, and JS-Dispatched Events +- **分类**: `devops` | **发布日期**: 2025-03-19 +- **线上地址**: https://blog.hoelee.com/posts/why-your-cdp-clicks-silently-fail/ (EN) | https://blog.hoelee.com/posts/zh/why-your-cdp-clicks-silently-fail/ (ZH) - **本篇审核状态**: ⏳ 待审核 (Pending) ### ✍️ 顾问审阅意见区 (Review Feedback) @@ -71,2724 +71,2402 @@ ### 🇨🇳 中文版原文 (Chinese Markdown Twin) ````markdown --- -title: "代码只让一个 AI 改:我是如何避开多 Agent 协同踩坑的「单写多审」架构" -description: "为什么让多个 AI Agent 同时写代码必然导致分支冲突与隐式失真?深度拆解「单写进程 + 独立素材子进程 + 对抗式代码审查」实战架构。" -pubDate: 2026-08-26 -updatedDate: 2026-10-25 -category: case-studies -blueprint: ai-agent-automation -blueprintLayer: L2-llm-gateway-agents -tags: ["ai", "agents", "architecture", "devops"] -ogImage: "/og/zh-the-single-writer-rule-for-coding-agents.jpg" -banner: "/banners/the-single-writer-rule-for-coding-agents.jpg" -draft: false ---- - -## 为什么这至关重要 - -当开发团队刚开始尝试 AI 编程代理(Coding Agents)时,直觉上的下一步往往是“开一整队”:如果一个 Agent 在 10 分钟内能写好一个功能,那么同时启动 4 个 Agent 并行协作,岂不是 3 分钟就能搞定整个里程碑? - -但在生产环境中,现实往往截然相反。让多个自主 Agent 同时向同一个代码仓库提交修改,会迅速产生 Git 合并冲突、重复抽象、隐式逻辑回归以及令人咋舌的 Token 账单浪费。协同造成的损耗会彻底吞噬并行带来的速度收益。 - -然而,如果只跑一个单一 Agent 到底,又会撞上致命的瓶颈:**上下文污染(Context Pollution)**。当同一个 Agent 既要搜寻文档、格式化资源、又要反复调试代码时,其工作记忆(Context Window)很快就会被塞满。长上下文检索精度断崖式下跌,幻觉频发,它会迅速遗忘最初设定的系统架构约束。 - -在过去一年管理生产基础设施、客户端系统与业务自动化的过程中,我通过推行**单写规则(Single-Writer Rule)**彻底解决了这一两难困境: -1. **严格独占单写**:任何时刻,只有**一个** Agent 拥有代码仓库的文件写入锁与修改权。 -2. **素材外包隔离**:只读子 Agent 并行处理沉重的文档检索、ComfyUI 生图与语音合成,保护主 Agent 上下文。 -3. **高阶对抗审查**:由完全干净的顶级推理模型(如 Gemini 4 Argon)对 Git Diff 进行对抗式挑刺。 -4. **代码图谱索引**:引入预先索引的 AST 代码知识图谱(`codegraph`),精确检索符号引用,将 Prompt 消耗压缩到极致。 - -以下是该架构的完整设计、踩坑复盘与可落地的工程实现。 - ---- - -## 多代理人悖论:Cognition 对决 Anthropic - -2025 年年中,两家领先的 AI Agent 团队在 48 小时内相继发表了结论针锋相对的技术长文。 - -Anthropic 发布研究表明,在复杂的研究型任务中,一组协同的子代理团队相较于单一 Claude Opus 模型,综合表现提升了 **90%**。主管代理人将庞大的目标拆分子任务,分配给底层子代理人并行查阅资料,汇总摘要,从而彻底保护了主管的上下文空间。 - -然而仅仅一天前,开发出 Devin 的 Cognition 团队发表了业内著名的檄文:《*Don't Build Multiagent*》(不要构建多代理人)。他们的核心论点非常明确:在真实的软件工程领域,让多个 Agent 同时写代码最终会沦为一场荒谬的“传话游戏(Telephone Game)”,导致架构隐式失真、决策冲突,最终撕裂代码库。 - -两边的结论在各自的场景下其实完全正确: -- **资料研究与信息提取**天然是分块且只读的。Agent A 查阅上市公司名单,对 Agent B 没有任何副作用与状态冲突。 -- **软件开发**则是强状态、深耦合的精密网络。如果子 Agent A 在重构数据库模式,而子 Agent B 还在按旧模式写 API 控制器,两者合入主干的结果只能是灾难。 - -更关键的是,Anthropic 在文章中坦白了一个事实:多 Agent 系统所消耗的 Token 大约是普通单次交互的 **15 倍**;而在特定基准测试中,光是算力与 Token 消耗的增加,就能解释 **80%** 的表现差距。 - -如果不解决代码写入冲突,仅仅堆叠几十个 Agent,你只是在花 15 倍的成本,快速生产出更难排查的 Bug。 - ---- - -## 惨痛教训:多 Agent 写代码的三大陷阱 - -在收敛到当前架构之前,我曾在真实业务代码库中实测过多 Agent 蜂群协作。所有的翻车都可以归结为以下三个结构性陷阱: - -### 1. 传话游戏(The Telephone Game) - -主管 Agent 接收人类工程师的需求后,为了分工,必须向下属 Agent 传达任务便签。 - -``` -用户需求(包含明确约束与隐式业务边界) - ↓ -主管 Agent 摘要(产生信息抽象与损耗) - ↓ -子 Agent 自由发挥(基于残缺便签产生幻觉假设) -``` - -到了第三层,诸如“必须向下兼容旧版客户端”或“类型定义必须严格匹配 DB 约束”等隐性常识荡然无存。子 Agent 确实百分之百完成了它便签上写的字面任务,但整体拼装时完全无法运行。 - -### 2. 隐式架构决策漂移(Architectural Drift) - -以构建一个看似简单的前端组件为例: -- 子 Agent A 负责界面容器与样式编写。 -- 子 Agent B 负责状态流转与事件监听。 - -两个 Agent 各自独立推进。Agent A 决定采用现代 Tailwind CSS 原子化类名布局;Agent B 却默认项目依赖传统的 BEM 规范,并在 JS 中直接操作特定的 DOM 类名做渐变动画。 - -两边各自的代码语法全对,本地单元测试全部亮绿灯。但当最终集成时,界面完全错位崩塌。它们没有共享实时的架构共识,而每一次敲击键盘都在暗中做出互斥的架构决策。 - -### 3. Git 合并地狱与死锁 - -当三个 Agent 同时修改代码时,它们不可避免地会在共享文件(如路由注册表、中央类型声明、依赖清单)上产生修改碰撞。 - -人类开发者面对 Git 冲突能通过业务常识进行语义级合并。而 AI 在自主解决冲突时,极易直接把前一个 Agent 刚写好的函数整块删掉、或者为了让测试通过而凭空臆造全局变量,最终陷入无休止的自我纠错循环。 - ---- - -## 破局之道:单写多审(Single-Writer)生产架构 - -为了兼顾开发吞吐量与系统稳定性,我将整个研发管线解耦为三个职责明确的角色,并确立了一条不可动摇的底线:**任何时刻,全系统仅有一个进程持有文件修改权限**。 - -``` - ┌────────────────────────┐ - │ 人类需求与目标 │ - └───────────┬────────────┘ - │ - ▼ -┌─────────────────────────────────────────────────────────────────────────────┐ -│ 主写进程(SINGLE WRITER) │ -│ │ -│ • 独占文件写入锁与 Git 工作树 │ -│ • 通过 AST Code Graph 精准按符号查询依赖拓扑 │ -│ • 下发只读、无副作用的任务给后台子 Worker │ -│ • 负责打补丁、运行本地测试并生成统一 Diff │ -└──────────────┬──────────────────────────────────────────────▲───────────────┘ - │ │ - 派发任务 │ (异步只读素材) 纯净 Diff 审查 │ (严格阻断闸门) - ▼ │ -┌──────────────────────────────┐ ┌───────────────┴───────────────┐ -│ 素材与调研 Worker │ │ 对抗式代码审查员 │ -│ │ │ │ -│ • 第三方文档与 API 抓取 │ │ • 独立高阶推理大模型 │ -│ • 本地 ComfyUI 生图 / 渲染 │ │ (如 Gemini 4 Argon) │ -│ • 本地 SenseVoice / TTS 处理 │ │ • 零上下文历史包袱 │ -│ • 极度纯净的短时运行环境 │ │ • 专职挑毛病、查泄露、判边界 │ -└──────────────────────────────┘ └───────────────────────────────┘ -``` - -### 核心 1:独占主写 Agent(Single Writer) - -主写 Agent 是整个系统里唯一能调用 `patch`、`write_file` 以及 Git 操作工具的实体。 - -由于它是唯一的写作者,它对代码库当前的修改状态拥有单调递增的完整掌控。没有后台文件竞态、没有幽灵锁定,更不会出现分支合并时代码被莫名冲掉的情况。 - -### 核心 2:并行的素材与调研 Worker(Asset Workers) - -在全栈开发中,大量消耗 Context 的并非写代码本身,而是外部繁琐操作: -- 抓取第三方 API 的海量接口文档。 -- 调度本地 ComfyUI 工作流生成界面封面与插图。 -- 提取音频文件并转录文字(如 SenseVoice 逐字稿)。 - -如果把这些巨量的 HTTP 原始响应、音频张量或 Base64 塞进主写 Agent 的上下文,它的记忆立刻就会爆满。 - -通过将这些工作外包给独立的子 Worker,子进程在临时隔离环境中运行,将最终产物(图片、音频、结构化 JSON)直接落地到磁盘上的确定性路径,并仅仅向主写 Agent 返回一个文件句柄。主写 Agent 的上下文永远维持纯净,只用来推理核心业务逻辑。 - -### 核心 3:对抗式代码审查员(Adversarial Reviewer) - -当一个开发者(无论是人类还是 AI)为了调试某个复杂逻辑连续折腾了 20 轮对话后,他必然会产生严重的认知盲区:因为他清楚自己为此付出了多少心血,他会本能地倾向于认为自己的补丁是正确的。 - -当主写 Agent 验证本地测试全部通过后,它会将生成的 `git diff` 提交给**对抗式审查员**。 - -审查员调用顶层推理模型(如 Gemini 4 Argon 或 Claude 3.5 Sonnet),且拥有**绝对空白纯净的上下文**。它只接收两样东西: -1. 原始任务目标。 -2. 统一的标准 Git 补丁(Diff)。 - -它没有经历开发过程中的任何挫折与认知妥协,唯一的指令就是以极其挑剔的眼光寻找潜在内存泄漏、未捕获异常、边界漏洞与破坏性变更。一旦审查员亮红灯,反馈会直接递交主写 Agent 修改,直至完全绿灯才允许推送发布。 - -### 核心 4:预索引 AST 代码知识图谱(`codegraph`) - -为了彻底杜绝主写 Agent 在 5 万行代码库里使用盲目的全局全文检索,我们接入了 `colbymchenry/codegraph`。 - -在修改代码前,Agent 通过代码图谱查询特定函数或类的调用方(Callers)、被调用方(Callees)以及继承关系。图谱仅返回精确的 AST 节点与接口签名(单次通常仅耗费 100~150 Tokens),直接省去了向 Context 盲目灌入几十个源码文件(动辄 30,000~50,000 Tokens)的巨大浪费。 - ---- - -## 生产实测指标对比 - -我们在相同的全栈功能开发任务下,针对传统单 Agent、蜂群多 Agent 以及本套架构进行了实测对比: - -| 评估指标 | 自由多 Agent 蜂群 | 传统单一 Agent | 单写多审 + 图谱索引架构 | -|---|---|---|---| -| **Git 合并冲突次数** | 14 次 / 任务 | 0 次 | **0 次** | -| **平均 Token 消耗** | ~480,000 | ~85,000 | **~62,000**(得益于图谱精准裁剪) | -| **上下文溢出/遗忘崩溃** | 极高(记忆迅速污染) | 中等(长任务难收敛)| **0 次(完美收敛)** | -| **隐式逻辑回归发生率** | 22%(架构决策打架) | 12%(主观盲区) | **< 1.5%**(审查员严格拦截) | -| **任务端到端耗时** | 18.4 分钟(大量重试)| 14.2 分钟(串行等待)| **6.8 分钟** | - ---- - -## 落地指导原则 - -如果你准备为自己的团队或系统搭建 Coding Agent 流水线,请牢记以下四条原则: - -1. **写操作永远单线程**:严禁让两个 LLM 线程同时对同一个工作目录持有写入工具。如确需并行,必须划分完全独立的 Git Worktree 并由人把关合并。 -2. **子任务只交句柄,不传过程**:外包调研与素材任务时,要求子进程落盘并只返回文件绝对路径,绝不把几十页的中间对话回传给主控。 -3. **审查模型必须保持“失忆”**:负责审核代码的模型绝对不能是编写代码的模型,也绝不能看到编写过程中的对话泥潭。给它干净的 Diff,让它无情挑刺。 -4. **先建图谱,再调 Agent**:在一个中大型代码库里盲目 Grep 是自杀行为。预先基于 AST 构建符号索引,才能让 Agent 在极低的 Token 预算下精准定位。 - ---- - -## 想为您的业务落地这套高可靠 AI 自动化方案? - -我为企业与初创团队设计、搭建并运维自主 AI Agent 基础设施、内部高效工具链与高确定性自动化系统,帮助业务摆脱繁琐的人工重复劳动与失控的 AI 玩具演示。 - -无论您是希望将日常软件开发自动化、构建坚如磐石的企业级 Agent 协同流水线,还是定制自托管自动化服务: - -- **WhatsApp**: [点击直接沟通 (+60 12-797 2969)](https://wa.me/60127972969) -- **Email**: [me@hoelee.com](mailto:me@hoelee.com?subject=关于AI%20Agent企业架构咨询) -- **官方网站**: [hoelee.com](https://hoelee.com) -```` - -### 🇬🇧 英文版原文 (English Markdown Primary) -````markdown ---- -title: "The Single-Writer Rule: Orchestrating Coding Agents Without Multi-Agent Chaos" -description: "Why letting multiple AI agents write code causes race conditions and drift, and how a single-writer architecture with isolated reviewers fixes it." -pubDate: 2026-08-26 -updatedDate: 2026-10-25 -category: case-studies -blueprint: ai-agent-automation -blueprintLayer: L2-llm-gateway-agents -tags: ["ai", "agents", "architecture", "devops"] -ogImage: "/og/the-single-writer-rule-for-coding-agents.jpg" -banner: "/banners/the-single-writer-rule-for-coding-agents.jpg" -draft: false ---- - -## Why It Matters - -When software teams first experiment with AI coding agents, the intuitive next step is almost always multi-agent parallelism: if one agent can write a feature in ten minutes, spawning four agents simultaneously should ship the entire milestone in three. - -In production, the reality is almost always the exact opposite. Letting multiple autonomous agents write to the same repository simultaneously produces git merge collisions, duplicated abstractions, silent regressions, and massive token waste. Coordination overhead devours any theoretical speed gains. - -Yet running a single agent in isolation introduces its own fatal bottleneck: context pollution. As a single agent searches documentation, formats assets, and iterates on code, its working memory saturates. Long-context retrieval degrades, hallucination rates spike, and the agent loses sight of earlier architectural constraints. - -Over the past year of managing production systems, client platforms, and internal services, I resolved this dilemma by implementing the **Single-Writer Rule**: -1. Exactly **one** agent holds the write lock and edits code. -2. Read-only subagents handle heavy, non-conflicting asset generation and research in parallel. -3. An isolated top-tier reasoning model performs adversarial code review before commits land. -4. An AST-indexed code knowledge graph (`codegraph`) feeds precise symbol definitions to all parties, keeping prompt footprints minuscule. - -Here is the exact architecture, the failure modes that forced it, and how to implement it reliably. - ---- - -## The Multi-Agent Paradox: Cognition vs. Anthropic - -In mid-2025, two of the leading teams in agentic AI published contradictory findings within forty-eight hours of each other. - -Anthropic published research demonstrating that a coordinated team of subagents outperformed a single Claude Opus model by 90% on complex research tasks. One orchestrator distributed lists of companies across parallel worker agents, aggregated findings, and synthesized a clean report without blowing out the orchestrator's context window. - -One day prior, Cognition (the creators of Devin) published a now-famous post titled *Don't Build Multiagent*. Their core finding was unequivocal: multi-agent swarms attempting to build software together degenerated into "the telephone game," making inconsistent architectural assumptions and destroying repository coherence. - -Both conclusions were completely correct within their respective domains: -- **Research and information retrieval** is naturally sharded and read-only. Worker A's lookup has zero side effects on Worker B. -- **Software development** is deeply stateful and tightly coupled. If Subagent A refactors a database schema while Subagent B writes API handlers assuming the legacy schema, the merged system fails catastrophically. - -Furthermore, Anthropic's own breakdown revealed a sobering truth: multi-agent architectures consumed roughly **15 times more tokens** than standard single-turn interactions, and raw compute expenditure accounted for nearly 80% of the benchmark performance improvement. - -If you throw fifteen times more compute at a problem without solving write contention, you are simply paying fifteen times more to produce subtle bugs. - ---- - -## What Failed: The Three Traps of Swarm Coding - -Before landing on our current orchestration pipeline, I tested multi-agent swarms across production codebases. Every failure traced back to three structural flaws: - -### 1. The Telephone Game - -An orchestrator receives a prompt from the human engineer. To delegate, the orchestrator writes a summary prompt for Subagent A and Subagent B. - -``` -User Prompt (Explicit Constraints + Implicit Domain Knowledge) - ↓ -Orchestrator Summary (Lossy Abstraction) - ↓ -Subagent Interpretation (Hallucinated Assumptions) -``` - -By the third tier of delegation, critical unspoken requirements—such as backward compatibility with legacy endpoints or strict typing conventions—vanish. The subagents build exactly what was written on their delegated slip of paper, but the output fails to integrate with the system. - -### 2. Implicit Architectural Drift - -Consider a seemingly trivial task: building an interactive browser widget. -- Subagent A is tasked with creating the container DOM and styling. -- Subagent B is tasked with writing the state engine and event handlers. - -Both agents execute independently. Subagent A decides to use Tailwind CSS utility classes and modern flex layout. Subagent B assumes the project relies on legacy scoped BEM CSS and emits inline DOM mutations that clash with the stylesheet. - -Neither agent made an error; both made valid local decisions. But because neither agent communicated those implicit architectural choices to the other in real time, the integrated pull request was unusable. - -### 3. Git Merge Hell and Lock Contention - -When three agents attempt to modify code simultaneously, they inevitably edit adjacent lines in shared files (`package.json`, route registers, central types). - -Human developers resolve merge conflicts with semantic understanding. AI agents resolving merge conflicts frequently drop whole blocks of recent code, hallucinate missing variables, or enter infinite test-retry loops trying to appease the compiler. - ---- - -## The Solution: The Single-Writer Architecture - -To achieve high throughput without write collisions, we decoupled the development lifecycle into three distinct roles governed by a strict invariant: **only one process can touch the repository files at any given time**. - -``` - ┌────────────────────────┐ - │ Human Requirements │ - └───────────┬────────────┘ - │ - ▼ -┌─────────────────────────────────────────────────────────────────────────────┐ -│ ORCHESTRATOR / SINGLE WRITER │ -│ │ -│ • Holds exclusive filesystem write lock & git worktree │ -│ • Queries pre-indexed AST Code Graph (codegraph) for symbols │ -│ • Issues scoped read/generation tasks to background workers │ -│ • Applies patches and runs local test suites │ -└──────────────┬──────────────────────────────────────────────▲───────────────┘ - │ │ - Delegate │ (Async Read-Only) Clean Diff Only │ (Strict Gate) - ▼ │ -┌──────────────────────────────┐ ┌───────────────┴───────────────┐ -│ ASSET & RESEARCH BOT │ │ ADVERSARIAL REVIEWER │ -│ │ │ │ -│ • Web documentation extract │ │ • Isolated high-tier model │ -│ • Local ComfyUI / PIL assets │ │ (e.g., Gemini 4 Argon) │ -│ • SenseVoice / TTS pipelines │ │ • Zero prior context baggage │ -│ • Strictly isolated context │ │ • Reviews unified git diff │ -└──────────────────────────────┘ └───────────────────────────────┘ -``` - -### Component 1: The Exclusive Single Writer - -The primary coding agent is the only entity with access to `patch`, `write_file`, and git staging tools. - -Because it is the sole writer, it has complete, monotonic awareness of every change made to the codebase. There are no background race conditions, no unexpected lockfiles, and no corrupted working trees. - -### Component 2: Parallel Asset & Research Workers - -When building full-stack features, significant time and context are consumed by auxiliary tasks: -- Extracting technical API schemas from external documentation. -- Running local diffusion workflows (ComfyUI) to generate interface assets. -- Transcribing or synthesizing audio assets (SenseVoice / CosyVoice 2). - -Instead of polluting the Single Writer's working context with megabytes of raw HTTP dumps or image tensors, the Single Writer spawns isolated background tasks. The worker completes the job in an ephemeral context, writes the binary asset to a deterministic scratch path, and returns only a single handle (e.g., file path or JSON payload) to the writer. - -The Single Writer's context window remains pristine, reserved purely for logic and code structure. - -### Component 3: Adversarial Reviewer (The Fresh Eyes Rule) - -When an agent spends twenty turns debugging an intricate function, it develops cognitive bias: it believes its own implementation is correct because it remembers the effort required to produce it. - -Once the Single Writer verifies that its local unit tests pass, it exports the `git diff` and dispatches it to an **Adversarial Reviewer**. - -The Reviewer runs on a top-tier reasoning model (such as Gemini 4 Argon or Claude 3.5 Sonnet) with **zero conversational context**. It is given only: -1. The original task objective. -2. The unified git diff. -3. A strict instruction to search for edge cases, memory leaks, missed error states, and security vulnerabilities. - -Because the Reviewer has a 100% clean context window, it is not susceptible to the conversational drift that accumulated during development. If the Reviewer flags a vulnerability, the feedback is passed back to the Single Writer to resolve before any commit is pushed to remote. - -### Component 4: Pre-Indexed AST Code Knowledge Graph - -To eliminate the need for the Single Writer to scan whole repositories via crude directory greps, we integrated a local code knowledge graph (`colbymchenry/codegraph`). - -Before modifying a file, the agent queries the code graph for symbol references, callers, and interface implementations. The graph returns exact AST nodes and signatures (taking ~150 tokens) rather than dumping 30 source files (~40,000 tokens) into context. - ---- - -## Quantified Results: Production Comparison - -We evaluated this architecture against both traditional single-agent development and unbounded multi-agent swarms on identical full-stack features: - -| Metric | Unbounded Multi-Agent Swarm | Traditional Single Agent | Single-Writer + Adversarial Review | -|---|---|---|---| -| **Git Merge Conflicts** | 14 conflicts / run | 0 conflicts | **0 conflicts** | -| **Token Consumption** | ~480,000 tokens | ~85,000 tokens | **~62,000 tokens** (via Code Graph) | -| **Context Exhaustion Failures** | High (memory saturation) | Moderate (long task sprawl) | **Zero** | -| **Edge-Case Regression Rate** | 22% (architectural drift) | 12% (author bias) | **< 1.5%** (adversarial caught) | -| **End-to-End Task Wall Time** | 18.4 min (merge retries) | 14.2 min (sequential) | **6.8 min** | - -By restricting file mutation to a single process, outsourcing non-coding subtasks to isolated workers, and gating output through an unpolluted reviewer, development speed improved by over 2x while regression rates dropped to near zero. - ---- - -## The Rules for Implementation - -If you are designing an agentic pipeline for your own team or infrastructure, follow these four rules: - -1. **One Writer at a Time**: Never allow two LLM threads to possess write tools over the same working directory. If you need parallel coding, use distinct git worktrees with strict human-gated PR merges. -2. **Workers Return Handles, Not Transcripts**: When delegating research or asset creation, instruct subagents to write results to disk and return a file path. Never serialize intermediate multi-page reasoning back into the orchestrator. -3. **Reviewers Must Be Stateless**: The model auditing your code should never be the model that wrote it, and it should never see the author's conversational struggle. Give it the diff and tell it to break it. -4. **Index Symbols Before Spawning Agents**: Raw text search inside a 50,000-line repository is an invitation for token bankruptcy. Pre-index your AST into a graph database or symbol index so agents can locate dependencies with micro-queries. - ---- - -## Want This for Your Business? - -I design, implement, and operate autonomous agent infrastructure, custom internal tooling, and self-hosted automation systems for companies that need software shipped reliably without human babysitting. - -Whether you are looking to deploy an automated technical pipeline, build custom internal tools, or eliminate manual operations with robust agent architectures: - -- **WhatsApp**: [Chat directly on WhatsApp (+60 12-797 2969)](https://wa.me/60127972969) -- **Email**: [me@hoelee.com](mailto:me@hoelee.com?subject=Inquiry%20regarding%20AI%20agent%20orchestration) -- **Website**: [hoelee.com](https://hoelee.com) -```` - ---- - -## 文章 02 / 11:什么时候该让 AI 操控物理鼠标(以及什么时候绝对不要用) -- **Slug**: `when-to-give-your-agent-physical-clicks` -- **英文标题**: When to Give Your Agent Physical Clicks (And When to Never Touch Them) -- **分类**: `case-studies` | **发布日期**: 2026-05-28 -- **线上地址**: https://blog.hoelee.com/posts/when-to-give-your-agent-physical-clicks/ (EN) | https://blog.hoelee.com/posts/zh/when-to-give-your-agent-physical-clicks/ (ZH) -- **本篇审核状态**: ⏳ 待审核 (Pending) - -### ✍️ 顾问审阅意见区 (Review Feedback) -```text -【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 -【事实与数字核对】: -【人设与用词卫生】: -【CRO与转化建议】: -``` - -### 🇨🇳 中文版原文 (Chinese Markdown Twin) -````markdown ---- -title: "什么时候该让 AI 操控物理鼠标(以及什么时候绝对不要用)" -description: "AI Agent 四层自动化架构决策模型:深度对比确定性 API、命令行脚本、后台无感无接触操控与物理桌面模拟的选型边界。" -pubDate: 2026-05-28 -updatedDate: 2026-10-25 -category: case-studies -tags: ["ai-agents", "automation", "windows", "computer-use", "architecture"] -ogImage: /og/zh-when-to-give-your-agent-physical-clicks.jpg -banner: /banners/when-to-give-your-agent-physical-clicks.jpg -draft: false ---- - -## 商业价值与背景:通用桌面 AI 的幻觉 - -在很多关于自主智能体(AI Agent)的公开演示中,桌面操控的效果最具视觉冲击力:大模型看一眼屏幕截图,计算出按钮所在的 (x, y) 像素坐标,物理光标在屏幕上划过并精准完成点击。 - -对于正在寻求企业内部降本增效的企业主和技术主管来说,这看起来像是一颗银弹:*“我们不再需要花费昂贵成本去订制 API 接口了,直接买一套 AI 软件,让它像真人员工一样对着电脑点点点不就行了?”* - -但在真正的生产运维实践中,如果把模拟物理 GUI 作为主力自动化方案,往往会变成灾难。物理点击极其脆弱、耗时漫长、极易被系统通知弹窗阻断,而且会严重干扰坐在同一台电脑前正常工作的真人。 - -在过去一年将各类 AI 工作流推向实际业务的过程中,我沉淀出了一套**四层自动化决策阶梯**。只有搞清楚各层的优劣,才能让物理点击工具真正发挥价值。 - ---- - -## 四层自动化梯队模型 - -每一个交由 AI Agent 处理的任务,都应尽可能在最底层、最具确定性的梯队解决: - -```text -第一梯队:确定性 API / 数据库直连 (耗时:~10ms · 可靠性:99.99%) - │ -第二梯队:无头 CLI / 子进程命令行 (耗时:~200ms · 可靠性:99.9%) - │ -第三梯队:后台无感无障碍驱动 (CUA) (耗时:~1-2s · 可靠性:95%) - │ -第四梯队:前台物理输入模拟 (MCP) (耗时:~3-5s · 可靠性:80%) -``` - -### 第一梯队:确定性 API 与数据库直连 -只要系统暴露了数据端点,绝不要碰 UI 界面。操作 MySQL、Docker、Portainer 或支付网关,必须通过 RESTful API、SQL 语句或受检的 SDK 完成。这种方式毫秒级响应、上下文完全隔离,且返回的是结构化数据而非含糊的像素点。 - -### 第二梯队:无头 CLI 与子进程 -如果没有现成的网络 API,第二优先级是寻找命令行工具。代码修改、文件处理、日志分析或视频压制,完全可以通过 `terminal`、`git`、`ffmpeg` 或本地脚本静默执行。模型无需移动鼠标,不仅速度快出几十倍,而且不会因界面卡顿而中断。 - -### 第三梯队:后台无感无障碍驱动(CUA) -当目标软件是一个图形界面且没有 CLI 时,首选是**后台无感自动化**(例如 Hermes 内置基于 `cua-driver` 的 `computer-use`)。 -- 指令通过系统底层辅助功能框架(Windows UIA / macOS AX)直接派发给目标控件。 -- **真人的物理鼠标光标完全不会被移动。** -- 窗口不需要前置聚焦。你可以在前台敲代码或写邮件,而 Agent 在后台最小化或未激活的窗口里完成点击。 - -### 第四梯队:前台物理输入模拟(Windows-MCP) -第四梯队是最后的防线:调用类似 `windows-mcp` 的工具,截取屏幕、计算全屏像素坐标,并通过系统底层的 `SendInput` 派发真实的硬件级鼠标键盘事件。 - ---- - -## 什么时候真正需要第四梯队(物理点击)? - -尽管第四梯队的成本最高、脆弱性最强,但在以下三大现实业务场景中,前三梯队会彻底失效,这正是 `windows-mcp` 展现价值的地方: - -### 1. 闭源陈旧的 Win32 遗留企业软件 -许多使用 Delphi、VB6 或老旧 C++ 编写的中小企业财务、仓储、ERP 客户端,根本没有实现现代 Windows UIAutomation 接口。后台 UIA 树只能看到一个空白容器,也没有任何命令行接口。此时,结合视觉截图(`Screenshot`)与物理坐标点击(`Click`)是让 AI 能够接管这套流程的唯一技术手段。 - -### 2. 操作系统原生文件选择与保存对话框 -在自动化驱动网页导出报表或桌面软件另存为时,经常会弹出 Windows 原生文件对话框(`comdlg32.dll` / 资源管理器窗口)。无头浏览器无法穿透操作系统的原生对话框,而 `windows-mcp` 可以识别“另存为”输入框、填入绝对路径,并通过键盘快捷键 `Enter` 触发保存。 - -### 3. 跨非联网软件的剪贴板与系统级提示 -两款互不联网的单机软件之间流转非结构化数据时,常需要借助系统剪贴板(`Clipboard` 的读取与写入)完成中转;或者在任务结束时,通过系统的原生 Toast 弹窗(`Notification`)提示人工介入。 - ---- - -## 典型反面模式:哪些事情绝对不要用物理点击? - -在代码审查和自动化诊断中,我经常看到把第四梯队当成万能钥匙的典型反模式: - -- **让 Agent 在编辑器里物理打字写代码**:让 AI 截图、点击 VS Code 编辑区、模拟敲键盘写代码不仅速度奇慢、极易漏字,还会巨额消耗图像 Token。应直接使用文件工具(`patch`、`write_file`)。 -- **通过点击图形浏览器来抓取公开网站数据**:物理操作前台 Chrome 浏览器的稳定性远低于无头浏览器或直接发起 HTTP 请求。 -- **人在使用电脑时触发物理操作**:因为第四梯队会抢占真实鼠标和键盘焦点,如果你正在打字回复客户,物理点击会瞬间夺走焦点并导致输入错乱。 - ---- - -## 选型矩阵总结 - -```text -┌────────────────────────────────────────────────────────┐ -│ 自动化架构选型矩阵 │ -├──────────────────────┬─────────────┬───────────────────┤ -│ 业务场景 │ 正确工具 │ 所属梯队 │ -├──────────────────────┼─────────────┼───────────────────┤ -│ 数据库查询 / API交互 │ REST / SQL │ 第一梯队(API) │ -│ 代码维护 / 运维脚本 │ Terminal │ 第二梯队(CLI) │ -│ 无需前置的软件自动化 │ cua-driver │ 第三梯队(后台UIA)│ -│ 遗留Win32 / 另存对话框│ windows-mcp │ 第四梯队(物理模拟)│ -└──────────────────────┴─────────────┴───────────────────┘ -``` - -把自动化视为一个逐步升级的阶梯,而不是一把万能锤子,是区分脆弱的实验室 Demo 与能够连续稳定运行数月的生产级工作流的分水岭。 - ---- - -## 想为你的企业构建这套自动化体系? - -我为马来西亚及海外中小企业量身定制并审查 AI 自动化管线——从纯后台的数据流转、智能客服 Agent 到跨越遗留桌面软件的自动化中转。如果你的团队每天仍在耗费大量人工在老旧软件之间机械地搬运数据,我可以为你搭建 7×24 小时高可靠运行的自动化架构。 - -直接联系我: -- **WhatsApp**: [+60 12-797 2969](https://wa.me/60127972969) -- **邮箱**: [me@hoelee.com](mailto:me@hoelee.com?subject=AI%20桌面自动化咨询) -- **主页**: [hoelee.com](https://hoelee.com) -```` - -### 🇬🇧 英文版原文 (English Markdown Primary) -````markdown ---- -title: "When to Give Your Agent Physical Clicks (And When to Never Touch Them)" -description: "A 4-tier automation matrix for AI agents: comparing deterministic APIs, shell execution, background accessibility, and physical desktop simulation." -pubDate: 2026-05-28 -updatedDate: 2026-10-25 -category: case-studies -tags: ["ai-agents", "automation", "windows", "computer-use", "architecture"] -ogImage: /og/when-to-give-your-agent-physical-clicks.jpg -banner: /banners/when-to-give-your-agent-physical-clicks.jpg -draft: false ---- - -## Why It Matters: The Illusion of Universal Desktop AI - -When autonomous agent frameworks demonstrate desktop automation, the visual appeal is undeniable: an LLM captures a screenshot, determines the (x, y) coordinates of a button, moves your cursor across the screen, and clicks it. - -To business owners and developers trying to automate internal workflows, it looks like a silver bullet: *"We don't need expensive API integrations anymore; we'll just have an AI click through our software like a human employee."* - -In real-world production, treating physical GUI simulation as your primary automation strategy is a reliability nightmare. Physical clicks are fragile, slow, susceptible to OS notification popups, and violently disrupt the human user who is trying to use the same machine. - -Over the past year of deploying AI workflows across production infrastructure, I have converged on a **4-tier automation hierarchy**. Here is where physical clicks genuinely shine—and the three higher tiers you should always exhaust first. - ---- - -## The 4-Tier Automation Hierarchy - -Every automation request an AI agent handles should be resolved at the lowest applicable tier: - -```text -Tier 1: Deterministic API / Database (Speed: ~10ms · Reliability: 99.99%) - │ -Tier 2: Headless CLI / Subprocess (Speed: ~200ms · Reliability: 99.9%) - │ -Tier 3: Background Accessibility/CUA (Speed: ~1-2s · Reliability: 95%) - │ -Tier 4: Foreground Physical Clicks (Speed: ~3-5s · Reliability: 80%) -``` - -### Tier 1: Deterministic APIs & Direct Queries -If an endpoint exists, never touch a UI. Interacting with MySQL, Docker, Portainer, or Stripe should happen through REST endpoints, SQL queries, or verified SDK calls. It is instantaneous, completely isolated, and returns structured data rather than ambiguous pixels. - -### Tier 2: Headless CLI & Subprocesses -If there is no remote API, look for a command-line utility. Editing code, running migrations, parsing logs, or transforming media should happen through `terminal`, `git`, `ffmpeg`, or headless scripts. The agent never moves your mouse, and executions finish in milliseconds. - -### Tier 3: Background Accessibility & Window Messages (CUA) -When dealing with GUI applications, the first choice is **background automation** (such as Hermes's `computer-use` powered by `cua-driver`). -- Messages are delivered via native accessibility APIs (Windows UIA / macOS AX). -- **Your mouse cursor never moves.** -- The application does not need to be focused or brought to the front. You can type an email while the agent clicks a button in an unfocused background window. - -### Tier 4: Foreground Physical Input Simulation (Windows-MCP) -Tier 4 is the final resort: using tools like `windows-mcp` to take full-screen screenshots, compute virtual desktop pixel coordinates, and dispatch hardware-level `SendInput` events. - ---- - -## When Tier 4 Physical Clicks Are Justified - -There are specific operational gaps where Tiers 1 through 3 fail completely. This is where `windows-mcp` earns its keep: - -### 1. Proprietary Win32 Legacy Software -Many accounting, industrial dispatch, CAD, and local inventory tools written in Delphi, VB6, or legacy C++ do not implement modern Windows UIAutomation interfaces. Background UIA trees return empty containers, and the software has no CLI. Physical screen capture (`Screenshot`) combined with coordinate clicks (`Click`) is the only way an agent can operate them. - -### 2. OS-Native File & Save Dialogs -When automating a browser or desktop application to export a report, you frequently hit a native Windows Common File Dialog (`comdlg32.dll` / Explorer file picker). Headless browsers cannot interact with the operating system's native file picker window. `windows-mcp` can identify the "Save As" text box, paste the target path, and hit `Enter` via `Shortcut`. - -### 3. Native Clipboard & System Notifications -Bridging unstructured data between two non-networked desktop programs often requires reading and writing the OS clipboard (`Clipboard mode="get"` / `"set"`) or alerting the human operator via a Windows Toast notification (`Notification`). - ---- - -## Anti-Patterns: Where Physical Clicks Fail Catastrophically - -In production audits, I regularly catch teams using Tier 4 for tasks that belong in Tiers 1 or 2: - -- **Writing Code in an IDE GUI**: Asking an agent to click VS Code's editor pane and type characters is catastrophically slow, prone to dropped keystrokes, and burns thousands of tokens per file. Use filesystem tools (`patch`, `write_file`). -- **Web Scraping via Browser Clicking**: Driving a visible Chrome window with mouse clicks is 20x slower and far more brittle than headless Chromium or an HTTP fetch tool. -- **Background Execution While Working**: Because Tier 4 moves your actual mouse and steals window focus, running an agent workflow while you are actively writing an email will cause the agent to hijack your keystrokes. - ---- - -## Architecture Summary - -```text -┌────────────────────────────────────────────────────────┐ -│ Automation Matrix │ -├──────────────────────┬─────────────┬───────────────────┤ -│ Use Case │ Right Tool │ Tier │ -├──────────────────────┼─────────────┼───────────────────┤ -│ Database / API │ REST / SQL │ Tier 1 (API) │ -│ File edits / builds │ Terminal │ Tier 2 (CLI) │ -│ Unfocused browser UI │ cua-driver │ Tier 3 (UIA/AX) │ -│ Legacy Win32 / Save │ windows-mcp │ Tier 4 (Physical) │ -└──────────────────────┴─────────────┴───────────────────┘ -``` - -Treating desktop automation as an escalation ladder rather than a single hammer is what separates fragile prototypes from production workflows that run for months without human intervention. - ---- - -## Want This for Your Business? - -I design, build, and audit automated AI agent pipelines for small and medium businesses—from headless backend data extractors to robust desktop legacy software bridges. If your team is wasting hours manually re-typing data between desktop tools, I can build an automation architecture that runs reliably 24/7. - -Reach me directly at: -- **WhatsApp**: [+60 12-797 2969](https://wa.me/60127972969) -- **Email**: [me@hoelee.com](mailto:me@hoelee.com?subject=AI%20Desktop%20Automation%20Consulting) -- **Website**: [hoelee.com](https://hoelee.com) -```` - ---- - -## 文章 03 / 11:为什么我要做视频精读知识库:把收藏夹吃灰的短视频变成可检索笔记 -- **Slug**: `why-i-built-a-video-knowledge-base` -- **英文标题**: Why I Built a Video Knowledge Base: Turning Saved Short Videos into Searchable Notes -- **分类**: `case-studies` | **发布日期**: 2024-11-28 -- **线上地址**: https://blog.hoelee.com/posts/why-i-built-a-video-knowledge-base/ (EN) | https://blog.hoelee.com/posts/zh/why-i-built-a-video-knowledge-base/ (ZH) -- **本篇审核状态**: ⏳ 待审核 (Pending) - -### ✍️ 顾问审阅意见区 (Review Feedback) -```text -【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 -【事实与数字核对】: -【人设与用词卫生】: -【CRO与转化建议】: -``` - -### 🇨🇳 中文版原文 (Chinese Markdown Twin) -````markdown ---- -title: "为什么我要做视频精读知识库:把收藏夹吃灰的短视频变成可检索笔记" -description: "为什么平台收藏夹是学习的死胡同?记录我如何利用本地语音识别与大模型构建视频精读知识库,实现文字点击跳播与毫秒级全文检索。" -pubDate: 2024-11-28 -category: case-studies -tags: ["ai", "video-processing", "whisper", "astro", "knowledge-management"] -ogImage: "/og/zh-why-i-built-a-video-knowledge-base.jpg" -banner: "/banners/why-i-built-a-video-knowledge-base.jpg" -draft: false ---- - -和很多持续学习的开发者一样,我的 B站、YouTube 和抖音收藏夹里常年躺着数百个视频。这里有一段 60 秒讲透 Transformer 注意力机制的精华讲解,那里有一段 2 分钟拆解系统架构的实战经验。 - -然而,收藏夹越来越长,真正要在几个月后复习或查证某个具体知识点时,根本找不到。 - -把视频丢进收藏夹,本质上是一种心理安慰。这篇文章记录了我为什么要立项搭建这套视频学习精读网站,如何用本地算力实现自动化转写与提炼,以及把碎片化视频转变为永久数字资产的思考。 - ---- - -## 1. 为什么平台收藏夹是学习的死胡同? - -短视频是目前打破信息差最高效的载体之一。优秀的博主能用 1 到 3 分钟把复杂的概念讲得通俗透彻。但在知识沉淀的维度上,视频载体有三个天然缺陷: - -1. **内容不可检索**:平台搜索只能检索视频标题和标签,讲者在第 1 分 15 秒说的那句核心结论,搜索引擎根本看不见。 -2. **复习摩擦力极高**:扫一眼 500 字的精读总结只需 30 秒,而重新看一段视频需要 2 到 3 分钟被动听讲,中间往往还夹杂着求关注、引流话术与片头片尾。 -3. **内容极易失效**:原帖下架、博主销号或外链失效时常发生,收藏夹瞬间变成灰白色的失效链接列表。 - -要真正把视频内容沉淀为个人知识库,必须满足一个硬性要求:**收藏的视频必须全自动转写为逐字稿、提炼为结构化要点与思维导图,并支持全文毫秒级检索与精确到秒的点击跳播。** - ---- - -## 2. 架构设计与工程取舍 - -在设计这套系统时,我结合现有的家庭基础设施,确立了四项核心原则: - -``` -[ 本地收集视频 / 收件箱 ] - │ - ▼ -[ 本地 GPU 算力流水线 ] ────► Silero-VAD + Faster-Whisper (本地零云端调用费) - │ - ├──────────────────► 大模型 6 维精读提炼 (TL;DR、思维导图、时间戳) - │ - ▼ -[ 严格解耦的数据层 ] - ├── src/content/videos/{slug}.md (元数据 + AI 结构化精读总结) - └── src/data/transcripts/{slug}.json (毫秒级分句逐字稿 [start, end, text]) - │ - ▼ -[ Astro 5 纯静态门户 ] ────► Pagefind 客户端 WASM 离线检索 (<20ms 响应) - │ - ▼ -[ 双轨流媒体分发 ] ────────► 官方 iFrame 嵌入优先 / NVENC 压缩后托管于 Cloudflare R2 -``` - -### 总结正文与时间轴严格分离 -在早期原型设计中,最容易踩的坑是把带时间戳的逐字稿全部硬编码进同一个 Markdown 正文里。这不仅导致 Markdown 文件膨胀到数千行,更致命的是,一旦后续调整 Prompt 想重新跑一遍 AI 总结,就会把人工校对好的时间戳冲掉。 - -规范的做法是:`src/content/videos/{slug}.md` 纯粹存放结构化要点与元数据,而分句时间轴存放于独立的 `src/data/transcripts/{slug}.json` 中。 - -### 本地算力闭环,零云端转写成本 -不用云端按分钟计费的语音转写 API,流水线直接运行在宿主机的 NVIDIA RTX 3060 显卡上。通过 `faster-whisper` 与 `Silero-VAD` 结合,自动切除无声段,并按标点符号聚合成 3 到 8 秒的自然语义分句。 - -### 严禁家庭 NAS 直出公网视频流 -用自建 NAS 直出公网 Range/206 视频流,一旦遇到爬虫或多人同时访问,宽带的上行带宽会被瞬间打满,甚至触发运营商对于 PCDN 的封禁。公网访问采用双轨策略:长青视频优先使用 B站/YouTube 官方嵌入播放器;自存短视频经 NVENC 压缩为 720p H.264 后托管在免流量费的 Cloudflare R2。 - -### 基于 Pagefind 的毫秒级离线搜索 -前台不维护重型的 Meilisearch 或 Elasticsearch 数据库,直接编译为 Astro 静态站点并利用 Pagefind 构建分片索引。读者在浏览器端搜索时,通过 WebAssembly 按需拉取几十 KB 的分片,零服务器内存常驻,中文关键词检索延迟在 20ms 以内。 - ---- - -## 3. 学习闭环带来的实际改变 - -从“盲目收藏”转变为“流水线吞吐”,知识吸收的效率发生了根本改变: - -- **从囤积变为检索**:不再翻看长长的收藏列表。按下 `Cmd+K` 输入技术术语(如 `RAG` 或 `Agent`),直接定位到哪段视频的第几秒讲过这个概念。 -- **Click-to-Seek 精准跳播**:点击精读要点或时间戳徽章,播放器直接跳到关键帧播放,跳过废话,只看核心论点。 -- **永久自主沉淀**:所有笔记与逐字稿均以 Markdown 与 JSON 保存在 Git 仓库中,即便第三方平台删帖,核心知识依然永久归档。 - ---- - -## 4. 业务咨询与合作 - -搭建全自动化知识提取流水线、本地大模型工作流以及高性能静态门户是我擅长的工作。 - -如果你的企业或团队也积累了大量内部培训录屏、会议回放或知识资产,需要将其转化为可检索、支持时间戳精读的企业内部知识库: - -- **WhatsApp 直接沟通**:[点击打开 WhatsApp (012-7972969)](https://wa.me/60127972969) -- **电子邮箱**:[me@hoelee.com](mailto:me@hoelee.com?subject=关于视频知识库与内训检索系统的合作咨询) -- **官方主页**:[hoelee.com](https://hoelee.com) -```` - -### 🇬🇧 英文版原文 (English Markdown Primary) -````markdown ---- -title: "Why I Built a Video Knowledge Base: Turning Saved Short Videos into Searchable Notes" -description: "Why saving short videos to bookmarks is a dead end, and how I built a local ASR and AI pipeline to convert them into searchable notes with Click-to-Seek video sync." -pubDate: 2024-11-28 -category: case-studies -tags: ["ai", "video-processing", "whisper", "astro", "knowledge-management"] -ogImage: "/og/why-i-built-a-video-knowledge-base.jpg" -banner: "/banners/why-i-built-a-video-knowledge-base.jpg" -draft: false ---- - -Like many developers and lifelong learners, I found myself accumulating hundreds of bookmarks across platforms like Bilibili, YouTube, and Douyin. A 60-second video explaining a Transformer concept here, a 2-minute architectural teardown there. - -The bookmark list kept growing, but when I actually needed that one specific explanation six months later, it was impossible to retrieve. - -Saving videos into platform favorites is a dead end. This post explains why I decided to solve this problem by building a dedicated learning portal, how I designed the architecture around local compute, and the lessons learned turning fleeting video content into a permanent, searchable knowledge asset. - ---- - -## 1. Why Video Bookmarks Fail - -Short-form video is currently the fastest medium for breaking information asymmetry. Creators pack high-density insights into 1 to 3 minutes. However, as a long-term knowledge repository, video suffers from three fatal flaws: - -1. **Unsearchable inside the content**: Platform search only indexes video titles and uploader tags. The actual golden nugget spoken at minute 01:15 is completely invisible to search engines. -2. **High review friction**: Reading a 500-word summary takes 30 seconds; watching a video requires 2 to 3 minutes of passive listening, often padded with intro hooks and subscriber calls. -3. **Fragile shelf life**: Links rot, accounts get banned, and videos get taken down without warning. - -To turn passive consumption into actionable learning, I set a clear requirement: **every video I save must be transcribed, summarized into structured bullet points and mindmaps, and made searchable down to the exact second.** - ---- - -## 2. Architecture & Design Principles - -When designing the system, I established four non-negotiable architectural principles based on my existing home infrastructure: - -``` -[ Local Input / Inbox ] - │ - ▼ -[ Local GPU Pipeline ] ────► Silero-VAD + Faster-Whisper (Zero cloud API fees) - │ - ├──────────────────► LLM 6-D Synthesis (TL;DR, Mindmap, Timestamps) - │ - ▼ -[ Decoupled Data Layer ] - ├── src/content/videos/{slug}.md (Frontmatter + Structured Insights) - └── src/data/transcripts/{slug}.json (Millisecond Cues [start, end, text]) - │ - ▼ -[ Astro 5 Static Portal ] ──► Pagefind Client-Side WASM Search (<20ms latency) - │ - ▼ -[ Dual-Track Video Sync ] ──► Official iFrame Embeds or NVENC H.264 on Cloudflare R2 -``` - -### Decouple Summaries from Transcripts -The biggest architectural trap in early prototypes was concatenating timestamped transcripts directly inside the Markdown content body. This caused Markdown files to balloon to thousands of lines, cluttered formatting, and made re-running LLM summaries destructive. - -The fix: keep `src/content/videos/{slug}.md` strictly for high-level synthesis and Frontmatter, while storing millisecond cues in `src/data/transcripts/{slug}.json`. - -### Zero Cloud STT Fees -Rather than paying recurring per-minute charges to cloud transcription APIs, the pipeline runs locally on an NVIDIA RTX 3060 (12GB VRAM). Using `faster-whisper` and `Silero-VAD`, speech is automatically transcribed into clean 3-to-8 second semantic sentences with sub-second timestamps. - -### Never Stream from Residential NAS -Serving video streaming directly from a residential home NAS to public web visitors saturates home broadband upload bandwidth and risks ISP restrictions. Public playback uses a dual-track strategy: official iframe embeds (Bilibili/YouTube) whenever possible, or lightweight NVENC 720p H.264 streams hosted on Cloudflare R2. - -### Sub-20ms Search with Pagefind -Instead of maintaining an always-on search database like Meilisearch or Elasticsearch, the front portal compiles to a pure static Astro site indexed by Pagefind. Search queries run in-browser via WebAssembly, delivering instantaneous Chinese keyword lookups with zero server memory footprint. - ---- - -## 3. What Changed in My Daily Learning Loop - -Replacing passive "saving for later" with an automated ingestion pipeline fundamentally changed how I retain information: - -- **From Hoarding to Searching**: Instead of scrolling through endless favorited lists, I hit `Cmd+K` in the portal, type a keyword like `RAG` or `Agent`, and instantly see matching quotes highlighted in the transcript. -- **Click-to-Seek Precision**: Clicking on any key point jumps the video player directly to that second, bypassing creator filler and replaying only the core explanation. -- **Permanent Ownership**: The knowledge lives in plain text and JSON in a Git repository, completely independent of third-party platforms. - ---- - -## 4. Work With Me - -Building automated knowledge ingestion pipelines, self-hosted AI workflows, and high-performance static portals is part of what I do. - -If your organization has internal training videos, product recordings, or course archives that you need converted into a fast, searchable internal knowledge hub: - -- **WhatsApp**: [Chat directly on WhatsApp](https://wa.me/60127972969) -- **Email**: [me@hoelee.com](mailto:me@hoelee.com?subject=Inquiry%20regarding%20video%20knowledge%20base%20portal) -- **Website**: [hoelee.com](https://hoelee.com) -```` - ---- - -## 文章 04 / 11:为什么你的无头浏览器不是万能爬虫 -- **Slug**: `why-your-headless-browser-cant-scrape-everything` -- **英文标题**: Why Your Headless Browser Can't Scrape Everything -- **分类**: `case-studies` | **发布日期**: 2026-01-21 -- **线上地址**: https://blog.hoelee.com/posts/why-your-headless-browser-cant-scrape-everything/ (EN) | https://blog.hoelee.com/posts/zh/why-your-headless-browser-cant-scrape-everything/ (ZH) -- **本篇审核状态**: ⏳ 待审核 (Pending) - -### ✍️ 顾问审阅意见区 (Review Feedback) -```text -【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 -【事实与数字核对】: -【人设与用词卫生】: -【CRO与转化建议】: -``` - -### 🇨🇳 中文版原文 (Chinese Markdown Twin) -````markdown ---- -title: "为什么你的无头浏览器不是万能爬虫" -description: "两个二手交易平台,两面完全不同的墙:闲鱼用「非法访问」把无头浏览器挡在门外,Carousell 却照常吐数据。教训是——在伸手拿 Playwright 之前,先搞清页面到底是怎么把数据交给你的。" -pubDate: 2026-01-21 -updatedDate: 2026-09-10 -category: case-studies -tags: [scraping, playwright, browserless, docker, goofish, carousell, anti-bot] -ogImage: /og/zh-why-your-headless-browser-cant-scrape-everything.jpg -banner: /banners/why-your-headless-browser-cant-scrape-everything.jpg ---- - -我在短短几周里,分别在两个不同的二手交易平台上撞上了同一堵墙,而这组对照 -教给我的,比学一年教程还多。 - -在 **Carousell** 上,一个无头浏览器把新上架的商品连价格、成色、图片链接一起 -抓进数据库——毫无问题,稳定跑了几个月。在**闲鱼**上,一模一样的设置,每次都 -只返回同样三个词: - -``` -为了保障您的体验,请使用正常浏览器访问闲鱼~ -``` - -两个平台,同一个浏览器,结果完全相反。这篇文章讲的就是**为什么**,以及那个 -本该在一开始就做、能帮我省下大半天时间的决定。 - -## 一个从一开始就没问对的问题 - -我想在闲鱼上搜索商品,把结果抽出来——标题、价格、链接。第一个跳出来的答案 -自然是「用无头浏览器」。每个人都会这么答:用 Playwright 或 Puppeteer 把页面 -渲染出来,等 JavaScript 执行完,再读 DOM。 - -于是我就真这么搭了。我部署了一个自托管的 `browserless` 容器——一个现成的 -「无头 Chrome 即 API」,把它指向闲鱼的搜索页。然后我花了几个小时,把那个工具 -暴露出来的每个开关都试了个遍: - -- `--disable-blink-features=AutomationControlled` 隐藏自动化标志 -- 用 `evaluateOnNewDocument` 把 `navigator.webdriver` 抹成 `undefined` -- 一个逼真的 Chrome user-agent -- 一个 `stealth` 启动选项 - -每一次,商品列表都卡在「加载中…」——页面框架渲染出来了,页头渲染出来了, -页脚渲染出来了,但真正的商品列表永远加载不出来。返回的 HTML 里价格是 0 条, -商品链接是 0 条。 - -与此同时,脑子里有个声音一直在提醒我:我的 Carousell 监控器抓的也是同样的 -数据,而且**没有任何 stealth、没有任何反检测手段**,却一直稳稳地工作。为什么? - -## 换个思路:先看数据是怎么到页面上的 - -答案根本不在浏览器的那些启动参数里,而在**每个网站是怎么把数据交给页面的**。 - -**Carousell 是把搜索结果嵌在页面的初始响应里的。** 服务器把商品列表作为 -JSON 烤进了 HTML(类似 `__PRELOADED_STATE__` 这种结构)。JavaScript 之后再把 -它们增强一下,但一次普通的 HTTP 请求就已经包含了所有的东西——商品 ID、标题、 -价格、图片。爬虫甚至不需要渲染任何东西,直接从这个原始 HTML 里把 JSON 解析 -出来就行。 - -**闲鱼什么都不在服务端给。** 它的搜索结果是在页面加载**之后**,才从一个带 -签名的 API 端点上拉回来的。这个端点要求: - -- 一个由 App 根据请求参数和一个密钥算出来的签名 -- 一系列会标记无头浏览器指纹的反爬检查(WebDriver 检测、CDP 痕迹、canvas/ - audio 指纹) - -把签名去掉,API 就什么都不返回。把浏览器特征去掉,页面就回你一句「非法访问」。 - -**服务端渲染的 JSON vs. 带签名的异步 API**——这一个区别,就是全部的游戏。 -它让你在一分钟内就判断出「用浏览器渲染」这条路是花一个下午,还是花一个月。 - -## 无头浏览器为什么在闲鱼上撞了墙 - -说句实在话:**开源的、自托管的浏览器本身不是隐身工具。** - -`browserless`(我部署的那个容器)是个**通用**渲染器。它的免费版能渲染页面、 -执行 JavaScript、截图、转 PDF。而反检测的能力——真正的 `stealth` 模式、验证码 -识别、解锁代理——明确是**付费的 Cloud/Enterprise 版**才有的。它们文档里写得 -毫不含糊。 - -所以说,我是在拿一个通用渲染器,去硬刚一个整个商业模式都建立在「击败自动化 -客户端」之上的平台。这不是配置 bug,是工具和对手之间的错配。 - -真要抓闲鱼,我有几条重得多的路可选: - -1. **逆向 App 的签名算法**,直接调搜索 API。严肃的爬虫都是这么干的——但签名 - 会变,所以这是持续的维护成本,不是一次性做完就完事。 -2. **买第三方数据接口**(阿里云市场之类卖 `item_search` 端点)。数据干净,但 - 按次计费,而且受制于供应商。 -3. **驱动一个真实登录的浏览器、低频访问**,指望频率始终低于雷达线。偶尔手动 - 查查还行,想稳定的大规模监控,没用。 - -没有一条是「起个容器就能跑」的。这才是重点。 - -## 可以复用的检查清单 - -在给一个新目标动用 Playwright 之前,我现在会按顺序问自己三个问题: - -1. **数据到底存在哪里?** 关掉 JavaScript 打开页面(或者直接读原始 HTML)。 - 如果数据就在 HTML 里,我根本不需要浏览器——我需要的是一个 HTTP 客户端和一个 - 解析器。浏览器纯属浪费。 -2. **如果不在 HTML 里,那个异步请求长什么样?** 打开 DevTools → Network,找到 - 那个返回数据的 XHR/fetch,看它的 header 和查询参数。有没有签名?它是稳定的, - 还是每个请求都变? -3. **是不是带签名的 API?** 如果是,停下来。先想清楚这个目标值不值得 (a) 逆向 - 签名,或者 (b) 付费买数据供应商。如果都不值,诚实的答案就是「这事成本高于 - 收益」——能在一个小时内就**知道**这一点,本身就是种胜利。 - -大多数爬虫教程会跳过这三步,直接跳到「装 Puppeteer」。那是昂贵的那条路—— -花一整天用最痛的方式,才搞懂一个 60 秒的调查早就该告诉你的事。 - -## 如果重来一次我会怎么做 - -- **在伸手拿浏览器之前,先禁用 JavaScript。** 这是判断「服务端渲染 vs. 客户端 - 拉取」最快的信号,十秒钟,零配置。 -- **别指望从通用渲染器里白嫖 stealth。** stealth 要么是你花钱买的产品 - (browserless Cloud、ScrapingBee 之类),要么是你自己搭、自己维护的东西。它 - 不是一个开源容器里的勾选框。 -- **把「渲染」和「提取」分开看。** 无头浏览器返回的是 HTML,它不会直接给你 - 结构化的商品字段。就算渲染成功了,还是得有人写选择器或 `evaluate` 脚本。那是 - 另一件事——要为它做计划,别以为它是免费的。 - -## 结果 - -这组对照沉淀成了一条我现在每个项目都会用的规则:**在选工具之前,先判断目标是 -服务端渲染还是 API 门槛。** 在 Carousell(服务端渲染)上,一个普通的 HTTP 解析器 -几个月来归档了几千条带价格和图片的商品。在闲鱼(签名 API)上,我诚实地评估了 -工作量和维护成本之后选择了停下——对一个偶尔手动搜一下就够用的需求来说,这本身 -就是正确的结局。 - -无头浏览器**有时候**是对的工具——截图、转 PDF、接管一个人工会话,或者目标本身 -就是服务端渲染。但它不是一把通用的爬虫钥匙,把它当成钥匙,才是那个昂贵的错误。 - ---- - -## 想知道一个网站值不值得花力气去抓? - -大多数爬虫项目都在第一个小时内失败,因为没人先去查一眼——这个目标到底允不 -允许你用低成本抓到数据。我写代码之前会先做这个判断——我也真的在搭那些能跑起来 -的监控器、通知管线,和背后的自托管基础设施。如果你盯上了一个数据源,想知道它是 -一个下午的活还是一个月的活,欢迎聊聊: - -- 📱 **WhatsApp:** [+60 12-797 2969](https://wa.me/60127972969) -- 📧 **Email:** [me@hoelee.com](mailto:me@hoelee.com) -- 🌐 **Website:** [hoelee.com](https://hoelee.com) -```` - -### 🇬🇧 英文版原文 (English Markdown Primary) -````markdown ---- -title: "Why Your Headless Browser Can't Scrape Everything" -description: "Two second-hand marketplaces, two very different walls: Goofish blocks a headless browser with 'illegal access' while Carousell keeps serving data. The lesson is to read how a page delivers data before you reach for Playwright." -pubDate: 2026-01-21 -updatedDate: 2026-09-10 -category: case-studies -tags: [scraping, playwright, browserless, docker, goofish, carousell, anti-bot] -ogImage: /og/why-your-headless-browser-cant-scrape-everything.jpg -banner: /banners/why-your-headless-browser-cant-scrape-everything.jpg ---- - -I hit the same wall a few weeks apart, on two different second-hand marketplaces, -and the contrast taught me more about scraping than a year of tutorials did. - -On **Carousell**, a headless browser pulled freshly-listed products into a database -with prices, conditions, and photo URLs — no problem, running for months. On -**Goofish (闲鱼)**, the exact same setup returned the same three words every time: - -``` -为了保障您的体验,请使用正常浏览器访问闲鱼~ -(translation: "to protect your experience, please use a normal browser") -``` - -Two marketplaces, one browser, opposite outcomes. This is the story of *why*, and -the one decision that would have saved me most of a day if I'd made it first. - -## The goal, badly framed - -I wanted to search Goofish for products and pull the results out — titles, prices, -links. The obvious first answer is "use a headless browser." It's the answer -everyone gives: render the page with Playwright or Puppeteer, wait for the -JavaScript, read the DOM. - -So I built exactly that. I deployed a self-hosted `browserless` container — a -ready-made headless-Chrome-as-an-API — and pointed it at Goofish search. Then I -spent hours trying every lever the tool exposes: - -- `--disable-blink-features=AutomationControlled` to hide the automation flag -- patching `navigator.webdriver` to `undefined` via `evaluateOnNewDocument` -- a realistic Chrome user-agent -- a `stealth` launch option - -Each time, the product list stayed stuck at "loading…" — the page frame rendered, -the header rendered, the footer rendered, but the actual listings never populated. -The HTML came back with zero prices and zero product links. - -Meanwhile I had a memory nagging me: my Carousell monitor grabs the same kind of -data with *no* stealth, *no* anti-detection tricks, and it works flawlessly. Why? - -## The frame change: read how the data gets to the page - -The answer wasn't in the browser flags. It was in **how each site delivers its data**. - -**Carousell embeds its search results in the page's initial payload.** The server -sends the listings as JSON baked into the HTML (a `__PRELOADED_STATE__`-style blob). -The JavaScript enhances them afterward, but a plain HTTP request already contains -everything — product ID, title, price, photos. A scraper can parse that JSON out of -the raw HTML without ever rendering anything. - -**Goofish delivers nothing server-side.** Its search results are fetched *after* -the page loads, from a signed API endpoint. That endpoint requires: - -- a signature the app computes from request parameters and a secret -- anti-bot checks that flag a headless browser's fingerprint (WebDriver detection, - CDP artifacts, canvas/audio fingerprints) - -Strip the signature away, and the API returns nothing. Strip the browser off, and -the page returns "illegal access." - -That single distinction — **server-rendered JSON vs. a signed async API** — is the -whole game. It tells you in one minute whether "render the page in a browser" will -take you an afternoon or a month. - -## Why the headless browser hit a wall on Goofish - -The honest reality: **an open-source, self-hosted browser is not a stealth tool.** - -`browserless` (the container I deployed) is a *generic* renderer. Its free tier -renders pages, executes JavaScript, takes screenshots, converts PDFs. The -anti-detection features — real `stealth` mode, captcha solving, unblocked proxies — -are explicitly the **paid Cloud/Enterprise** tier. The message in their docs is -unambiguous. - -So I was asking a general-purpose renderer to beat a platform whose entire -business depends on defeating automated clients. That's not a configuration bug; -it's a mismatch between the tool and the adversary. - -To actually scrape Goofish I'd have to choose one of a few much heavier paths: - -1. **Reverse the app's signing algorithm** and call the search API directly. This - is how the serious scrapers do it — but the signature changes, so it's an - ongoing maintenance cost, not a one-time build. -2. **Buy a third-party data API** (Alibaba Cloud's marketplace and similar sell - `item_search` endpoints). Clean data, but you pay per call and you're at the - mercy of the vendor. -3. **Drive a real, logged-in browser at low frequency** and hope the rate stays - under the radar. Works for occasional manual checks, useless for reliable - monitoring at scale. - -None of these are "spin up a container and go." That's the point. - -## The reusable checklist - -Before I touch Playwright again on a new target, I now answer three questions in -order: - -1. **Where does the data actually live?** Open the page with JavaScript disabled - (or read the raw HTML). If the data is in the HTML, I don't need a browser at - all — I need an HTTP client and a parser. The browser is waste. -2. **If it's not in the HTML, what does the async request look like?** Open - DevTools → Network, find the XHR/fetch that returns the data, and read its - headers and query params. Is there a signature? Is it stable, or does it change - per request? -3. **Is there a signed API?** If yes, stop. Decide up front whether the target is - worth either (a) reverse-engineering the sign, or (b) paying a data vendor. If - neither, the honest answer is "this costs more than it's worth" — and *knowing* - that in the first hour is itself a win. - -Most scraping guides skip all three and jump straight to "install Puppeteer." -That's the expensive path, the one that burns a day discovering the hard way what -a 60-second investigation would have told you. - -## What I'd do differently - -- **Disable JavaScript before reaching for a browser.** It's the single fastest - signal for "server-rendered vs. client-fetched." Ten seconds, no setup. -- **Don't buy stealth from a generic renderer.** Stealth is either a product you - pay for (browserless Cloud, ScrapingBee, etc.) or something you build and - maintain. It is not a checkbox in an open-source container. -- **Distinguish "rendering" from "extraction."** A headless browser returns HTML; - it does not hand you structured product fields. Even when rendering works, - someone still has to write the selectors or the `evaluate` script. That's a - separate task — plan for it, don't assume it's free. - -## The result - -The contrast sharpened into a rule I now apply to every project: **decide whether -the target is server-rendered or API-gated before choosing a tool.** On Carousell -(server-rendered), a plain HTTP parser has archived thousands of listings with -prices and photos for months. On Goofish (signed API), I stopped after an honest -look at the effort and the maintenance burden — which is itself the right -outcome for a project where a manual search once in a while does everything I -needed. - -A headless browser is the right tool *sometimes* — for screenshots, PDFs, taking -over a human session, or targets that render server-side. It is not a universal -scraping key, and treating it as one is the expensive mistake. - ---- - -## Want me to look at a site before you commit to scraping it? - -Most scraping projects fail in the first hour because nobody checked whether the -target even *lets* data be scraped cheaply. I do that check before writing any -code — and I build the monitors, notification pipelines, and self-hosted -infrastructure that actually run. If you're eyeing a data source and want to know -if it's an afternoon or a month, let's talk: - -- 📱 **WhatsApp:** [+60 12-797 2969](https://wa.me/60127972969) -- 📧 **Email:** [me@hoelee.com](mailto:me@hoelee.com) -- 🌐 **Website:** [hoelee.com](https://hoelee.com) -```` - ---- - -## 文章 05 / 11:一个字符让我的 authentik CSS 静默失效 -- **Slug**: `authentik-css-greater-than-bug` -- **英文标题**: The Character That Silently Broke My authentik CSS -- **分类**: `devops` | **发布日期**: 2026-09-20 -- **线上地址**: https://blog.hoelee.com/posts/authentik-css-greater-than-bug/ (EN) | https://blog.hoelee.com/posts/zh/authentik-css-greater-than-bug/ (ZH) -- **本篇审核状态**: ⏳ 待审核 (Pending) - -### ✍️ 顾问审阅意见区 (Review Feedback) -```text -【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 -【事实与数字核对】: -【人设与用词卫生】: -【CRO与转化建议】: -``` - -### 🇨🇳 中文版原文 (Chinese Markdown Twin) -````markdown ---- -title: "一个字符让我的 authentik CSS 静默失效" -description: "我的 authentik 自定义 CSS 看起来完全正确,也匹配到了目标元素,却毫无效果。原因是一个 > 字符被 authentik 转义成了无效文本。" -pubDate: 2026-09-20 -updatedDate: 2026-10-16 -category: devops -tags: ["authentik", "css", "self-hosting", "debugging", "browser"] -ogImage: /og/zh-authentik-css-greater-than-bug.jpg -banner: /banners/authentik-css-greater-than-bug.jpg -draft: false ---- - -我花了一个下午去查一条本该三十秒解决的 CSS 规则。 - -我想隐藏 authentik 登录页脚里的一行——硬编码的「Powered by -authentik」署名。这条规则在我做过的其他项目里从来都是有效的: - -```css -ul.pf-c-list > li:last-child { - display: none !important; -} -``` - -它毫无作用。不是「看起来有点不对」——那个元素依然完整地显示着。下面 -是我追过的四个错误答案、唯一正确的答案,以及我本该第一个就做的调试 -动作。 - -## 为什么这不只是一行页脚的问题 - -如果你自托管 authentik,曾经把 CSS 粘进 -**System → Brands → Custom CSS** 却完全没效果,那你多半以为自己哪里 -写错了。你几乎肯定没写错。样式表被接收、被存储、被送到浏览器、也被 -解析了——然后静默失效,你够得着的任何日志里都没有报错。 - -这是最糟糕的一类 bug:没有反馈回路。这篇文章把这条回路还给你。 - -## 错误答案 #1:这是 shadow DOM,CSS 进不去 - -我的第一个假设。现代 Web Component 常常把标记藏在 shadow root 后面, -普通的文档 CSS 无法跨越那道边界。authentik 的登录页确实由 -Web Component 渲染——我在页面源码里见过 `` 和 -``——所以这看起来显然是答案。 - -我从打包好的 bundle 里把组件定义读出来确认: - -```js -var oe = class extends L { - createRenderRoot() { return this } - render() { ... } -} -``` - -`createRenderRoot(){ return this }` 意味着**没有 shadow root**——组件 -直接渲染进 light DOM。普通 CSS 完全可以作用于它。 - -错误答案。继续。 - -## 错误答案 #2:CSS 根本没被注入 - -下一个理论:我的 CSS 压根没进到页面里。我在返回的 HTML 里搜了一个 -自己规则里的特征类名: - -``` - -**我搭建可靠的监控与通知管线——Telegram/WhatsApp 告警、抓取器,以及背后的 -基础设施。** 告诉我你要监控什么、通知要发到哪里: +
+ +
+ + + + + + + +
+
+ + +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
-- [WhatsApp 联系 →](https://wa.me/60127972969?text=Hi%20Hoelee%2C%20I%20need%20a%20monitoring%2Fnotification%20pipeline) -- [Email 联系 →](mailto:me@hoelee.com?subject=Monitoring%20%2F%20notification%20pipeline) -- [hoelee.com](https://www.hoelee.com) -```` +## 核心痛点:240 秒的时长硬墙 -### 🇬🇧 英文版原文 (English Markdown Primary) -````markdown ---- -title: "Why Telegram Bot Notifications Die: IPv6, DNS, and a 400 That Took a Day" -description: "A debugging story: a Dockerized telegram monitor whose sendPhoto calls returned 400 from nginx/1.30.1 while getMe worked fine — an IPv6-only DNS answer, a wrong extra_hosts IP, and a multipart join that corrupted JPEG bytes." -pubDate: 2026-03-25 -updatedDate: 2026-09-09 -category: devops -blueprint: ai-agent-automation -blueprintLayer: L1-deterministic-orchestration -tags: [docker, telegram, python, dns, ipv6, debugging, portainer] -ogImage: /og/why-telegram-bot-notifications-die.jpg -banner: /banners/why-telegram-bot-notifications-die.jpg ---- +在初期的实验中,使用默认配置调用 ComfyUI 生成音频时,经常陷入两个误区: -I run a small monitoring bot that watches Carousell for newly-listed -listings and pings me on Telegram when something fresh appears. One day it -stopped pinging. The container was healthy, the scraper was still archiving -listings into NocoDB — but every notification died with the same three -characters in the log: +1. **尾奏被腰斩(硬截断)**:若将 `max_duration` 设为 `240.0s` 并填满长歌词,模型在唱到最后一段副歌时时间刚好用尽。此前跑出的 12 首样本无一例外精确停在 `240.000s`,尾部毫无渐隐,沦为残次品。 +2. **语速失控(慌乱压缩)**:如果试图在有限的窗口内通过提示词催促模型“唱快点”,自回归声学模型会自动压缩发音时长,导致原本舒缓的民谣变成含混不清的“急口令”。 -``` -telegram sendPhoto failed: 400 ... nginx/1.30.1 +根本原因在于:**不能把最大时长(Max Duration)当成目标歌曲时长来设置。在自回归音频生成中,最大时长必须作为声学安全余量缓冲槽(Headroom Buffer)。** + +## 解决架构:三项核心工程策略 + +### 1. 295.0 秒 Headroom 留白公式 + +要得到一首体感约为 4 分钟的完整长歌,必须将**歌词词量规划在 210秒~260秒区间**,而底层生成参数直接赋予 **295.0 秒**的宽松上限: + +$$\text{Headroom 留白余量} = \text{参数上限 (295s)} - \text{预估词量时长 (约 220s)} \approx 75\text{秒}$$ + +这 75 秒看似多余的余量,是自回归声学模型实现“体面收尾”的命脉所在: +- 保证最后一节副歌完整舒展唱完,不产生急促抢拍; +- 赋予模型充足的 Token 生成纯乐器 Outro 尾奏; +- 让尾音伴随混响自然衰减至真正的分贝零点。 + +### 2. 自动化硬切隔离门禁(Quarantine Gate) + +在批量跑批自动化脚本中,加入严格的质量门禁:凡是实际音频长度逼近上限(`duration >= 294.9s`)的文件,判定为发生硬截断,自动归档进 `未自然结尾/` 隔离目录;仅有在上限之前自然休止收音(`duration < 294.0s`)的成品才予以放行。 + +本次实跑的 60 首曲目最终时长均匀分布在 **129.9s 至 285.6s**,100% 实现了自然淡出。 + +### 3. 12GB 显存的高效自持 + +在 12GB 显存下运行 YuE2-3B BF16,必须严格执行显存释放策略: + +```bash +# 启动 ComfyUI(关键参数防 OOM) +cd /d/app/ComfyUI +./python_embeded/python.exe -s ComfyUI/main.py \ + --windows-standalone-build \ + --port 8188 \ + --disable-pinned-memory \ + --disable-nvml-pressure \ + --cache-classic ``` -That string, `nginx/1.30.1`, became the villain of a day-long debugging -session. This is the story of how a deceptively small bug turned out to be -three separate problems stacked on top of each other — and how I'd find each -one faster next time. - -## The problem - -The bot had two jobs: **collect** listings, and **notify** me. Collection -worked. Notification didn't. The log said `400 Bad Request` and pointed at a -server identifying itself as `nginx/1.30.1`. - -My first assumption was textbook: **something in the network is intercepting -the request.** `nginx/1.30.1` is not a header I associated with Telegram's -API. A 400 with an HTML body (Telegram returns JSON even on errors) smelled -like a local reverse proxy or a VPN gateway rejecting traffic before it ever -left the machine. - -Assumptions like that are cheap. They're also wrong a lot. Let me walk -through what I actually found. - -## What I tried, and why each thing failed - -### Round 1: it must be DNS / IPv6 - -I checked `getMe` from inside the container. It worked. Then I checked -`sendMessage`. It failed. Same token, same container, one method up, one down. - -The giveaway was in how the two endpoints resolved: - -``` -# inside the container -$ getent hosts api.telegram.org -2001:67c:4e8:f004::9 api.telegram.org -``` - -The container resolved `api.telegram.org` to **IPv6 only** — a single `AAAA` -record and no `A` record. The container ran on a Docker bridge network with -**no IPv6 connectivity**. So every request that needed `api.telegram.org` was -trying to reach an IPv6 address it had no route to. - -The fix looked obvious: pin the IPv4 address with `extra_hosts`. I did, and -the DNS answer became exactly what I expected: - -``` -149.154.167.220 api.telegram.org -``` - -And the notifications **still failed.** Same 400. My proud fix did nothing. - -### Round 2: I picked the wrong IP - -Here's a mistake worth remembering: I hard-coded `149.154.167.220` from -memory. When I finally queried a public resolver, the real `A` record for -`api.telegram.org` was different: - -``` -149.154.166.110 api.telegram.org # what DNS actually says -149.154.167.220 api.telegram.org # what I hard-coded -``` - -`167.220` is *inside* Telegram's IP range (`149.154.160.0/20`), so it's not -"wrong" in the sense of being somebody else's server — but it's not the -active endpoint, and bot-API traffic to it behaved unpredictably. I switched -to `166.110`. It still failed. So the IP wasn't the whole story either. - -### Round 3: the same command, two different outcomes - -This was the moment the whole thing got weird. Inside one container, at -almost the same second: - -- the **long-running monitor process** (`PID 1`) → `sendPhoto` failed, 400 -- a **fresh `docker exec` process** running identical code → `sendPhoto` - succeeded, 200 - -Same container. Same code. Same payload. Same second. - -I ruled out token, chat_id, emoji in the caption, Unicode quotes, image -format, environment variables, and the image URL itself — I download-tested -the photo and it was a perfectly valid JPEG. Nothing in the code differed -between the two paths. - -When you hit a contradiction like that — "identical inputs, opposite -outputs" — the answer is usually that the inputs *aren't* identical. But -finding the difference took one more frame change. - -### Round 4: `nginx/1.30.1` is Telegram - -I re-read the raw 400 response instead of assuming. The response was an HTML -"400 Bad Request" page, and the `Server` header was `nginx/1.30.1`. - -**That nginx is Telegram's own edge.** Telegram's API sits behind nginx -(version 1.30.1), and when a request is malformed *before* it reaches their -application layer, nginx itself answers with a plain 400 page — no JSON, no -friendly error code. - -That reframed everything. The request wasn't being intercepted. It was -**reaching Telegram, and Telegram's nginx was rejecting it as malformed.** - -And the malformed thing was the one part I hadn't scrutinized: the -`sendPhoto` multipart body. - -## The fix - -My original code built the multipart body like this — the kind of -"obviously fine" line that ships a subtle bug: - -```python -body = b"\r\n".join(body_lines) -``` - -That `join` looks convenient, but a JPEG is **binary data**. Its bytes include -`\r\n` byte sequences in the middle of the image data. Joining with `\r\n` -as the delimiter corrupts the exact bytes that are supposed to be the image -payload. Telegram receives a body whose multipart boundaries are broken, so -its nginx rejects the request with a 400 before the bot API ever parses it. - -The correct approach is to assemble the body field by field, keeping binary -data untouched: - -```python -boundary = "----tg" + token_hex(8) - -parts = [] -parts.append(f"--{boundary}\r\n".encode()) -parts.append(b'Content-Disposition: form-data; name="chat_id"\r\n\r\n') -parts.append(f"{chat_id}\r\n".encode()) - -parts.append(f"--{boundary}\r\n".encode()) -parts.append(b'Content-Disposition: form-data; name="caption"\r\n\r\n') -parts.append(f"{caption}\r\n".encode()) - -parts.append(f"--{boundary}\r\n".encode()) -parts.append( - b'Content-Disposition: form-data; name="photo"; ' - b'filename="image.jpg"\r\nContent-Type: image/jpeg\r\n\r\n' -) -parts.append(image_bytes) # ← binary stays binary -parts.append(b"\r\n") - -parts.append(f"--{boundary}--\r\n".encode()) - -body = b"".join(parts) # join bytes, not lines -``` - -The difference is `b"".join(parts)` instead of `b"\r\n".join(...)`: each part -is already a complete chunk with its own framing, and we concatenate them -verbatim rather than inserting a delimiter *between every element*. - -There's a second, higher-level fix worth naming: **stop asking Telegram to -download the image for you.** My earlier code passed the image as a *URL* and -let Telegram fetch it: - -```python -tg("sendPhoto", {"photo": image_url, "caption": caption}) -``` - -That means Telegram's servers have to reach out to the source CDN — and if -that CDN is flaky or geo-blocks Telegram's crawlers, you get intermittent -failures that are impossible to reproduce locally. Downloading the image -yourself, then uploading the bytes, removes an entire class of flakiness and -gives you a chance to validate the bytes before you send them. - -## What I'd do differently - -1. **Read the raw response, not the assumption.** `nginx/1.30.1` sat in logs - for hours while I chased phantom proxies. Look up who owns the header - before inventing a man-in-the-middle. -2. **Verify a hard-coded IP against a live resolver.** Memory is not DNS. - `dig +short api.telegram.org` takes three seconds and would have saved me - a whole round. -3. **Treat "identical inputs, opposite outputs" as a lie.** The inputs were - never identical — the two processes differed somewhere I wasn't looking. - The honest move is to diff the bytes, not the code. -4. **Never hand-join binary data with a text delimiter.** `b"\r\n".join()` on - a mix of text and JPEG is a corruption bug waiting to happen. - -## The result - -After the multipart fix, the monitor pushed a real notification through on -the next tick — image and all. I also folded in a retry queue so a failed -notification stays marked un-sent and is retried 30 seconds later instead of -silently vanishing. The whole episode cost the better part of a day, but it -turned into exactly the kind of bug I'll never trip over twice. +在批处理完成后及时调用 `/free` 卸载显存,避免连续生成多首长音频时产生显存碎片积压。 --- -*The bot is a personal project, but the lesson generalizes to any service -that relies on outbound notifications. If you've got a monitor, a scraper, or -an alert pipeline that needs to reach people reliably, let's talk.* +## 60 首长歌全集在线鉴赏 -**I build reliable notification and monitoring pipelines — Telegram/WhatsApp -alerts, scrapers, and the infrastructure around them.** Tell me what you need -to watch and where you need it delivered: +以下 60 首作品均已上传至 Publitio 媒体存储,支持 HTTP 206 自由拖拽定位。封面全量采用 1024×1024 独立生成的无字 WebP 艺术插画,并内嵌同步 LRC 歌词。 -- [WhatsApp me →](https://wa.me/60127972969?text=Hi%20Hoelee%2C%20I%20need%20a%20monitoring%2Fnotification%20pipeline) -- [Email me →](mailto:me@hoelee.com?subject=Monitoring%20%2F%20notification%20pipeline) -- [hoelee.com](https://www.hoelee.com) +*操作提示:可直接利用上方导航面板进行分类筛选,或从下拉菜单中快速直达指定曲目。* + +
+
+ The Thimble Under the Moss cover art +
+
+
+ 01. The Thimble Under the Moss + MP3 + 3分11秒 (191.1s) · 凯尔特竖琴民谣 · 清脆稚气女童声(类似 Cécile Corbel《Arrietty's Song》)|中速轻快(约 105 BPM) +
+ + +
+
+ +
+
+ Mist of Skellig Michael cover art +
+
+
+ 02. Mist of Skellig Michael + MP3 + 4分26秒 (266.2s) · 凯尔特竖琴民谣 · 空灵圣洁的小女孩独唱(类似 Enya + 幼态音色)|慢速悠长(约 72 BPM,字少音长) +
+ + +
+
+ +
+
+ The Rose of Connemara cover art +
+
+
+ 03. The Rose of Connemara + MP3 + 4分43秒 (283.1s) · 凯尔特竖琴民谣 · 纯净稚气少女音(类似 Cara Dillon 早期清亮少女感)|中慢速叙事(约 82 BPM) +
+ + +
+
+ +
+
+ Lanterns on the Moor cover art +
+
+
+ 04. Lanterns on the Moor + MP3 + 3分31秒 (211.2s) · 凯尔特竖琴民谣 · 俏皮精灵般的女童声(类似 Cécile Corbel 欢快舞曲风)|快速三拍子(约 128 BPM) +
+ + +
+
+ +
+
+ The Weaver of Raglan Lane cover art +
+
+
+ 05. The Weaver of Raglan Lane + MP3 + 4分39秒 (279.3s) · 凯尔特竖琴民谣 · 醇厚温暖的凯尔特民谣男声(类似 Luke Kelly,调剂男声)|中慢速(约 80 BPM) +
+ + +
+
+ +
+
+ 硝子の花束 cover art +
+
+
+ 06. 硝子の花束 + MP3 + 3分49秒 (230.0s) · 日系治愈动漫 · 稚气通透、略带脆弱感的动漫少女音(祈妹风)|中慢速钢琴弦乐(约 78 BPM) +
+ + +
+
+ +
+
+ 銀の時計塔と宵の歌 cover art +
+
+
+ 07. 銀の時計塔と宵の歌 + MP3 + 4分34秒 (274.8s) · 日系治愈动漫 · 清亮圣洁少女音 + 梶浦语吟唱|中速华尔兹三拍子(约 110 BPM) +
+ + +
+
+ +
+
+ 森の郵便屋さん cover art +
+
+
+ 08. 森の郵便屋さん + MP3 + 3分44秒 (225.0s) · 日系治愈动漫 · 极度轻柔、如耳语般的稚气女童声|慢速木吉他与竖琴(约 68 BPM) +
+ + +
+
+ +
+
+ 白鳥の祈り cover art +
+
+
+ 09. 白鳥の祈り + MP3 + 4分06秒 (246.3s) · 日系治愈动漫 · 空灵通透的高音少女/女童声,尾音带空灵共鸣|慢速大气(约 70 BPM) +
+ + +
+
+ +
+
+ 星屑のオルゴール cover art +
+
+
+ 10. 星屑のオルゴール + MP3 + 3分31秒 (211.8s) · 日系治愈动漫 · 清甜稚气的少女声|中慢速轻盈感(约 88 BPM) +
+ + +
+
+ +
+
+ ひまわり行進曲 cover art +
+
+
+ 11. ひまわり行進曲 + MP3 + 3分18秒 (198.0s) · 日系元气童趣 · 元气满满的小女孩独唱/齐唱感|中快速欢快节奏(约 118 BPM) +
+ + +
+
+ +
+
+ プリンは世界を救うのだ! cover art +
+
+
+ 12. プリンは世界を救うのだ! + MP3 + 3分23秒 (203.4s) · 日系元气童趣 · 软萌夸张的稚气萝莉音(高音、语速快、字密)|快速电音流行(约 145 BPM) +
+ + +
+
+ +
+
+ こねこ探偵団のテーマ cover art +
+
+
+ 13. こねこ探偵団のテーマ + MP3 + 2分16秒 (136.1s) · 日系元气童趣 · 奶声奶气的女童声(6~8岁童音感)|中速轻快爵士童谣(约 115 BPM) +
+ + +
+
+ +
+
+ 夏祭りのラムネ星 cover art +
+
+
+ 14. 夏祭りのラムネ星 + MP3 + 3分14秒 (195.0s) · 日系元气童趣 · 清亮少年男声 + 稚气少女声(调剂少年音)|中快速夏日流行(约 122 BPM) +
+ + +
+
+ +
+
+ ほうきに乗って宅配便 cover art +
+
+
+ 15. ほうきに乗って宅配便 + MP3 + 3分16秒 (196.1s) · 日系元气童趣 · 清脆阳光的小女孩声音|中速轻快复古流行(约 116 BPM) +
+ + +
+
+ +
+
+ 白露·竹间灯 cover art +
+
+
+ 16. 白露·竹间灯 + MP3 + 3分42秒 (222.6s) · 中文国风古意 · 清甜稚气的少女/女童声|中速轻快电子国风(约 108 BPM) +
+ + +
+
+ +
+
+ 小鲤跃龙门 cover art +
+
+
+ 17. 小鲤跃龙门 + MP3 + 2分09秒 (129.9s) · 中文国风古意 · 活泼软萌的稚气少女音(语速偏快、吐字灵动)|中快速(约 120 BPM) +
+ + +
+
+ +
+
+ 云海归鲲 cover art +
+
+
+ 18. 云海归鲲 + MP3 + 3分56秒 (236.9s) · 中文国风古意 · 空灵仙气的少年假声/美声男声(调剂男声)|慢速悠远(约 68 BPM) +
+ + +
+
+ +
+
+ 纸伞巷 cover art +
+
+
+ 19. 纸伞巷 + MP3 + 3分34秒 (214.6s) · 中文国风古意 · 清亮温婉的少女声(带一点点江南小调韵味)|中慢速(约 80 BPM) +
+ + +
+
+ +
+
+ 山间小道士 cover art +
+
+
+ 20. 山间小道士 + MP3 + 3分07秒 (187.6s) · 中文国风古意 · 纯真稚气的小女孩/少女声音|中速轻快民谣古风(约 105 BPM) +
+ + +
+
+ +
+
+ 橘子汽水的夏天 cover art +
+
+
+ 21. 橘子汽水的夏天 + MP3 + 2分48秒 (169.0s) · 温暖民谣治愈 · 清澈稚气的少女声|中慢速木吉他民谣(约 82 BPM) +
+ + +
+
+ +
+
+ 外婆的小院 cover art +
+
+
+ 22. 外婆的小院 + MP3 + 3分32秒 (212.4s) · 温暖民谣治愈 · 纯真软糯的小女孩声音|慢速温情(约 72 BPM) +
+ + +
+
+ +
+
+ 开往北方的绿皮车 cover art +
+
+
+ 23. 开往北方的绿皮车 + MP3 + 3分36秒 (216.3s) · 温暖民谣治愈 · 低沉温暖的民谣男声(调剂男声)|慢速叙事(约 75 BPM) +
+ + +
+
+ +
+
+ 写给流浪猫的信 cover art +
+
+
+ 24. 写给流浪猫的信 + MP3 + 2分09秒 (129.9s) · 温暖民谣治愈 · 俏皮温柔的稚气少女音|中速轻快尤克里里/木吉他(约 98 BPM) +
+ + +
+
+ +
+
+ 平凡的傍晚 cover art +
+
+
+ 25. 平凡的傍晚 + MP3 + 3分41秒 (221.0s) · 温暖民谣治愈 · 温柔治愈的青年男声(调剂男声)|慢速钢琴与木吉他(约 74 BPM) +
+ + +
+
+ +
+
+ Light of the Eventide cover art +
+
+
+ 26. Light of the Eventide + MP3 + 4分09秒 (249.0s) · 空灵天籁合唱 · 天籁女童高音领唱 + 纯净童声合唱|极慢速庄严(约 66 BPM) +
+ + +
+
+ +
+
+ Bells of the Winter Star cover art +
+
+
+ 27. Bells of the Winter Star + MP3 + 2分47秒 (167.6s) · 空灵天籁合唱 · 清脆女童多声部齐唱與轮唱|中快速灵动节奏(约 125 BPM) +
+ + +
+
+ +
+
+ Paper Planes in the Wind cover art +
+
+
+ 28. Paper Planes in the Wind + MP3 + 3分25秒 (205.5s) · 空灵天籁合唱 · 清亮纯真的女童领唱 + 学院风童声合唱|中速温暖(约 96 BPM) +
+ + +
+
+ +
+
+ Lullaby of the Little Star cover art +
+
+
+ 29. Lullaby of the Little Star + MP3 + 3分47秒 (227.8s) · 空灵天籁合唱 · 稚气纯净的小女孩独唱(突出童真独唱感)|慢速温柔(约 70 BPM) +
+ + +
+
+ +
+
+ Hymn of the Morning Meadow cover art +
+
+
+ 30. Hymn of the Morning Meadow + MP3 + 4分19秒 (259.9s) · 空灵天籁合唱 · 神圣清澈的女童领唱 + 宏大童声和声(帕赫贝尔卡农式递进)|慢速治愈(约 72 BPM) +
+ + +
+
+ +
+
+ 地板下的借物小人 cover art +
+
+
+ 31. 地板下的借物小人 + MP3 + 3分07秒 (187.7s) · 凯尔特童话民谣 (中文) · 清脆稚气女童声|中速轻快凯尔特竖琴与锡哨(约 105 BPM) +
+ + +
+
+ +
+
+ 迷雾孤岛的竖琴 cover art +
+
+
+ 32. 迷雾孤岛的竖琴 + MP3 + 3分24秒 (204.4s) · 凯尔特童话民谣 (中文) · 空灵圣洁的小女孩独唱|慢速悠长(约 70 BPM,字少音长) +
+ + +
+
+ +
+
+ 石楠花开的高地 cover art +
+
+
+ 33. 石楠花开的高地 + MP3 + 3分36秒 (216.9s) · 凯尔特童话民谣 (中文) · 纯净稚气少女音|中慢速木吉他与凯尔特小提琴(约 82 BPM) +
+ + +
+
+ +
+
+ 橡树下的萤火舞会 cover art +
+
+
+ 34. 橡树下的萤火舞会 + MP3 + 3分43秒 (223.1s) · 凯尔特童话民谣 (中文) · 俏皮精灵般的女童声(语速快、节奏感强)|快速三拍子(约 128 BPM) +
+ + +
+
+ +
+
+ 老航海家的绿宝石 cover art +
+
+
+ 35. 老航海家的绿宝石 + MP3 + 3分49秒 (229.8s) · 凯尔特童话民谣 (中文) · 醇厚温暖的凯尔特民谣男声(调剂男声)|中慢速(约 80 BPM) +
+ + +
+
+ +
+
+ 玻璃温室的告别 cover art +
+
+
+ 36. 玻璃温室的告别 + MP3 + 3分37秒 (217.0s) · 日系治愈物语 (中文) · 稚气通透、略带脆弱感的动漫少女音|中慢速钢琴与弦乐(约 78 BPM) +
+ + +
+
+ +
+
+ 银色钟塔与暮光咏叹 cover art +
+
+
+ 37. 银色钟塔与暮光咏叹 + MP3 + 4分01秒 (241.4s) · 日系治愈物语 (中文) · 清亮圣洁少女音 + 造语吟唱|中速古典哥特华尔兹(约 110 BPM) +
+ + +
+
+ +
+
+ 森林邮差的蒲公英 cover art +
+
+
+ 38. 森林邮差的蒲公英 + MP3 + 3分26秒 (206.7s) · 日系治愈物语 (中文) · 极度轻柔、如耳语般的稚气女童声|慢速木吉他与钢片琴(约 68 BPM) +
+ + +
+
+ +
+
+ 白鸟与雪原的祈愿 cover art +
+
+
+ 39. 白鸟与雪原的祈愿 + MP3 + 3分39秒 (220.0s) · 日系治愈物语 (中文) · 空灵通透的高音女童/少女声|慢速大气钢琴与管弦(约 70 BPM) +
+ + +
+
+ +
+
+ 发条星尘八音盒 cover art +
+
+
+ 40. 发条星尘八音盒 + MP3 + 3分18秒 (198.2s) · 日系治愈物语 (中文) · 清甜稚气的少女声|中慢速八音盒与木吉他(约 88 BPM) +
+ + +
+
+ +
+
+ 向日葵小队出发 cover art +
+
+
+ 41. 向日葵小队出发 + MP3 + 2分39秒 (159.4s) · 元气童趣流行 (中文) · 元气满满的小女孩领唱 + 童声合唱感|中快速欢快节奏(约 118 BPM) +
+ + +
+
+ +
+
+ 焦糖布丁保卫战! cover art +
+
+
+ 42. 焦糖布丁保卫战! + MP3 + 3分38秒 (218.9s) · 元气童趣流行 (中文) · 软萌夸张的稚气萝莉音(高音、语速快、字密)|快速电音流行(约 145 BPM) +
+ + +
+
+ +
+
+ 猫咪侦探事务所 cover art +
+
+
+ 43. 猫咪侦探事务所 + MP3 + 2分31秒 (151.4s) · 元气童趣流行 (中文) · 奶声奶气的女童声(6~8岁童音感)|中速轻快木琴与铜管(约 115 BPM) +
+ + +
+
+ +
+
+ 夏夜烟火与波子汽水 cover art +
+
+
+ 44. 夏夜烟火与波子汽水 + MP3 + 3分07秒 (187.8s) · 元气童趣流行 (中文) · 清亮少年男声 + 稚气少女声(调剂少年音)|中快速夏日流行(约 122 BPM) +
+ + +
+
+ +
+
+ 骑上扫帚送快递 cover art +
+
+
+ 45. 骑上扫帚送快递 + MP3 + 3分08秒 (188.5s) · 元气童趣流行 (中文) · 清脆阳光的小女孩声音|中速轻快木吉他与手鼓(约 116 BPM) +
+ + +
+
+ +
+
+ 小满·青梅煮雨 cover art +
+
+
+ 46. 小满·青梅煮雨 + MP3 + 3分34秒 (214.9s) · 国风新篇古韵 (中文) · 清甜稚气的少女/女童声|中速轻快电子国风(约 106 BPM) +
+ + +
+
+ +
+
+ 糖画摊前的小狐仙 cover art +
+
+
+ 47. 糖画摊前的小狐仙 + MP3 + 3分12秒 (192.2s) · 国风新篇古韵 (中文) · 活泼软萌的稚气少女音(字密语速快)|中快速(约 124 BPM) +
+ + +
+
+ +
+
+ 鲛人泪·沧海月 cover art +
+
+
+ 48. 鲛人泪·沧海月 + MP3 + 3分59秒 (239.8s) · 国风新篇古韵 (中文) · 空灵仙气的少年假声/美声男声(调剂男声)|慢速深邃(约 68 BPM) +
+ + +
+
+ +
+
+ 兰亭旧墨 cover art +
+
+
+ 49. 兰亭旧墨 + MP3 + 3分49秒 (229.3s) · 国风新篇古韵 (中文) · 清亮温婉的少女声|中慢速古筝与二胡(约 80 BPM) +
+ + +
+
+ +
+
+ 采药小童下山记 cover art +
+
+
+ 50. 采药小童下山记 + MP3 + 3分24秒 (204.4s) · 国风新篇古韵 (中文) · 纯真稚气的小女孩声音|中速轻快木吉他与竹笛(约 104 BPM) +
+ + +
+
+ +
+
+ 晒太阳的旧毛衣 cover art +
+
+
+ 51. 晒太阳的旧毛衣 + MP3 + 3分04秒 (184.9s) · 温暖民谣新篇 (中文) · 清澈稚气的少女声|中慢速木吉他民谣(约 80 BPM) +
+ + +
+
+ +
+
+ 奶奶的桂花糕 cover art +
+
+
+ 52. 奶奶的桂花糕 + MP3 + 3分42秒 (222.4s) · 温暖民谣新篇 (中文) · 纯真软糯的小女孩声音|慢速温情口琴与吉他(约 72 BPM) +
+ + +
+
+ +
+
+ 北方的末班渡轮 cover art +
+
+
+ 53. 北方的末班渡轮 + MP3 + 3分49秒 (229.6s) · 温暖民谣新篇 (中文) · 低沉温暖的民谣男声(调剂男声)|慢速深沉(约 74 BPM) +
+ + +
+
+ +
+
+ 云朵收集指南 cover art +
+
+
+ 54. 云朵收集指南 + MP3 + 2分56秒 (176.4s) · 温暖民谣新篇 (中文) · 俏皮温柔的稚气少女音|中速轻快(约 98 BPM) +
+ + +
+
+ +
+
+ 街角二十四小时书店 cover art +
+
+
+ 55. 街角二十四小时书店 + MP3 + 4分13秒 (253.4s) · 温暖民谣新篇 (中文) · 温柔治愈的青年男声(调剂男声)|慢速钢琴与木吉他(约 74 BPM) +
+ + +
+
+ +
+
+ 暮光归途 cover art +
+
+
+ 56. 暮光归途 + MP3 + 4分02秒 (242.6s) · 天籁童声圣咏 (中文) · 天籁女童高音领唱 + 纯净童声合唱|极慢速庄严管风琴与弦乐(约 66 BPM) +
+ + +
+
+ +
+
+ 冬夜银铃 cover art +
+
+
+ 57. 冬夜银铃 + MP3 + 2分59秒 (179.0s) · 天籁童声圣咏 (中文) · 清脆女童多声部齐唱与轮唱|中快速灵动三拍子(约 125 BPM) +
+ + +
+
+ +
+
+ 迎风飞翔的纸飞机 cover art +
+
+
+ 58. 迎风飞翔的纸飞机 + MP3 + 3分53秒 (233.2s) · 天籁童声圣咏 (中文) · 清亮纯真的女童领唱 + 学院风童声合唱|中速温暖(约 96 BPM) +
+ + +
+
+ +
+
+ 小星星的晚安曲 cover art +
+
+
+ 59. 小星星的晚安曲 + MP3 + 3分51秒 (232.0s) · 天籁童声圣咏 (中文) · 稚气纯净的小女孩独唱|慢速竖琴与小提琴(约 70 BPM) +
+ + +
+
+ +
+
+ 晨曦草地的赞美诗 cover art +
+
+
+ 60. 晨曦草地的赞美诗 + MP3 + 4分26秒 (266.0s) · 天籁童声圣咏 (中文) · 神圣清澈的女童领唱 + 宏大童声和声(卡农式递进)|慢速治愈(约 72 BPM) +
+ + +
+
+ + + +--- + +## 需要为你的业务构建自动化 AI 媒体流水线? + +我为马来西亚及海外中小企业提供定制化自托管 AI 系统部署、自动化音视频内容生产管线以及全栈网站开发服务。 + +- **WhatsApp**: [012-7972969](https://wa.me/60127972969) +- **Email**: [me@hoelee.com](mailto:me@hoelee.com?subject=AI%20Audio%20Pipeline%20Inquiry) +- **个人网站**: [hoelee.com](https://hoelee.com) ```` --- diff --git a/docs/consultant-review/batches/batch-06.md b/docs/consultant-review/batches/batch-06.md index 1d440b1..b78ae0c 100644 --- a/docs/consultant-review/batches/batch-06.md +++ b/docs/consultant-review/batches/batch-06.md @@ -1,10 +1,10 @@ # 博客文章顾问审阅资料包 — Batch-06 > **批次编号**:`Batch-06` -> **包含文章数**:11 篇 -> **本批次总字符量**:167,652 字(严格限制 < 200,000 字) +> **包含文章数**:1 篇 +> **本批次总字符量**:131,667 字(严格限制 < 200,000 字) > **模式**:BILINGUAL -> **生成时间**:2026-10-27 03:02:03 +> **生成时间**:2026-10-27 04:23:31 # 外部顾问审阅前置须知与工程背景规范 @@ -39,25 +39,15 @@ ## 本批次文章目录索引 -1. [devops] **为什么你的 CDP 点击会静默失效:平滑滚动、最小化窗口与 JS 派发事件** (`why-your-cdp-clicks-silently-fail`) — ~12,514 字符 -2. [devops] **Prometheus 明明有数据,Grafana 面板却全是 No data 的原因** (`why-your-grafana-dashboard-shows-no-data`) — ~11,212 字符 -3. [devops] **你的“磁盘将满”告警在说谎:别再按百分比告警** (`your-disk-full-alert-is-lying`) — ~8,912 字符 -4. [engineering] **浏览器翻译没有 API:我给一个纯中文网页应用加上了英文模式** (`adding-english-mode-to-a-chinese-only-web-app`) — ~18,070 字符 -5. [engineering] **排查 Remotion 视频抽搐:为什么在背景图挂载音频低频 Scale 会毁了转场** (`debugging-remotion-video-jitter`) — ~15,111 字符 -6. [engineering] **把字体嵌进 PDF,让它在任何机器上都长一样** (`embedding-fonts-so-a-pdf-looks-the-same-everywhere`) — ~11,465 字符 -7. [engineering] **那个把静默丢失更新变成 409 的 JPA 字段:@Version 乐观锁** (`jpa-version-field-lost-update`) — ~19,575 字符 -8. [engineering] **把 CodeIgniter 4 应用从 IIS 迁移到 OpenLiteSpeed** (`migrating-codeigniter-iis-to-openlitespeed`) — ~23,361 字符 -9. [engineering] **用「热浏览器会话」爬取有反爬墙的电商网站** (`scraping-bot-walled-marketplace-warm-browser-session`) — ~16,928 字符 -10. [engineering] **JavaScript 文件静默失效的两种方式:而页面看上去一切正常** (`two-ways-a-javascript-file-stops-working-and-looks-fine`) — ~11,294 字符 -11. [engineering] **逐页验证一份 19 页的 PDF 报告** (`verifying-a-pdf-report-page-by-page`) — ~19,210 字符 +1. [tutorials] **用 YuE2 BF16 生成完整长歌:突破时长限制与音频硬截断** (`generating-full-length-songs-with-yue2-comfyui-en`) — ~131,667 字符 --- -## 文章 01 / 11:为什么你的 CDP 点击会静默失效:平滑滚动、最小化窗口与 JS 派发事件 -- **Slug**: `why-your-cdp-clicks-silently-fail` -- **英文标题**: Why Your CDP Clicks Silently Fail: Smooth Scroll, Minimised Windows, and JS-Dispatched Events -- **分类**: `devops` | **发布日期**: 2025-03-19 -- **线上地址**: https://blog.hoelee.com/posts/why-your-cdp-clicks-silently-fail/ (EN) | https://blog.hoelee.com/posts/zh/why-your-cdp-clicks-silently-fail/ (ZH) +## 文章 01 / 01:用 YuE2 BF16 生成完整长歌:突破时长限制与音频硬截断 +- **Slug**: `generating-full-length-songs-with-yue2-comfyui` +- **英文标题**: Generating Full-Length Songs with YuE2 BF16: Overcoming Duration Limits and Audio Truncation +- **分类**: `tutorials` | **发布日期**: 2026-10-26 +- **线上地址**: https://blog.hoelee.com/posts/generating-full-length-songs-with-yue2-comfyui/ (EN) | https://blog.hoelee.com/posts/zh/generating-full-length-songs-with-yue2-comfyui/ (ZH) - **本篇审核状态**: ⏳ 待审核 (Pending) ### ✍️ 顾问审阅意见区 (Review Feedback) @@ -68,4073 +58,3294 @@ 【CRO与转化建议】: ``` -### 🇨🇳 中文版原文 (Chinese Markdown Twin) -````markdown ---- -title: "为什么你的 CDP 点击会静默失效:平滑滚动、最小化窗口与 JS 派发事件" -description: "Chrome DevTools Protocol 点击报告成功却毫无反应的三个原因:平滑滚动导致的过期坐标、最小化窗口被丢弃的坐标输入、以及页面收到了点击但拒绝了它。" -pubDate: 2025-03-19 -updatedDate: 2026-09-29 -category: devops -tags: [cdp, chrome, react, browser-automation, debugging, python] -ogImage: /og/zh-why-your-cdp-clicks-silently-fail.jpg -banner: /banners/why-your-cdp-clicks-silently-fail.jpg -draft: false ---- - -如果你用 Chrome DevTools Protocol 驱动网页应用,你一定见过这个失败:脚本报告 `clicked @591,361`,元素明明在,点击也确实发出去了 —— 然后什么都没发生。没有异常,没有控制台报错,页面毫无变化。 - -我在自动化某平台卖家后台时整整耗了一个晚上在这上面。找到的三个原因值得写下来,因为**它们对「报告点击成功」的那段代码全都是隐形的**。 - -## 原因一:坐标过期,因为页面是平滑滚动的 - -最直观的点击辅助函数大概长这样: - -```python -r = self.ev("""(()=>{const e=%s; e.scrollIntoView({block:'center'}); - const b=e.getBoundingClientRect(); - return JSON.stringify({x:b.left+b.width/2, y:b.top+b.height/2});})()""") -self.click_xy(json.loads(r)["x"], json.loads(r)["y"]) -``` - -滚动到可视区、读取元素矩形、点它的中心。逻辑没错 —— 除非页面有 `scroll-behavior: smooth`(现代 UI 组件库里非常常见)。那时 `scrollIntoView()` 启动的是**动画**,而同一个 tick 里的 `getBoundingClientRect()` 返回的是元素**即将离开**的位置。你的点击落在元素**原来**的地方,落在当时在那儿的别的东西上,而日志忠实地告诉你:它点击了你要求的坐标。 - -修法是两行 —— 关掉平滑滚动,然后重新读矩形: - -```python -self.ev("""(()=>{document.documentElement.style.scrollBehavior='auto'; - if(document.body) document.body.style.scrollBehavior='auto'; return 'ok';})()""") -moved = self.ev("""(()=>{const e=%s; if(!e) return 'no'; - e.scrollIntoView({block:'center', behavior:'instant'}); return 'ok';})()""" % sel) -time.sleep(0.35) # 等布局稳定 -# 然后再读矩形(元素晚一帧才渲染的话,外面再套一层重试) -``` - -两个细节很关键:`scrollIntoView` 上的 `behavior:'instant'` 会覆盖 CSS;而读取前那一小段等待,才是让坐标可信的原因。没有重试循环的话,这个辅助函数在晚一帧渲染的元素上仍会偶发失败 —— **偶发失败是最糟的一类,因为它会让你怀疑自己的判断。** - -## 原因二:窗口最小化时,坐标点击被丢弃 - -修好之后,我的点击辅助函数在一次性探针里能用,一放进真正的脚本就再也没成功过。同样的选择器、同样的坐标、同样的页面。差别最后落在可见性上: - -``` -document.visibilityState → "hidden" -document.hasFocus() → true -``` - -当目标标签页不是可见窗口的活动标签页时,CDP 合成的坐标级鼠标事件是不可靠的 —— 浏览器可能接受、可能限流、也可能直接不往任何地方送。注意 `hasFocus()` **在文档隐藏时依然返回 `true`**,所以它不是有效的判断依据;要看的是 `document.hidden` / `visibilityState`。 - -两个修法,我都用: - -```python -def activate(self): # 把标签页提到窗口最前 - self.cdp("Page.bringToFront") - time.sleep(0.2) - -def click_js(self, sel): # 在页面内部派发事件来点击 - return self.ev("""(()=>{const e=%s; if(!e) return 'no'; - ['mousedown','mouseup','click'].forEach(k=> - e.dispatchEvent(new MouseEvent(k,{bubbles:true,cancelable:true,view:window}))); - return 'js-clicked';})()""" % sel) -``` - -`Page.bringToFront` 解决了常见情况。但真正从不出错的是 JS 派发的点击:它不依赖窗口是否可见,而且 React 挂在根节点上的事件监听器会收到它,和收到真实点击的方式完全一样 —— 因为事件冒泡到的是同一个根。一个用坐标点击五次才能打开一次的日期选择器,用这种方式**每次都开**。 - -需要知道的取舍:派发事件会跳过 hit-testing,所以它也会「点到」用户根本够不到的元素(被遮住、滚出屏幕、透明度为零)。在这里这是优点 —— 如果你用它去掩盖布局 bug,那就是坑 —— 所以凡是可视化的东西我都用坐标点击,而遇到自定义控件时才伸手去拿 `click_js`。 - -## 原因三:页面收到了点击,然后拒绝了它 - -这个最浪费时间,因为它的症状和前两个一模一样:点击发出去了,什么都没变。 - -区分它们只需要注入一个监听器: - -```js -window.__ev = []; -['mousedown','mouseup','click'].forEach(k => - document.addEventListener(k, e => window.__ev.push(k + ':' + e.target.tagName), true)); -``` - -- 有事件记录 → 输入链路是通的,问题在应用侧(原因三),或者在你读取结果的方式上(见下)。 -- 一条都没有 → 是原因一或原因二。 - -挂上监听器后我点了一次 `Confirm`,缓冲区满了 —— 说明点击没问题,是应用在说「不」。理由在一段我从没想过要看的文字里: - -> “Please create a new shop welcome voucher after the existing one is expired.” - -表单拒绝创建同类型的第二张券。没有字段级红字、头 500 毫秒里没有提示条、URL 也没变。**拒绝是真的,点击是无辜的。** - -这一类 bug 还有两个工具: - -```js -document.elementFromPoint(x, y) // 那个坐标上到底是什么? -document.querySelectorAll('button').length // 你的选择器到底命中了几个? -``` - -第二个抓到过一处很细的问题:门户页面在 DOM 里留了一个**隐藏的** `Confirm` 按钮(来自收起状态的日期面板),于是 `.pop()` 返回的是那个看不见的副本,点击自然落到了无人的地方。按可见性和尺寸一起过滤: - -```python -"[...document.querySelectorAll('button')].filter(b=>/^Confirm$/.test(b.innerText.trim())" -" && b.offsetParent!==null && b.getBoundingClientRect().width>0).pop()" -``` - -## 第四种「失败」,只有回读才发现 - -还有一类「失败」其实不是失败:**写入成功了,而你的读取是旧的。** 我因为列表页没有立刻显示,就断定创建被静默拒绝,又点了一次;后来才发现那张券一直都存在 —— 列表只是延迟了大约十分钟。这个教训可以推广:一次写入之后,唯一可信的结论是在**等待足够时间之后**回读得到的,而「看不到变化」意味着**未知**,不是失败。 - -## 检查清单 - -1. 关掉平滑滚动;用 `behavior:'instant'` 滚动;等一会儿再读矩形。 -2. 点击前调用 `Page.bringToFront`;判断依据用 `document.hidden`,不是 `hasFocus()`。 -3. 自定义控件用 JS 派发 `mousedown`/`mouseup`/`click`,别点坐标。 -4. 先挂事件监听器,证明输入是否到达,再去怪应用。 -5. 数一数选择器命中几个 —— 组件库里隐藏的重复元素很常见。 -6. 写入之后先等待再回读;永远不要重复点击一个还没验证过的提交按钮。 - -这些都不算冷门知识,但它们中的每一条,在一行 `clicked @591,361` 面前都是隐形的。如果你正在对着一个自己无法控制的后台做自动化:点击是整条链路里最不可靠的一环 —— 也是最容易被最后才怀疑的一环。 - -我平时就在做这类浏览器自动化与排障 —— 自托管服务、Docker 与 Traefik 栈,偶尔还有被 bot 墙挡住的市场页面。如果你有条工作流总因为「UI 有自己的想法」而断掉,跟我说说:[WhatsApp](https://wa.me/60127972969) · [me@hoelee.com](mailto:me@hoelee.com?subject=Browser%20automation%20debugging) · [hoelee.com](https://hoelee.com)。 -```` - ### 🇬🇧 英文版原文 (English Markdown Primary) ````markdown --- -title: "Why Your CDP Clicks Silently Fail: Smooth Scroll, Minimised Windows, and JS-Dispatched Events" -description: "Three reasons a Chrome DevTools Protocol click reports success and does nothing: a stale rect from smooth scrolling, a minimised window that drops coordinate input, and a page that received the click but rejected it." -pubDate: 2025-03-19 -updatedDate: 2026-09-29 -category: devops -tags: [cdp, chrome, react, browser-automation, debugging, python] -ogImage: /og/why-your-cdp-clicks-silently-fail.jpg -banner: /banners/why-your-cdp-clicks-silently-fail.jpg -draft: false ---- - -If you drive a web app with the Chrome DevTools Protocol, you have met this failure: your script reports `clicked @591,361`, the element is there, the click landed — and nothing happens. No exception, no console error, no change on the page. - -I spent an evening on exactly this while automating a marketplace's seller admin panel, and the three causes I found are worth writing down, because they are all invisible to the code that reports the click. - -## Cause 1: a stale rect, because the page scrolls smoothly - -The obvious click helper looks like this: - -```python -r = self.ev("""(()=>{const e=%s; e.scrollIntoView({block:'center'}); - const b=e.getBoundingClientRect(); - return JSON.stringify({x:b.left+b.width/2, y:b.top+b.height/2});})()""") -self.click_xy(json.loads(r)["x"], json.loads(r)["y"]) -``` - -Scroll into view, read the element's rectangle, click its centre. Correct — unless the page has `scroll-behavior: smooth` (very common in modern UI kits). Then `scrollIntoView()` starts an **animation**, and `getBoundingClientRect()` in the same tick returns the position the element is *about to leave*. Your click goes to where the element was, lands on whatever is there, and the log tells you it clicked the coordinates you asked for. - -The fix is two lines — turn smooth scrolling off, then re-read the rect: - -```python -self.ev("""(()=>{document.documentElement.style.scrollBehavior='auto'; - if(document.body) document.body.style.scrollBehavior='auto'; return 'ok';})()""") -moved = self.ev("""(()=>{const e=%s; if(!e) return 'no'; - e.scrollIntoView({block:'center', behavior:'instant'}); return 'ok';})()""" % sel) -time.sleep(0.35) # let layout settle -# then read the rect (and retry a couple of times if the element is not there yet) -``` - -Two details matter. `behavior:'instant'` on `scrollIntoView` overrides the CSS; and the small wait before reading is what makes the rect trustworthy. Without the retry loop the helper still fails intermittently on elements that render a frame late — intermittent failures are the worst kind, because they make you doubt your own diagnosis. - -## Cause 2: the window is minimised, and coordinate clicks are dropped - -After the fix, my click helper worked in a one-off probe and then never again inside the real script. Same selector, same coordinates, same page. The difference turned out to be visibility: - -``` -document.visibilityState → "hidden" -document.hasFocus() → true -``` - -CDP-synthesised mouse events at coordinates are unreliable when the target tab is not the active tab of a visible window — the browser may accept them, throttle them, or route them nowhere. Note that `hasFocus()` returns `true` even when the document is hidden, so it is not a useful check; `document.hidden`/`visibilityState` is. - -Two fixes, and I use both: - -```python -def activate(self): # bring the tab to the front of its window - self.cdp("Page.bringToFront") - time.sleep(0.2) - -def click_js(self, sel): # click by dispatching events from inside the page - return self.ev("""(()=>{const e=%s; if(!e) return 'no'; - ['mousedown','mouseup','click'].forEach(k=> - e.dispatchEvent(new MouseEvent(k,{bubbles:true,cancelable:true,view:window}))); - return 'js-clicked';})()""" % sel) -``` - -`Page.bringToFront` fixes the common case. But the JS-dispatched click is the one that never fails: it does not depend on the window being visible, and React's root-level event listener receives it exactly as it receives a real click, because the events bubble to the same root. A date-picker input that opened maybe one time in five with coordinate clicks opens **every** time this way. - -The trade-off to know: dispatching events skips hit-testing, so it will also “click” an element a user could not reach (covered, scrolled off, zero-opacity). That is a feature here — and a trap if you use it to paper over a layout bug — so I keep coordinate clicking for anything visual and reach for `click_js` when the widget is a custom control. - -## Cause 3: the page received the click and rejected it - -This is the one that wasted the most time, because the symptom is identical to causes 1 and 2: click fires, nothing changes. - -Distinguishing them takes one injected listener: - -```js -window.__ev = []; -['mousedown','mouseup','click'].forEach(k => - document.addEventListener(k, e => window.__ev.push(k + ':' + e.target.tagName), true)); -``` - -- Events recorded → the input path works. The problem is in the app (cause 3), or in how you read the result (see below). -- Nothing recorded → causes 1 or 2. - -With the listener armed I clicked `Confirm` and the buffer filled up — so the click was fine, and the app was saying no. The reason was in text I had not thought to look at: - -> “Please create a new shop welcome voucher after the existing one is expired.” - -The form refuses a second voucher of that type. No field-level red text, no toast in the first 500 ms, the URL unchanged. **The rejection was real and the click was innocent.** - -Two more tools for this class of bug: - -```js -document.elementFromPoint(x, y) // what is actually on top at that coordinate? -document.querySelectorAll('button').length // how many match your selector? -``` - -The second one caught a subtle one: the portal leaves a **hidden** `Confirm` button in the DOM from the collapsed date-panel, so `.pop()` returned the invisible duplicate and the click went nowhere visible. Filter by visibility *and* size: - -```python -"[...document.querySelectorAll('button')].filter(b=>/^Confirm$/.test(b.innerText.trim())" -" && b.offsetParent!==null && b.getBoundingClientRect().width>0).pop()" -``` - -## And the fourth failure I only found by re-reading - -There is a class of “failure” that is not one: **the write succeeded and your read is stale.** I concluded a create had been silently refused because the list page did not show it immediately, clicked again, and later discovered the voucher had existed the whole time — the list just lagged about ten minutes. The lesson generalises: after a write, the only trustworthy verdict is a read-back *after* a real waiting period, and “no visible change” means *unknown*, not *failed*. - -## The checklist - -1. Turn off smooth scrolling; scroll with `behavior:'instant'`; wait, then read the rect. -2. Call `Page.bringToFront` before clicking; treat `document.hidden` as the signal, not `hasFocus()`. -3. For custom widgets, dispatch `mousedown`/`mouseup`/`click` from JS rather than clicking coordinates. -4. Arm an event listener to prove whether input arrived before you blame the app. -5. Count your selectors — hidden duplicates are common in component libraries. -6. After a write, wait and re-read; never re-click a submit you have not verified. - -None of this is exotic, but every item is invisible in a log line that says `clicked @591,361`. If you are building automation against an admin panel you do not control, the click is the least reliable part of the pipeline — and the one most likely to be blamed last. - -I build and debug this kind of browser automation for a living — self-hosted services, Docker and Traefik stacks, and the odd scraped-but-bot-walled marketplace. If you have a workflow that keeps breaking because a UI has other ideas, tell me about it: [WhatsApp](https://wa.me/60127972969) · [me@hoelee.com](mailto:me@hoelee.com?subject=Browser%20automation%20debugging) · [hoelee.com](https://hoelee.com). -```` - ---- - -## 文章 02 / 11:Prometheus 明明有数据,Grafana 面板却全是 No data 的原因 -- **Slug**: `why-your-grafana-dashboard-shows-no-data` -- **英文标题**: Why Your Grafana Dashboard Shows No Data (When Prometheus Is Fine) -- **分类**: `devops` | **发布日期**: 2026-05-17 -- **线上地址**: https://blog.hoelee.com/posts/why-your-grafana-dashboard-shows-no-data/ (EN) | https://blog.hoelee.com/posts/zh/why-your-grafana-dashboard-shows-no-data/ (ZH) -- **本篇审核状态**: ⏳ 待审核 (Pending) - -### ✍️ 顾问审阅意见区 (Review Feedback) -```text -【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 -【事实与数字核对】: -【人设与用词卫生】: -【CRO与转化建议】: -``` - -### 🇨🇳 中文版原文 (Chinese Markdown Twin) -````markdown ---- -title: "Prometheus 明明有数据,Grafana 面板却全是 No data 的原因" -description: "所有 target 都是 up、数据就在 Prometheus 里、面板表达式也没错——41 个面板却全部 No data。原因是 Grafana 变量过滤了自己,而我的验证方式恰好掩盖了它。" -pubDate: 2026-05-17 -updatedDate: 2026-09-29 -category: devops -blueprint: self-hosted-infrastructure -blueprintLayer: L3-observability-self-healing -tags: [grafana, prometheus, dashboards, monitoring, promql, observability] -ogImage: /og/zh-why-your-grafana-dashboard-shows-no-data.jpg -banner: /banners/why-your-grafana-dashboard-shows-no-data.jpg -draft: false ---- - -打开每天在看的面板,结果是空的。不是\"某一格坏了\",而是**从上到下每一格**都写着 *No data*。去查 Prometheus,一切健康。这篇讲我踩到的那个具体且不直观的原因,以及为什么我自己的验证会同时告诉我\"面板没问题\"。 - -## 最省时间的排查顺序 - -常见原因(数据源选错、时间范围不对、`rate()` 用在会重置的计数器上、target 没被抓取)都不适用。真正有效的检查顺序是: - -```bash -# 1. target 真被抓取了吗? -curl -s http://prometheus:9090/api/v1/targets | jq '.data.activeTargets[] | {job:.labels.job, health}' - -# 2. 指标现在存在吗?(完全绕过 Grafana) -curl -s -G http://prometheus:9090/api/v1/query \ - --data-urlencode 'query=node_uname_info{job="unraid-host"}' | jq '.data.result[0].metric' - -# 3. 面板表达式本身对吗? -curl -s -G http://prometheus:9090/api/v1/query \ - --data-urlencode 'query=count(node_cpu_seconds_total{mode="idle",job="unraid-host"})' -``` - -三项都过了:7 个 target `up`、2.5 万条序列在采集、手动跑面板表达式也有数据。所以问题不在指标、不在抓取、也不在 PromQL——而在**它们之间的变量层**。 - -## 真正的原因:变量过滤了自己 - -面板上有一个主机选择器,两个变量串联:`$nodename`(哪台机器)和 `$node`(它的 `instance` 标签)。第一个的定义是: - -```promql -# BROKEN — 变量用自身的值来过滤自己 -label_values(node_uname_info{job="unraid-host", nodename=~"$nodename"}, nodename) -``` - -首次加载时 `$nodename` 还没有值,选择器就变成 `nodename=~""`——**什么都匹配不到**。查询返回零行的变量没有任何选项,于是它保持空;而 `$node` 又是基于 `$nodename` 定义的: - -```promql -label_values(node_uname_info{job="unraid-host", nodename="$nodename"}, instance) -``` - -于是 `$node` 也是空,所有以 `$node` 为过滤条件的面板自然匹配不到序列。Grafana 说 *No data* 并没有骗人:面板查询真的没有数据,因为给它限定范围的变量解析成了空。 - -修法是去掉自引用,并给每个变量存一个明确的默认值: - -```promql -# FIXED — 不自引用,每个变量只跳一层 -# $nodename -label_values(node_uname_info{job="unraid-host"}, nodename) -# $node -label_values(node_uname_info{job="unraid-host", nodename="$nodename"}, instance) -``` - -## 为什么我的验证没抓到 - -这才是值得抄的部分。我\"验证\"面板的方式是:**手动**把每个面板表达式里的变量替换成我知道正确的值(`$nodename=unRaid`、`$node=host.docker.internal:9100`),然后断言查询有数据点。13 项检查全部通过——面板依然是空的,因为 bug 在被替换的那个值**上游**:Grafana 自己对变量的解析是空的。 - -**一个替换掉\"可疑值\"的验证,永远发现不了那个值解析失败。** 要抓它,得读 Grafana 真实存下来的值: - -```bash -curl -s -u admin:"$PW" http://grafana:4010/api/dashboards/uid/rYdddlPWk \ - | jq '.dashboard.templating.list[] | {name, current: .current.value}' -``` - -更直接的检查对象是变量查询本身——跑 Grafana 会跑的那条: - -```bash -# $nodename 的 label_values() 到底返回什么? -curl -s -G http://prometheus:9090/api/v1/query \ - --data-urlencode 'query=count by (nodename) (node_uname_info{job="unraid-host"})' | jq '.data.result' -``` - -那里是空,面板就不可能渲染出来,无论数据多健康。 - -## 第二个坑:`$__all` 不是 `.*` - -做自动化面板检查时,值为\"All\"的变量,其 current 是哨兵字符串 `$__all`——不是正则。把 `name=~"$__all"` 原样展开会匹配不到任何东西,于是完全健康的容器面板\"全军覆没\"。展开前要把 `$__all` 解析成该变量的 `allValue`(通常是 `.*`),否则你追的是一个只存在于自己检查脚本里的 bug。 - -## 不是每个空面板都是 bug - -修完之后 25 个面板有 21 个出数。剩下 4 个是**设计上就不可能**有数据的,最好在面板说明里写清楚: - -- **PSI 面板**需要 `/proc/pressure`,而这台 NAS 的内核不暴露它——指标在这台机器上无法存在;同样的面板在会导出 `node_pressure_*` 的主机上正常显示。 -- **根文件系统面板**的表达式带 `fstype!="rootfs"`,而某台主机的 `/` 是**内存盘**(unRaid 就是),所以永远匹配不到。 - -区分\"因为 bug 空\"和\"因为这台机器不可能有这个指标而空\",是真修好和瞎忙一下午的分界线。 - -## 我下次会怎么做 - -- **永远不要定义过滤自己的模板变量。** 一个变量只跳一层。 -- **给面板依赖的变量存明确的 `current` 值**,别让全新加载依赖下拉框被选中。 -- **用 Grafana 存下来的值做验证**,而不是我以为的值。 -- **故意留空的缺口写进面板说明**,否则未来的你会花一个下午去\"修\"一个本来就没打算工作的面板。 - -## 结果 - -三台主机现在跑同一套布局——每台一个 41 面板的主机面板 + 一个 10 面板的容器面板,分别有 21/23/25 个面板出数,两类结构性空缺写在面板里,而不是留给下一个打开它的人去猜。 - -## 需要为你的业务做这个吗? - -如果你有一堆没人信任的 Grafana 面板,或者服务器和 NAS 完全没有监控,我可以帮你搭自托管的 Prometheus + Grafana(主机与容器指标、合理的告警规则、通知推到 Telegram 和邮件),也会把你那些悄悄\"不出数\"的面板修好。 - -**WhatsApp:[+60 12-797 2969](https://wa.me/60127972969)** · **邮箱:[me@hoelee.com](mailto:me@hoelee.com?subject=Grafana%20monitoring)** · **[hoelee.com](https://hoelee.com)** - -网站设计与开发是我的主业;服务器加固与自托管基础设施是它的另一半。 -```` - -### 🇬🇧 英文版原文 (English Markdown Primary) -````markdown ---- -title: "Why Your Grafana Dashboard Shows No Data (When Prometheus Is Fine)" -description: "Every target up, data in Prometheus, panel expressions correct — and all 41 panels reading No data. The culprit was a Grafana variable filtering on itself, plus the verification habit that hid it." -pubDate: 2026-05-17 -updatedDate: 2026-09-29 -category: devops -blueprint: self-hosted-infrastructure -blueprintLayer: L3-observability-self-healing -tags: [grafana, prometheus, dashboards, monitoring, promql, observability] -ogImage: /og/why-your-grafana-dashboard-shows-no-data.jpg -banner: /banners/why-your-grafana-dashboard-shows-no-data.jpg -draft: false ---- - -You open the dashboard you use every day and it's empty. Not "one panel broke" empty — -**every panel**, top to bottom, says *No data*. You check Prometheus and everything is -healthy. This post is the specific, non-obvious cause I hit, and the way my own -verification convinced me the dashboard was fine while it wasn't. - -## The searchable question - -*My Grafana panels show No data but the data is in Prometheus — why?* - -The usual answers (wrong datasource, wrong time range, `rate()` on a counter that -resets, missing scrape target) did not apply. Here is the checklist that narrowed it -down, in the order that costs the least time: - -```bash -# 1. is the target actually being scraped? -curl -s http://prometheus:9090/api/v1/targets | jq '.data.activeTargets[] | {job:.labels.job, health}' - -# 2. does the metric exist right now? (bypasses Grafana entirely) -curl -s -G http://prometheus:9090/api/v1/query \ - --data-urlencode 'query=node_uname_info{job="unraid-host"}' | jq '.data.result[0].metric' - -# 3. is the panel's expression sound? -curl -s -G http://prometheus:9090/api/v1/query \ - --data-urlencode 'query=count(node_cpu_seconds_total{mode="idle",job="unraid-host"})' -``` - -All three were green: 7 targets `up`, 25k series ingested, and the panel's raw -expression returned data when I ran it by hand. So the problem was not the metrics, -the scrape, or the PromQL — it was **the variable layer between them**. - -## The actual cause: a variable that filtered on itself - -The dashboard had a host picker. Two variables chained: `$nodename` (which machine) -and `$node` (its `instance` label). The definition of the first one was: - -```promql -# BROKEN — the variable filters on its own value -label_values(node_uname_info{job="unraid-host", nodename=~"$nodename"}, nodename) -``` - -On first load `$nodename` has no value, so the selector becomes -`nodename=~""` — which matches **nothing**. A variable whose query returns no rows has -no options, so it stays empty. `$node` is then defined against `$nodename`: - -```promql -label_values(node_uname_info{job="unraid-host", nodename="$nodename"}, instance) -``` - -…which is also empty, so every panel filtering on `$node` matches no series. Grafana -isn't lying when it says *No data*: the panel query genuinely has no data, because the -variable that scopes it resolved to nothing. - -The fix is to stop the self-reference and give each variable an explicit saved default: - -```promql -# FIXED — no self-reference, one hop per variable -# $nodename -label_values(node_uname_info{job="unraid-host"}, nodename) -# $node -label_values(node_uname_info{job="unraid-host", nodename="$nodename"}, instance) -``` - -Then save `current` values for both so the dashboard opens populated instead of -depending on a click. (This is also why the same 41-panel layout can be cloned to -three hosts and just work.) - -## Why my verification missed it - -This is the part worth stealing. I "verified" the dashboard by expanding each panel's -expression **by hand**, substituting the variable values I knew were correct -(`$nodename=unRaid`, `$node=host.docker.internal:9100`), and asserting the query -returned points. Thirteen of those checks passed. The dashboard was still blank, -because the bug was upstream of the substitution: Grafana's *own* resolution of the -variables was empty. - -**A verification that substitutes the very value under suspicion cannot detect that -value failing to resolve.** To catch it, read the values Grafana actually saved and -expand with those: - -```bash -curl -s -u admin:"$PW" http://grafana:4010/api/dashboards/uid/rYdddlPWk \ - | jq '.dashboard.templating.list[] | {name, current: .current.value}' -``` - -The correct check is on the variable query itself — run what Grafana runs: - -```bash -# what does $nodename's label_values() actually return? -curl -s -G http://prometheus:9090/api/v1/query \ - --data-urlencode 'query=count by (nodename) (node_uname_info{job="unraid-host"})' | jq '.data.result' -``` - -Empty there means the dashboard cannot possibly render, no matter how healthy the data is. - -## The second trap: `$__all` is not `.*` - -While automating panel checks, a variable set to *All* reports its current value as the -sentinel string `$__all` — not a regex. Expanding panel expressions naively turns -`name=~"$__all"` into a literal that matches nothing, so a perfectly healthy -container dashboard "fails" every panel. Resolve `$__all` to the variable's `allValue` -(usually `.*`) before expanding, or you'll chase a bug that only exists in your checker. - -## Not every empty panel is a bug - -After the fix, 21 of 25 panels had data. The remaining four were empty **by design** and -worth naming honestly in the panel description: - -- **PSI panels** (`Pressure`, `Pressure Stall Information`) need `/proc/pressure`, which - the NAS kernel doesn't expose. The metric cannot exist there — the same panels on a - host that *does* export `node_pressure_*` render fine. -- **Root filesystem panels** whose expression carries `fstype!="rootfs"` can never match - on a host whose `/` is a **ramdisk**, which is what unRaid's root is. - -Distinguishing "broken because of a bug" from "empty because the metric cannot exist on -this host" is the difference between a real fix and a wild goose chase. - -## What I'd do differently - -- **Never define a template variable that filters on itself.** One hop per variable. -- **Always save explicit `current` values** for variables a dashboard depends on, so a - fresh load doesn't rely on a populated dropdown. -- **Verify with Grafana's saved values, not my idea of them.** The masking is invisible - in the test result and obvious in the UI. -- **Describe intentional gaps in the panel description.** Future-you will otherwise - spend an afternoon "fixing" a panel that was never meant to work there. - -## The result - -All three hosts now run the same instrumented layout — a 41-panel host dashboard and a -10-panel container dashboard each — with 21/23/25 panels returning data respectively, -and the two structurally-empty classes documented in place instead of silently -confusing whoever opens them next. - -## Want this for your business? - -If you have Grafana dashboards that nobody trusts — or servers and a NAS with no -monitoring at all — I build self-hosted Prometheus + Grafana stacks (host and container -metrics, sensible alert rules, alerts to Telegram and email) and I'll fix the ones that -have quietly stopped showing data. - -**WhatsApp: [+60 12-797 2969](https://wa.me/60127972969)** · **Email: [me@hoelee.com](mailto:me@hoelee.com?subject=Grafana%20monitoring)** · **[hoelee.com](https://hoelee.com)** - -Website design and development is my main line of work; server hardening and -self-hosted infrastructure is the other half of it. -```` - ---- - -## 文章 03 / 11:你的“磁盘将满”告警在说谎:别再按百分比告警 -- **Slug**: `your-disk-full-alert-is-lying` -- **英文标题**: Your Disk-Full Alert Is Lying: Stop Alerting on Percentages -- **分类**: `devops` | **发布日期**: 2026-06-24 -- **线上地址**: https://blog.hoelee.com/posts/your-disk-full-alert-is-lying/ (EN) | https://blog.hoelee.com/posts/zh/your-disk-full-alert-is-lying/ (ZH) -- **本篇审核状态**: ⏳ 待审核 (Pending) - -### ✍️ 顾问审阅意见区 (Review Feedback) -```text -【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 -【事实与数字核对】: -【人设与用词卫生】: -【CRO与转化建议】: -``` - -### 🇨🇳 中文版原文 (Chinese Markdown Twin) -````markdown ---- -title: "你的“磁盘将满”告警在说谎:别再按百分比告警" -description: "\"剩余 3%\"听着像紧急事故,直到你发现那是 500 GB。在多 TB 的卷上,百分比阈值会在没事的时候乱叫,也会在真出事的时候沉默。" -pubDate: 2026-06-24 -updatedDate: 2026-09-29 -category: devops -blueprint: self-hosted-infrastructure -blueprintLayer: L3-observability-self-healing -tags: [monitoring, alerting, prometheus, grafana, storage, capacity, observability] -ogImage: /og/zh-your-disk-full-alert-is-lying.jpg -banner: /banners/your-disk-full-alert-is-lying.jpg -draft: false ---- - -我搭好监控、写了一套看着合理的规则,然后用一个下午删掉了其中大半阈值。它们全是百分比,而且都以同一种方式错了。 - -## 三个教我道理的告警 - -**1.「文件系统使用率超过 90%」**——它在一个还剩约 500 GB 的 17 TB 卷上触发。没事发生,也不会马上有事发生。这种体量的卷,一次大备份就能让百分比摆动几个点:比例是噪声,而\"还有 500 GB 可用\"才是世界的真实状态。 - -**2.「内存使用率超过 90%」**——在一台**可用**内存 4.8 GB 的主机上反复触发。Linux 会用空闲内存做 page cache,需要时立刻归还;`MemTotal - MemFree` 描述的是文件缓存,不是你的风险。真正预示 OOM 的是 `MemAvailable`。 - -**3.「CPU steal 超过 25%」**——一台把邮件栈跑得完全正常的 VPS,steal 长期在 41%。steal 说明宿主机忙,它是**容量**信号而不是**故障**信号;7 vCPU 的机器 41% steal 就是这台机器的成本。这条规则产生的告警永远为真、也永远无用。 - -共同点:**我在对比例告警,而比例不知道东西有多大。** - -## 对\"后果\"告警,而不是对比例 - -我现在对每个阈值都问一句:*如果这个状态持续下去,实际会发生什么?* 答案几乎总能用绝对单位表达。 - -| 不要这样 | 改成 | 原因 | -|---|---|---| -| 文件系统 > 90% | 剩余空间 < N GB | \"我还能不能写进去\"才是问题 | -| 内存使用 > 90% | `MemAvailable` < 512 MB | 逼近 OOM,而不是\"缓存很暖和\" | -| CPU steal > 25% | steal > 50% | 容量成本 vs 真的被饿死 | -| 负载 > N | `load1 / 核数 > 2` | 不谈核数的负载没有意义 | - -PromQL 的前后对比: - -```promql -# BEFORE — 17 TB 卷的百分比;还剩半 TB 就开叫 -(1 - node_filesystem_avail_bytes / node_filesystem_size_bytes) * 100 > 90 - -# AFTER — 真正装数据的卷上,还剩多少容量 -min by (instance, mountpoint) ( - node_filesystem_avail_bytes{mountpoint=~"/volume[0-9]+|/mnt/ssd|/mnt/disk[0-9]+"} -) < 25e9 -``` - -```promql -# BEFORE — 把 page cache 当成压力 -(1 - node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes) * 100 > 90 - -# AFTER — 真正的 OOM 前兆 -node_memory_MemAvailable_bytes < 512 * 1024 * 1024 -``` - -两个让规则能活下来的细节: - -**把比较放进阈值条件里,不要塞进表达式。** 查询就写 `min by (mountpoint) (node_filesystem_avail_bytes{...})`,让告警规则去和 `25000000000` 比。若你在 PromQL 里写死 `< 25e9`、规则里又留着继承来的 `> 90`,规则照样会评估——但界面显示的阈值是错的,下一个读它的人得从两个互相矛盾的条件下反推你的意图。 - -**排除那些\"只是另一个挂载点的视图\"。** 一条\"剩余空间\"规则有多诚实,取决于它的选择器。在我自己的环境里,同一个 NAS 卷出现三次(`/volume1`、`/opt`、以及在另一台主机上以 CIFS 再次挂载),而 unRaid 的 shfs 联合挂载报告 `avail=0`——不加排除的规则不是永远误报,就是把容量算成两倍。一个写明白的选择器胜过聪明的通用写法。 - -## 噪声不是无害的 - -坏阈值的代价不在告警本身,而在**训练**:每条\"没事乱叫\"的告警都在教你先扫一眼、然后忽略;等你真正该看的那条到来时,它出现在一个你早已不再读的频道里。我的规则总数**减少了**,覆盖率却上升了——更少,但每条都对应一个明确的后果。 - -## 阈值是私人的,形状是通用的 - -上面的数字是我的:NAS 卷剩不到 25 GB 我会在意、可用内存低于 512 MB 我才管、VPS steal 超过 50% 才算被饿。你的数字随硬件和容忍度而变。 - -能通用的是形状: - -- 用绝对单位而非比例; -- 把后果写进告警的摘要里; -- 选择器明确声明它在替哪些挂载点说话; -- 规则数量少到你还能读完每一条。 - -## 结果 - -同一套栈,从\"三条永久无用报警\"变成 16 条在机房健康时保持安静的规则——其中一条立刻暴露了一个只剩 21 GB 的 NAS 卷,而那正是百分比规则一直藏在\"99% 满的巨物\"背后、被你学会忽略的东西。 - -## 需要为你的业务做这个吗? - -如果你的监控在发你已经学会忽略的告警,或者你根本没有监控、宁愿从一条规则而不是从一次失败的备份里得知磁盘满了,我可以帮你搭自托管的监控与告警(Prometheus + Grafana,通知推 Telegram 和邮件),阈值按\"什么会真的坏\"来定。 - -**WhatsApp:[+60 12-797 2969](https://wa.me/60127972969)** · **邮箱:[me@hoelee.com](mailto:me@hoelee.com?subject=Monitoring%20and%20alerting)** · **[hoelee.com](https://hoelee.com)** - -网站设计与开发是我的主业;服务器加固与自托管基础设施是它的另一半。 -```` - -### 🇬🇧 英文版原文 (English Markdown Primary) -````markdown ---- -title: "Your Disk-Full Alert Is Lying: Stop Alerting on Percentages" -description: "3% free sounds like an emergency until you notice it is 500 GB. On multi-terabyte volumes, percentage thresholds fire when nothing is wrong — and miss when something is." -pubDate: 2026-06-24 -updatedDate: 2026-09-29 -category: devops -blueprint: self-hosted-infrastructure -blueprintLayer: L3-observability-self-healing -tags: [monitoring, alerting, prometheus, grafana, storage, capacity, observability] -ogImage: /og/your-disk-full-alert-is-lying.jpg -banner: /banners/your-disk-full-alert-is-lying.jpg -draft: false ---- - -I built a monitoring stack, wrote a reasonable set of rules, and then spent an -afternoon deleting most of my own thresholds. Every one of them was a percentage, and -every one of them was wrong in the same specific way. - -## The three alerts that taught me - -**1. "Filesystem above 90% used."** It fired on a 17 TB volume that had ~500 GB free. -Nothing was wrong. Nothing was *about* to be wrong. On a volume that size, a single -large backup can swing the percentage by several points — the ratio is noise, and the -fact that 500 GB is still available is the actual state of the world. - -**2. "Memory above 90% used."** Fired constantly on a host with 4.8 GB *available*. -Linux uses free RAM for page cache and gives it back on demand; `MemTotal - MemFree` -describes your filesystem cache, not your risk. The number that predicts an OOM is -`MemAvailable`. - -**3. "CPU steal above 25%."** Fired on a VPS that had been running its mail stack -perfectly at 41% steal. Steal means the hypervisor is busy — it is a *capacity* signal, -not a *failure* signal, and 41% steal on a 7-vCPU box was simply what that host costs. -The rule produced alerts that were always true and never actionable. - -The common thread: **I was alerting on a ratio, and the ratio doesn't know how big the -thing is.** - -## Alert on the consequence, not the ratio - -The test I now apply to every threshold: *if this condition persists, what will actually -happen?* That answer is almost always expressible in absolute units. - -| Instead of | Alert on | Because | -|---|---|---| -| Filesystem > 90% | Free space < N GB | "Can I still write?" is the question | -| Memory > 90% used | `MemAvailable` < 512 MB | about to OOM, not "cache is warm" | -| CPU steal > 25% | Steal > 50% | capacity cost vs. starvation | -| Load average > N | `load1 / cores > 2` | load is meaningless without core count | - -In PromQL, before and after: - -```promql -# BEFORE — percentage of a 17 TB pool; fires with half a terabyte still free -(1 - node_filesystem_avail_bytes / node_filesystem_size_bytes) * 100 > 90 - -# AFTER — capacity left, on the volumes that hold data -min by (instance, mountpoint) ( - node_filesystem_avail_bytes{mountpoint=~"/volume[0-9]+|/mnt/ssd|/mnt/disk[0-9]+"} -) < 25e9 -``` - -```promql -# BEFORE — page cache counted as "pressure" -(1 - node_memory_MemAvailable_bytes / node_memory_MemTotal_bytes) * 100 > 90 - -# AFTER — the actual OOM precursor -node_memory_MemAvailable_bytes < 512 * 1024 * 1024 -``` - -Two details that make these rules survive contact with a real dashboard: - -**Keep the comparison in the threshold condition, not inside the expression.** Query -`min by (mountpoint) (node_filesystem_avail_bytes{...})`, then let the alert rule -compare it to `25000000000`. If you bake `< 25e9` into the PromQL *and* leave an -inherited `> 90` in the rule, the rule still evaluates — but it displays a nonsense -threshold, and the next person to read it has to reconstruct your intent from two -contradictory conditions. - -**Exclude the mounts that are views of other mounts.** A "free space" rule is only as -honest as its selector. On my own setup, one NAS volume appears three times (as -`/volume1`, as `/opt`, and again on another host as a CIFS re-mount), and unRaid's shfs -union mount reports `avail=0` — a rule without exclusions would either fire forever or -double-count capacity. One explicit selector beats a clever generic one: - -```promql -node_filesystem_avail_bytes{mountpoint=~"/volume[0-9]+|/mnt/ssd|/mnt/disk[0-9]+"} -``` - -## Noise is not harmless - -The cost of a bad threshold isn't the alert itself — it's the *training*. Every alert -that fires while nothing is wrong teaches you to skim, then to ignore, and then the one -that matters arrives in a channel you've stopped reading. My rule count went **down** -while coverage went up: fewer, each tied to a named consequence. - -## Thresholds are personal, shapes are not - -The specific numbers above are mine — 25 GB free before a NAS volume bothers me, 512 MB -available before I care about memory, 50% steal before a VPS is being starved. Yours -will differ with your hardware and your tolerance. - -What transfers is the shape: - -- absolute units over ratios, -- the consequence written into the alert's summary, -- a selector that states exactly which mounts it speaks for, -- and a rule count small enough that you still read every message. - -## The result - -The same stack that was producing three permanent, uninformative warnings now runs 16 -rules that stay silent when the lab is healthy — and one of them immediately surfaced a -NAS volume sitting at 21 GB free, which is the kind of thing a percentage rule had been -hiding behind a 99%-full giant that I'd learned to ignore. - -## Want this for your business? - -If your monitoring sends you alerts you've learned to ignore, or you have none and would -rather find out about a full disk from a rule than from a failed backup, I set up -self-hosted monitoring and alerting (Prometheus + Grafana, alerts to Telegram and email) -with thresholds tied to what actually breaks. - -**WhatsApp: [+60 12-797 2969](https://wa.me/60127972969)** · **Email: [me@hoelee.com](mailto:me@hoelee.com?subject=Monitoring%20and%20alerting)** · **[hoelee.com](https://hoelee.com)** - -Website design and development is my main line of work; server hardening and -self-hosted infrastructure is the other half of it. -```` - ---- - -## 文章 04 / 11:浏览器翻译没有 API:我给一个纯中文网页应用加上了英文模式 -- **Slug**: `adding-english-mode-to-a-chinese-only-web-app` -- **英文标题**: No API for Browser Translation: Adding an English Mode to a Chinese-Only Web App -- **分类**: `engineering` | **发布日期**: 2025-06-11 -- **线上地址**: https://blog.hoelee.com/posts/adding-english-mode-to-a-chinese-only-web-app/ (EN) | https://blog.hoelee.com/posts/zh/adding-english-mode-to-a-chinese-only-web-app/ (ZH) -- **本篇审核状态**: ⏳ 待审核 (Pending) - -### ✍️ 顾问审阅意见区 (Review Feedback) -```text -【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 -【事实与数字核对】: -【人设与用词卫生】: -【CRO与转化建议】: -``` - -### 🇨🇳 中文版原文 (Chinese Markdown Twin) -````markdown ---- -title: "浏览器翻译没有 API:我给一个纯中文网页应用加上了英文模式" -description: "浏览器不提供触发翻译的 JavaScript API,而我的应用明明是中文却声明自己是英文。于是我改用反向代理,把一个英文模式注入进去。" -pubDate: 2025-06-11 -updatedDate: 2026-09-29 -category: engineering -blueprint: sme-digital-suite -blueprintLayer: L1-high-conversion-web -tags: ["i18n", "nginx", "vue", "javascript", "self-hosting"] -ogImage: "/og/zh-adding-english-mode-to-a-chinese-only-web-app.jpg" -banner: "/banners/adding-english-mode-to-a-chinese-only-web-app.jpg" -draft: false ---- - -「能不能用 JavaScript 触发浏览器自带的翻译?」答案是**不能**。接受这一点花了我一个下午 —— 但更有意思的发现出现在前面:我的应用其实一直在破坏浏览器的翻译功能,而且只用一个属性就做到了。 - -## 我在做什么 - -我维护着一个私人的邀请制阅读平台 `book.hoelee.com`:自建的阅读器(Kotlin/Spring 后端 + Vue 单页应用),装着我自己的藏书,并给受邀读者开了账号。界面是纯中文 —— 不是「以中文为主」,而是**只有中文**。我在相信这一点之前把每个前端 bundle 都翻了一遍:没有 i18n 库、没有语言包、没有语言切换,只有一个简繁转换表和一堆英文 TTS 语音名。 - -后来我开始把邀请卡发给只说英文的读者。他们能注册,然后迎面撞上:书架、浏览书仓、确定、设置 —— 每一个控件都在他们读不懂的语言里。这不是「体验不够精致」的问题。对我邀请的一半人来说,这个产品是不可用的。 - -有一条约束决定了后面所有做法:**我不改这个应用。** 它的上游仓库已经归档,界面是压缩过的 Vue bundle —— 任何我打进镜像里的补丁,都会在下一次换镜像时消失。所以我做的东西必须待在**外面一层**:我已经架在应用前面的那个 nginx 网关。 - -## 发现一:应用声明了自己错误的语言,而这会关掉翻译 - -写代码之前,我先看看浏览器到底看到了什么: - -```bash -$ curl -s https://book.hoelee.com/index.html | grep -o ']*>' - -``` - -外壳声明英文,界面 100% 中文。 - -这件事比看上去严重。Chrome、Edge、Safari 决定「要不要**主动提示**翻译」,很大程度取决于页面声明的语言。一个声明自己是英文、却渲染中文内容的页面,不会得到那个「要翻译此页面吗?」的提示 —— 对我的新读者来说最有用的一项无障碍功能,就这么被悄悄关掉了;而「右键 → 翻译成中文/英文」是大多数人从来不知道的操作。 - -修复只要一行,而且是作用在**响应出站时**,不是打进应用里: - -```nginx -location = /index.html { - # sub_filter 不能改写 gzip 后的内容 -> 让上游返回未压缩的 HTML - proxy_set_header Accept-Encoding ""; - sub_filter_once on; - # 应用声明 lang="en" 而界面是中文 -> 浏览器因此永远不提示中译英。 - # 说出事实。 - sub_filter '' ''; - proxy_pass http://hectorqin-reader:8080; -} -``` - -用发现它的方式验证:`curl -s https://book.hoelee.com/index.html | grep -o '' ''; - proxy_pass http://hectorqin-reader:8080; -} -``` - -整个部署就是这样:一个 40 KB 的脚本,只在 `/index.html` 加载,所以按钮只存在于应用内,别处都没有。脚本做三件事。 - -### 1. 从应用自己的 bundle 里「收割」词汇表 - -界面文案本来就在压缩后的 JavaScript 里,以字符串字面量的形式存在。把所有含中日韩字符的字符串抓出来并计数: - -```python -import re, collections -CJK = re.compile(r'[\u4e00-\u9fff]') -count = collections.Counter() -for bundle in bundles: - for m in re.finditer(r'"([^"\\\n]{2,40})"', bundle): - if CJK.search(m.group(1)): - count[m.group(1)] += 1 -print(len(count)) # 840 条唯一字符串,按出现频率排序 -``` - -跑出 840 条唯一字符串:菜单(书架、书源管理)、确认框(确认要删除所选择的书籍吗?)、设置项(段落行距)、错误信息(本地书籍源文件不存在)。词典最终是 **871 条** —— 收割来的,加上我在英文模式下实际使用应用、看还有什么没翻而补上的。 - -### 2. 按 DOM 的真实样子匹配,而不是你希望的样子 - -朴素的子串替换会毁掉中文词组:书架 就藏在 加入书架 里面,单字更糟(页 藏在 页面 里)。三条规则解决了它: - -- **先做整标签匹配,基于去掉空白后的文本。** 应用里的标签是 `" 书架 "` 这种带空格的,所以词典里的 `设置` 必须能匹配 DOM 里的 `" 设置 "`。 -- **然后是最长优先的子串替换**,只允许长度 ≥ 2 的键参与。 -- **单字键只做整标签匹配**(章、页、条),这样它们永远不可能破坏更长的词。 - -```js -function tr(s) { - if (!s || !CJK.test(s)) return s; - var hit = EXACT[s.replace(/[\s\u3000]/g, '')]; // 整标签匹配,空白归一化 - if (hit) return keepWS(s, hit); - var t = s; - for (var i = 0; i < KEYS.length; i++) { // KEYS:最长优先,长度 >= 2 - if (t.indexOf(KEYS[i]) >= 0) t = t.split(KEYS[i]).join(DICT[KEYS[i]]); - } - // 收拾数量短语:共58个可用书源 -> "58 usable sources" - return t.replace(/共\s*(\d+)/g, '$1').replace(/(\d+)\s*个/g, '$1').replace(/(\d)([A-Za-z])/g, '$1 $2'); -} -``` - -### 3. 跟上框架的重绘 - -它是 Vue 应用,DOM 一直在被重写 —— 只跑一次的翻译,一秒后就有一半是错的。一个带 150 ms 防抖的 `MutationObserver`,在任何变化之后重跑一遍遍历。 - -这一遍是幂等的:标签一旦变成英文就不再含中日韩字符,于是不会被再写一次,也不会形成写入循环。文本节点之外,`placeholder`、`title`、`aria-label`、`alt` 和输入框的 `value` 也会翻译 —— 所以提示气泡和搜索框也一起变英文了。 - -UI 是右下角的一个小胶囊:关闭时显示 `EN`,开启后显示 `中文`,选择记在 `localStorage`,还提供「隐藏此按钮」给更愿意用自己翻译器的读者。 - -## 它**刻意**不翻译什么 - -**书籍正文。** 阅读器把 EPUB 内容渲染在 iframe 里,我的遍历器按设计跳过 iframe —— 而且我无论如何也不会去机器替换一本小说的正文。 - -同样保持原样的还有:书名与作者、书源名称、我自己建的分组名(梯子、精品、正版),以及应用那句诗。这些是**数据**,不是界面。翻译界面是一种体贴;悄悄改写用户自己的内容是另一回事,而且糟糕得多。 - -书籍正文仍然交给浏览器自带的翻译 —— 而且因为「发现一」,它现在真的会被提示出来。按钮的弹窗里就是这么写的。 - -## 要量,不要用眼睛看 - -「截图看起来基本是英文了」不算结果。我在开关按钮的前后,数了实时 DOM 里含中日韩字符的文本节点: - -```js -let cjk = 0, total = 0; // 遍历器跳过注入的 UI 与 script/style -while ((n = walker.nextNode())) { - const t = n.nodeValue.trim(); - if (!t) continue; - total++; - if (/[\u4e00-\u9fff]/.test(t)) cjk++; -} -``` - -| 界面 | 之前 | 之后 | 已翻译 | -|---|---|---|---| -| 登录 / 注册对话框 | 80 | 12 | 85% | -| 书架 + 设置 | 259 | 60 | 77% | -| 阅读页界面 | 214 | 31 | 88% | - -那些界面里仍被计为中文的,全部是数据 —— 书名、作者、书源名、我自己的分组名、那句诗 —— 正是应该保持中文的部分。 - -## 我会怎么做得不一样 - -**不要用手工重写一份 871 条的词典。** 我重构过一次,静默丢了 25 个键。症状看起来像逻辑 bug:设置 还是中文,而它的每个兄弟标签都翻译正常。匹配器没问题 —— 是**条目**不见了。在你相信一次重写之前,用程序对比键集合: - -```bash -python -c "print(sorted(set(old_keys) - set(new_keys)))" -``` - -**自动化 UI 检查要写短。** 我的无头运行器每次调用硬超时 60 秒。一个遍历六本书的循环返回 HTTP 408 和空 body,而我的 JSON 解析器报的是「解析错误」而不是「超时」—— 我一度在查错的东西。 - -**调试之前先搞清楚 SPA 的真实路由。** `#/reader/1` 会渲染出一个空白外壳,让人以为应用坏了;真正的路由是 `#/reader?bookUrl=`。 - -**注意你自己的跳转逻辑。** 我的网关会把任何刷新送回前台页,除非设置了 `sessionStorage` 的通行标记。把界面切**回**中文会重载页面 —— 所以按钮会先设好同一个标记,否则读者会因为改了个语言设置被踢出应用。 - -## 结果 - -一个只懂英文的读者,现在打开平台、点一下按钮,就能用英文读界面。应用本身没有被改动:整个功能只是一个由 sidecar nginx 容器提供的 40 KB 脚本,所以下一次换镜像不可能弄坏它;而浏览器自带的翻译,终于有一个会声明自己真实语言的页面可以配合。 - -我留下的经验:**当平台不给你 API 时,往外看一层。** 反向代理是添加「应用里加不了的行为」的正当位置 —— 而且通常是唯一能在升级中存活的位置。 - ---- - -*我为马来西亚的中小企业搭建并自托管这类平台 —— 网页应用、私人书库、内部工具。有需要可以找我:[WhatsApp +60 12-797 2969](https://wa.me/60127972969)、[me@hoelee.com](mailto:me@hoelee.com?subject=Self-hosted%20platform),或 [hoelee.com](https://www.hoelee.com)。* -```` - -### 🇬🇧 英文版原文 (English Markdown Primary) -````markdown ---- -title: "No API for Browser Translation: Adding an English Mode to a Chinese-Only Web App" -description: "Browsers expose no JavaScript API to trigger translation — and my app declared English while being Chinese. How I injected an English mode at the reverse proxy." -pubDate: 2025-06-11 -updatedDate: 2026-09-29 -category: engineering -blueprint: sme-digital-suite -blueprintLayer: L1-high-conversion-web -tags: ["i18n", "nginx", "vue", "javascript", "self-hosting"] -ogImage: "/og/adding-english-mode-to-a-chinese-only-web-app.jpg" -banner: "/banners/adding-english-mode-to-a-chinese-only-web-app.jpg" -draft: false ---- - -Can I trigger the browser's translate feature from JavaScript? No. That answer cost me an afternoon to accept — but the more interesting discovery came first: my app was already sabotaging the browser's translation, and it did it with a single attribute. - -## What I was working on - -I run a private, invite-only reading platform at `book.hoelee.com`: a self-hosted reader (Kotlin/Spring backend, Vue single-page app) holding my library, with accounts for invited readers. The interface is Chinese-only. Not "Chinese-first" — *only*. I grepped every served bundle before believing it: no i18n library, no locale files, no language switcher. Just a Simplified/Traditional character converter and a list of English TTS voice names. - -Then I started handing out invite cards to English-speaking readers. They could register, and then they met 书架, 浏览书仓, 确定, 设置 — every control in a language they don't read. That isn't a polish problem. For half the people I invited, the product was unusable. - -One constraint shaped everything that follows: **I don't modify the app.** Its upstream repository is archived and the UI is a minified Vue bundle, so anything I patch inside the image dies the next time I swap the image. Whatever I build has to live one layer out — in the nginx gateway I already run in front of the app. - -## Finding 1: the app declares the wrong language, and that disables translation - -Before writing a single line of code, I looked at what the browser sees: - -```bash -$ curl -s https://book.hoelee.com/index.html | grep -o ']*>' - -``` - -The shell says English. The interface is 100% Chinese. - -That matters more than it looks. Chrome, Edge and Safari decide whether to *offer* translation largely from the page's declared language. A page that declares English while rendering Chinese text doesn't get the "Translate this page?" prompt — the single most useful accessibility feature for my new readers was silently switched off, and right-click → *Translate to English* is a ritual most people never learn. - -The fix is one line, applied to the response on the way out instead of inside the app: - -```nginx -location = /index.html { - # sub_filter cannot rewrite a gzipped body -> ask upstream for plain HTML - proxy_set_header Accept-Encoding ""; - sub_filter_once on; - # the app declares lang="en" while its UI is Chinese -> browsers then never - # offer Chinese -> English translation. Declare the truth. - sub_filter '' ''; - proxy_pass http://hectorqin-reader:8080; -} -``` - -Verify the same way you found it: `curl -s https://book.hoelee.com/index.html | grep -o '' ''; - proxy_pass http://hectorqin-reader:8080; -} -``` - -That's the whole deployment: a 40 KB script, loaded only on `/index.html`, so the button exists inside the app and nowhere else. The script does three things. - -### 1. Harvest the vocabulary from the app's own bundles - -The UI strings are already in the minified JavaScript as quoted literals. Extract every one that contains a CJK character and count them: - -```python -import re, collections -CJK = re.compile(r'[\u4e00-\u9fff]') -count = collections.Counter() -for bundle in bundles: - for m in re.finditer(r'"([^"\\\n]{2,40})"', bundle): - if CJK.search(m.group(1)): - count[m.group(1)] += 1 -print(len(count)) # 840 unique strings, most frequent first -``` - -840 unique strings came out: menus (书架, 书源管理), confirmations (确认要删除所选择的书籍吗?), settings labels (段落行距), error messages (本地书籍源文件不存在). The dictionary ended up at **871 entries** — the harvest plus everything I found by running the app in English mode and watching what stayed Chinese. - -### 2. Match like the DOM actually is, not like you wish it were - -Naive substring replacement mangles Chinese compounds: 书架 sits inside 加入书架, and single characters are worse (页 inside 页面). Three rules fixed it: - -- **Whole-label match first, on whitespace-stripped text.** The app stores labels like `" 书架 "` with padding, so a dictionary key of `设置` has to match `" 设置 "` in the DOM. -- **Then longest-first substring replacement**, restricted to keys of two or more characters. -- **One-character keys are whole-label only** (章, 页, 条), so they can never corrupt a longer word. - -```js -function tr(s) { - if (!s || !CJK.test(s)) return s; - var hit = EXACT[s.replace(/[\s\u3000]/g, '')]; // whole label, whitespace-normalised - if (hit) return keepWS(s, hit); - var t = s; - for (var i = 0; i < KEYS.length; i++) { // KEYS: longest-first, length >= 2 - if (t.indexOf(KEYS[i]) >= 0) t = t.split(KEYS[i]).join(DICT[KEYS[i]]); - } - // tidy count phrases: 共58个可用书源 -> "58 usable sources" - return t.replace(/共\s*(\d+)/g, '$1').replace(/(\d+)\s*个/g, '$1').replace(/(\d)([A-Za-z])/g, '$1 $2'); -} -``` - -### 3. Keep up with the framework - -It's a Vue app, so the DOM is rewritten constantly — a translation pass that runs once is a translation pass that's half wrong a second later. A `MutationObserver` with a 150 ms debounce re-runs the walk after any change. - -The pass is idempotent: once a label is English it contains no CJK, so nothing is rewritten and there is no write loop. Text nodes plus `placeholder`, `title`, `aria-label`, `alt` and input `value` attributes all get translated, which is why tooltips and the search box come along too. - -The UI is a small pill in the bottom-right corner: `EN` when off, `中文` when on, remembered in `localStorage`, with a "Hide this button" link for readers who prefer their own translator. - -## What it deliberately does not translate - -**Book text.** The reader renders EPUB content inside an iframe; my walker skips iframes by design, and I would never machine-swap a novel's prose anyway. - -Also left alone: book titles and authors, book-source names, and the group names I created myself (梯子, 精品, 正版), plus the app's poem tagline. Those are *data*, not interface. Translating the chrome is a courtesy; silently rewriting a user's own content is a different and much worse idea. - -For book text the browser's own translation is still the right tool — and it now actually gets offered, thanks to Finding 1. The button's popup says exactly that. - -## Measure it, don't eyeball it - -"Screenshots look mostly English" is not a result. I counted CJK-containing text nodes in the live DOM before and after toggling the button: - -```js -let cjk = 0, total = 0; // walker skips the injected UI + script/style -while ((n = walker.nextNode())) { - const t = n.nodeValue.trim(); - if (!t) continue; - total++; - if (/[\u4e00-\u9fff]/.test(t)) cjk++; -} -``` - -| Screen | Before | After | Translated | -|---|---|---|---| -| Login / register dialog | 80 | 12 | 85% | -| Bookshelf + settings | 259 | 60 | 77% | -| Reading page chrome | 214 | 31 | 88% | - -Everything still counted as Chinese on those screens is data — titles, authors, source names, my own group names, the tagline — which is exactly what should stay Chinese. - -## What I'd do differently - -**Don't rewrite an 871-entry dictionary by hand.** I restructured mine once and silently dropped 25 keys. The symptom looked like a logic bug: 设置 stayed Chinese while every sibling label translated correctly. The matcher was fine — the *entry* was gone. Diff the key sets programmatically before you trust a rewrite: - -```bash -python -c "print(sorted(set(old_keys) - set(new_keys)))" -``` - -**Keep automated UI checks short.** My headless runner hard-times-out at 60 seconds per call. A six-book loop came back HTTP 408 with an empty body, and my JSON parser reported a parse error rather than a timeout — I debugged the wrong thing for a while. - -**Learn the SPA's real routes before debugging it.** `#/reader/1` renders a blank shell and makes you think the app is broken; the actual route is `#/reader?bookUrl=`. - -**Mind your own bounce logic.** My gateway sends any reload back to the front page unless a `sessionStorage` pass flag is set. Switching the interface *back* to Chinese reloads the page — so the button sets that same flag first, or the reader gets thrown out of the app for changing a language setting. - -## Result - -An English-only reader now opens the platform, taps one button, and reads the interface in English. The app itself is untouched: the whole feature is a 40 KB script served by a sidecar nginx container, so the next image update cannot break it, and the browser's own translation has a page that declares its real language to work with. - -The lesson I'm keeping: **when the platform won't give you an API, look one layer out.** A reverse proxy is a legitimate place to add behaviour you can't add in the app — and it's usually the only place that survives upgrades. - ---- - -*I build and self-host platforms like this one — web apps, private libraries, internal tools for small businesses in Malaysia. If you need something similar: [WhatsApp +60 12-797 2969](https://wa.me/60127972969), [me@hoelee.com](mailto:me@hoelee.com?subject=Self-hosted%20platform), or [hoelee.com](https://www.hoelee.com).* -```` - ---- - -## 文章 05 / 11:排查 Remotion 视频抽搐:为什么在背景图挂载音频低频 Scale 会毁了转场 -- **Slug**: `debugging-remotion-video-jitter` -- **英文标题**: Debugging Remotion Video Jitter: Why Bass Scaling Ruins Background Transitions -- **分类**: `engineering` | **发布日期**: 2025-11-26 -- **线上地址**: https://blog.hoelee.com/posts/debugging-remotion-video-jitter/ (EN) | https://blog.hoelee.com/posts/zh/debugging-remotion-video-jitter/ (ZH) -- **本篇审核状态**: ⏳ 待审核 (Pending) - -### ✍️ 顾问审阅意见区 (Review Feedback) -```text -【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 -【事实与数字核对】: -【人设与用词卫生】: -【CRO与转化建议】: -``` - -### 🇨🇳 中文版原文 (Chinese Markdown Twin) -````markdown ---- -title: "排查 Remotion 视频抽搐:为什么在背景图挂载音频低频 Scale 会毁了转场" -description: "深入排查 Remotion 音频可视化中背景画面剧烈抽搐与切镜暗闪的根本原因:解耦 HUD 与背景图层,以及纯净单向叠化与硬件基准实测对比。" -pubDate: 2025-11-26 -updatedDate: 2026-10-22 -category: engineering +title: "Generating Full-Length Songs with YuE2 BF16: Overcoming Duration Limits and Audio Truncation" +description: "AI music tools cut off complex tracks mid-sentence. Here is how I solved the 240s duration wall using YuE2 BF16, 295s headroom budgeting, and a 60-song pipeline." +pubDate: 2026-10-26 +category: tutorials +blueprint: ai-agent-automation +blueprintLayer: L4-aigc-media-pipelines stream: creative-lab -tags: ["remotion", "react", "audio-visualizer", "css-animation", "debugging"] -ogImage: "/og/zh-debugging-remotion-video-jitter.jpg" -banner: "/banners/debugging-remotion-video-jitter.jpg" +tags: ["ai-music", "yue2", "comfyui", "audio-engineering", "subtitles", "python"] +ogImage: "/og/generating-full-length-songs-with-yue2-comfyui.jpg" +banner: "/banners/generating-full-length-songs-with-yue2-comfyui.jpg" draft: false --- -使用 React 和 Remotion 编写自动化视频赋予了开发者对每一帧画面的极致掌控。你可以直接将 Web Audio 的频域分析数据映射到 SVG 属性、CSS 变换矩阵以及排版样式上,这种灵活性是传统非线性剪辑软件很难比拟的。 +Every generative music engine I have benchmarked suffers from the same fatal flaw: +**the sudden, unceremonious cutoff**. -然而,将视频帧当作常规网页来渲染时,极易踩入微妙的视觉陷阱。在我们的自动化音乐视频生成管线中,一个在开发组件预览时看似完全正常的设计,在全量导出为 1080P 30fps 视频后,却出现了极其刺眼、让人目眩的“地震式剧烈抽搐”。 +Whether you use cloud APIs or local weights, models trained on fixed acoustic token +windows struggle the moment you give them a complete, narrative song structure. A +9-part progression—`[Intro] -> [Verse 1] -> [Chorus] -> [Interlude] -> [Verse 2] -> [Chorus] -> [Bridge] -> [Chorus] -> [Outro]`—inevitably +collides with the hard ceiling of the generation buffer. The vocalist is mid-word in +the climax, and the audio abruptly flatlines into digital silence. -本文记录这次视觉 BUG 的深度排查过程:为什么对音频动效的朴素直觉会毁了整部视频,以及如何重构 React 视频图层架构以实现丝滑稳定的影视级转场。 +After iterating across hundreds of takes on an RTX 3060 12GB rig, I built an end-to-end +pipeline that generates genuine 4-minute full-length songs with natural melodic resolution +and zero mid-phrase amputations. -> **线上成品验证**:修复后的渲染流水线已正式交付并发布至 YouTube:[《糖画小仙》1080p 官方 MV](https://youtu.be/vZbyKeCCSRA),全片背景稳固、转场平滑。 - -> **TL;DR** —— 让整幅背景图跟着低频段缩放,等于每一帧都重新做图像插值采样,肉眼读到的就是剧烈抖动与震颤;再加上两层半透明图层对称交叉淡化,在时间中点必然透出底层的黑色容器。修复方案:背景画面绝对静态,将所有音频动效彻底隔离在顶层 HUD 频谱层,转场采用「100% 实体底图 + 顶层单向淡入」。渲染耗时实测**缩短 38.0%(从 352 秒降至 218 秒,吞吐速度提升 1.61 倍)**。这一篇是 [全自动 MV 生成流水线](/posts/zh/how-i-built-an-automated-music-video-pipeline/) 的渲染篇;文件落盘与发布那一半见 [Docker 容器大文件上传](/posts/zh/uploading-large-videos-to-youtube-via-cdp/)。 +Below is the breakdown of why standard generation fails, the 295-second headroom formula +that fixes it, and the full collection of **60 completed full-length songs** (with +individual 1024×1024 cover art and synchronized scrolling lyrics). --- -## 1. 故障现象:全画面的“高频地震” + -该视频合成组件最初的视觉设想非常清晰: -1. 底层是一组 1080P 高清插画分镜,在不同章节间慢速淡入淡出(Crossfade); -2. 画面上方浮动一个跟随音乐重音律动的环形音频频谱仪; -3. 三行书法歌词居中显示在音频环内,并根据每张插画的主体位置在画面左右两侧平滑滑移避让。 - -在开发工具里单帧点按检查时,画面一切正常。但在以 30fps 正常播放渲染出的成片时,肉眼观感极度难受:每当强烈的电子重音鼓点响起,整张背景图每秒剧烈颤抖震荡数十次;不仅如此,在两张图片交替切镜的 1.8 秒窗口内,画面中央还会突然闪现明显的“暗黑闪烁”,亮度瞬间下沉。 - ---- - -## 2. 根因分析一:低频 Scale 能量污染背景图 - -翻阅最初的 `BackgroundSlideshow.tsx` 组件,我们发现了一段看似合情合理的动效代码: - -```tsx -// 埋下灾难的罪魁祸首代码 -const bassScale = interpolate(bassLevel, [0, 1], [1.0, 1.025], { - extrapolateRight: 'clamp', -}); - -// 应用在全屏背景图片上: - -``` - -在直觉中,重低音响起时让背景图随着节奏轻微放大 2.5%,听起来像是在模拟动感的镜头呼吸感。然而在真实物理渲染中: -- **电音鼓点的瞬态脉冲只有 30~60 毫秒**:低频能量在连续 2 到 3 帧之内瞬间从零冲上顶峰,又在下一帧骤跌回原点; -- **1920x1080 的巨幅背景图放大 2.5%,边缘物理像素瞬间位移多达 25 到 30 像素**; -- 这种在相邻帧之间急剧拉扯的剧烈像素位移,人眼接收到的根本不是“音乐律动”,而是被视网膜本能判定为**强烈的镜头颠簸、抽动与丢帧残影**; -- 更致命的是,在 1.8 秒的交叉淡入淡出期间,两张重叠的图片各自具有不同的锚点和缩放系数,两层图像以不同的相位同时高频抖动,产生了极其混乱的重影眩晕感。 - ---- - -## 3. 根因分析二:对称线性透明度重叠时的“黑闪”陷阱 - -第二个问题是切镜时的亮度下陷黑闪。在传统 Web CSS 中,人们通常很自然地写出: - -```css -/* 常见的渐变叠化陷阱 */ -.current-slide { opacity: 1 -> 0; } -.next-slide { opacity: 0 -> 1; } -``` - -当两张图片都以线性渐变进行透明度变换时,在正中间那颗时间点($t = 0.5$): -- 当前图片透明度 = 0.5 -- 下一张图片透明度 = 0.5 - -来看浏览器和 Remotion 的合成器是如何将这几层叠在底层的纯黑容器之上的: - -``` -┌─────────────────────────────────────────────────────────────┐ -│ Layer 2: 下一张图片(Next Slide,透明度 = 0.5) │ -├─────────────────────────────────────────────────────────────┤ -│ Layer 1: 当前图片(Current Slide,透明度 = 0.5) │ -├─────────────────────────────────────────────────────────────┤ -│ Layer 0: 根容器底色(Root Container,背景色 = #000000 纯黑) │ -└─────────────────────────────────────────────────────────────┘ -``` - -由于多层半透明通道是依次向下进行乘法 Alpha 混合: -$$\text{有效综合不透明度} = 1 - (1 - 0.5) \times (1 - 0.5) = 1 - 0.25 = 0.75$$ - -合成后的总有效透明度只有 **0.75**,这意味着多达 **25% 的底层纯黑背景**被暴露了出来!这不是错觉,而是纯粹的数学光度衰减。每一次转场切镜,画面整体照度都会凭空跌掉四分之一,造成非常明显的瞬间暗淡闪烁。 - ---- - -## 4. 重构方案:稳固基座 + 纯净单向叠化 - -找到症结后,我们对组件进行了彻底重构: - -### 1. 彻底剥离背景图层的所有音频缩放 -背景插画必须稳如磐石。所有的音频跳动、瞬态光斑与能量爆发,**只能且必须限定在顶层的 HUD 频谱仪中**。背景层坚决不承载任何高频振荡属性。 - -### 2. 底层 100% 实体 + 顶层单向平滑淡入 -坚决不要让底图淡出。**当前图片始终保持 100% 不透明**,下一张图片直接覆盖在其上方,慢速执行 `0 -> 1.0` 的单向淡入: - -```tsx -return ( -
- {/* 1. 底层图片:坚固不透明,彻底消除暗黑闪烁 */} - - - {/* 2. 顶层图片:在 1.8 秒内平滑淡入 (0 -> 1.0) */} - {isTransitioning && ( - - )} +
+ -); -``` - -### 3. HUD 与背景物理层级绝对隔离 -歌词弹幕与音频环容器设置在独立的顶层图层中,并赋予 `pointerEvents: 'none'`。歌词在留白侧之间的横向位移完全根据当前时间戳自主计算,与底层的图片渐变完全物理隔离,互不干涉。 - ---- - -## 5. 改造后的成效与基准复现 - -重构落地后,对比极其显著: - -1. **彻底消除画面抖动**:无论音乐鼓点多么狂暴密集,背景画面在所有测试分镜中纹丝不动,人物与细节清晰稳定; -2. **转场不再发生黑闪**:1.8 秒的单向贝塞尔叠化始终保持 100% 连续亮度,杜绝了中间态透出底层黑色的缺陷; -3. **渲染吞吐速度大幅提升**:移除了对超大尺寸背景图的高频矩阵重算后,渲染性能获得了实测提升。 - -### 基准实测与硬件复现条件 - -| 评估指标 | 优化前版本 | 优化后版本 | 变化幅度与提升 | -|---|---|---|---| -| **渲染总耗时** | 352.0 秒 | 218.3 秒 | **耗时减少 38.0% (-133.7s)** | -| **平均渲染帧率** | 22.24 fps | 35.87 fps | **吞吐速度提升 1.61 倍** | -| **总计处理帧数** | 7,830 帧 | 7,830 帧 | 完全一致(261 秒 / 4 分 21 秒) | -| **输出视频规格** | 1920 × 1080 (1080p @ 30fps) | 1920 × 1080 (1080p @ 30fps) | 完全一致 | -| **编码器设置** | H.264 (CRF 18, preset medium) | H.264 (CRF 18, preset medium) | 完全一致 | - -**基准测试宿主环境:** -- **CPU**:Intel Core i9-13900K(24 核 / 32 线程,最高睿频 5.8 GHz) -- **GPU**:NVIDIA GeForce RTX 3060(12GB GDDR6 显存,驱动版本 551.xx) -- **内存**:64GB DDR5 5600 MHz -- **系统**:Windows 11 专业版 64 位 -- **软件栈**:Node.js v20.x,Remotion v4.0.x,开启 Chromium 无头 GPU 加速 - -两次基准测试均在同一工作站、连续以完全相同的音频频谱输入和插画素材进行。渲染耗时缩短 38.0%,即吞吐速度达到优化前的 **1.615 倍**,使原本慢于真实播放时长的渲染变为高于实时帧率的高效输出。 - ---- - -## 本专题关联阅读 -- **系统总架构篇**:[我是如何用 Remotion 与 Docker CDP 打造全自动 MV 生成与多语种油管发布流的](/posts/zh/how-i-built-an-automated-music-video-pipeline/) -- **大文件上传篇**:[借助 Docker Archive API 模式通过 CDP 自动化上传 100MB+ 视频到 YouTube](/posts/zh/uploading-large-videos-to-youtube-via-cdp/) -- **线上实成片**:[前往 YouTube 观看《糖画小仙》1080P 官方完整成片](https://youtu.be/vZbyKeCCSRA) -```` - -### 🇬🇧 英文版原文 (English Markdown Primary) -````markdown ---- -title: "Debugging Remotion Video Jitter: Why Bass Scaling Ruins Background Transitions" -description: "Diagnose audio-reactive background jitter and crossfade flicker in Remotion. See how separating the HUD from background layers can improve visual stability and rendering performance." -pubDate: 2025-11-26 -updatedDate: 2026-10-22 -category: engineering -stream: creative-lab -tags: ["remotion", "react", "audio-visualizer", "css-animation", "debugging"] -ogImage: "/og/debugging-remotion-video-jitter.jpg" -banner: "/banners/debugging-remotion-video-jitter.jpg" -draft: false ---- - -Building programmatic videos with React and Remotion gives you complete DOM control over every frame. You can map web audio frequencies directly to SVG attributes, CSS transforms, and typography in ways standard video editors can barely touch. - -However, treating video frames like standard web pages introduces subtle visual bugs. In our automated music video pipeline, an export that looked plausible in unit tests developed a jarring, violent shudder when rendered into a 1080p MP4. - -Here is what went wrong, why our initial intuition about audio reactivity failed, and how to structure React video layers so audio-driven HUDs never pollute background transitions. - -> **Live Reference**: The repaired rendering pipeline produced the final production MV for [《糖画小仙》 (Sugar Art Fairy) on YouTube](https://youtu.be/vZbyKeCCSRA), running rock-solid at 1080p 30fps. - -> **TL;DR** — Scaling a full-bleed background image with the bass band forces an interpolation resampling on every frame, which the human eye perceives as violent shudder. Furthermore, two stacked semi-transparent layers crossfading symmetrically dip through the black root container at the midpoint. Fixes: keep the background canvas completely static, decouple all audio-reactive pulsing into isolated foreground HUD layers, and fade in the incoming slide on top of a 100% solid base. Render time dropped by **38.0% (from 352s to 218s, a 1.61× throughput speedup)**. This is the rendering chapter of our [music-video pipeline](/posts/how-i-built-an-automated-music-video-pipeline/); the file-staging half is covered in [uploading large videos via CDP](/posts/uploading-large-videos-to-youtube-via-cdp/). - ---- - -## 1. The Symptom: A Whole-Frame Earthquake - -The visual effect was supposed to be simple: -1. An illustrated 1080p background slowly crossfading between slides. -2. A pulsing circular spectrum visualizer in the foreground. -3. Three lines of Chinese calligraphy lyrics that slide between left and right depending on where the character in the artwork is standing. - -In preview scrubbing, everything looked acceptable. But during full-speed 30fps playback of the rendered 1080p file, the viewer felt instant visual fatigue. Every time the electronic drum pattern kicked in, the entire scene appeared to vibrate violently up to 30 times per second. Furthermore, during slide transitions, the screen experienced micro-flashes where the background brightness suddenly dipped. - ---- - -## 2. Root Cause 1: Low-Frequency Scale Pollution - -Looking at the initial `BackgroundSlideshow.tsx`, we had attached an audio reactivity hook: - -```tsx -// The culprit in BackgroundSlideshow.tsx -const bassScale = interpolate(bassLevel, [0, 1], [1.0, 1.025], { - extrapolateRight: 'clamp', -}); - -// Applied to the background image: - -``` - -On paper, expanding the image by 2.5% on bass hits sounds like an engaging dynamic pulse. In reality: -- **Electronic audio beats hit in 30–60ms bursts**: The bass amplitude oscillates rapidly between zero and peak within 2 to 3 consecutive frames. -- **A 1920x1080 image scaling by 2.5% shifts edge pixels by nearly 25 to 30 physical pixels in a single frame**. -- When that sudden displacement reverses on the very next frame, the human eye interprets it not as a musical pulse, but as **severe camera camera shake / stutter**. -- To make matters worse, during the 1.8-second slide transition, two overlapping images with different transform origins were simultaneously vibrating at conflicting scales, creating a hallucinatory double-vision jitter. - ---- - -## 3. Root Cause 2: Symmetrical Opacity Crossfade DIP - -The second issue was the crossfade flash. In standard web CSS, people often do: - -```css -/* Web crossfade trap */ -.current-slide { opacity: 1 -> 0; } -.next-slide { opacity: 0 -> 1; } -``` - -When two images crossfade with linear opacity, consider what happens at the exact midpoint ($t = 0.5$): -- $\text{Current Slide Opacity} = 0.5$ -- $\text{Next Slide Opacity} = 0.5$ - -Here is how the browser/Remotion compositing pipeline stacks these layers against the root black container: - -``` -┌─────────────────────────────────────────────────────────────┐ -│ Layer 2: Next Slide (opacity = 0.5) │ -├─────────────────────────────────────────────────────────────┤ -│ Layer 1: Current Slide (opacity = 0.5) │ -├─────────────────────────────────────────────────────────────┤ -│ Layer 0: Root Container (background = #000000 black) │ -└─────────────────────────────────────────────────────────────┘ -``` - -Because alpha blending operates multiplicatively down the stack: -$$\text{Composite Alpha} = 1 - (1 - 0.5) \times (1 - 0.5) = 1 - 0.25 = 0.75$$ - -The total combined alpha drops to **0.75**, exposing **25% of the black background**! This is not an optical illusion; it is mathematical light loss. Every time a transition peaked, the frame darkened by a quarter of its luminance, creating an unmistakable flicker. - ---- - -## 4. The Solution: Rock-Solid Base + Pure Single-Direction Opacity - -To fix both issues permanently: - -### 1. Remove All Scaling from Backgrounds -Background artwork must remain rock-solid. All audio reactivity belongs exclusively in the HUD layer (the radial spectrum bars and glowing rings). The background canvas should only ever receive smooth, non-oscillating transformations. - -### 2. Base Solid + Top Layer Fade-In -Instead of fading out the current image, **keep the current image at solid 100% opacity**. Only animate the incoming image on top: - -```tsx -return ( -
- {/* Base Slide: Stays 100% solid, eliminating any drop to black */} - - - {/* Next Slide: Smoothly fades in on top over 1.8s */} - {isTransitioning && ( - - )} +
+ + + + + + +
-); +
+ + +
+
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+ +## The Problem: The 240-Second Wall + +In earlier batches, songs generated via standard ComfyUI text-to-music nodes frequently +exhibited one of two failure modes: + +1. **The Chopped Outro**: Setting `max_duration = 240.0s` while feeding a full lyric + sheet resulted in the track hitting the final timestamp while the acoustic model was + still executing the chorus. All 12 initial test runs ended at exactly `240.000s`—an + unusable hard cliff. +2. **The Panic Accelerando**: If you prompt the model to fit too many lines into a tight + window, the auto-regressive acoustic token predictor compresses the vocal pacing, + turning an emotional Celtic ballad into an unnatural rap cadence. + +The fundamental mistake was treating `max_duration` as the *desired song length*. +In generative auto-regressive audio, **max duration is not your target length; it is your +acoustic safety wall.** + +## The Three Architecture Fixes + +### 1. The 295.0s Headroom Formula + +To produce songs that naturally conclude with a 4-minute runtime, you must structure +the lyric density for **210s to 260s**, but provision the generator with **295.0s** +of ceiling: + +$$\text{Headroom Buffer} = \text{Max Duration (295s)} - \text{Expected Lyric Duration (220s)} \approx 75\text{s}$$ + +This ~75-second buffer provides the acoustic model with the token budget required to: +- Complete the final verse without panic compression; +- Introduce a dedicated, melodic instrumental outro; +- Execute natural acoustic decay, room reverb dissipation, and final silence. + +### 2. Automated Hard-Cut Quarantine Gate + +Any take whose generated length measures within 0.1s of the hard ceiling (`>= 294.9s`) +is treated as an unresolved truncation failure and automatically quarantined. Only takes +that resolve naturally before the ceiling (`duration < 294.0s`) are accepted into the +production archive. Across our 60-song run, all 60 finalized masters ended between +**129.9s and 285.6s** with zero abrupt cutoffs. + +### 3. VRAM Stabilization on a 12GB RTX 3060 + +Running YuE2-3B in BF16 on consumer hardware requires tight memory lifecycle management: + +```bash +# Launch ComfyUI standalone with minimal VRAM overhead +cd /d/app/ComfyUI +./python_embeded/python.exe -s ComfyUI/main.py \ + --windows-standalone-build \ + --port 8188 \ + --disable-pinned-memory \ + --disable-nvml-pressure \ + --cache-classic ``` -### 3. Physical Decoupling of HUD and Canvas -The lyric box and circular spectrum are mounted inside a completely separate container layer with `pointerEvents: 'none'`. As the HUD glides across the canvas from `centerX: 540` to `centerX: 1380`, it calculates its position strictly from the timeline clock. It has zero knowledge of and zero impact on the background's opacity crossfade. +By enforcing immediate model unloading via `/free` after batch execution and maintaining +zero pinned memory overhead, generation of 4.5-minute sequences remains rock-solid without +triggering CUDA out-of-memory errors. --- -## 5. The Outcome & Benchmark Reproduction - -After removing the background `bassScale` and switching to one-way opacity stacking: - -1. **Eliminated visible jitter**: Background illustrations remain crisp and visually anchored through rapid 140 BPM electronic drum drops across all test sequences. -2. **Eliminated transition light dips**: The 1.8s Bezier crossfade maintains 100% luminance continuity without dipping through the dark container base. -3. **Significant throughput speedup**: Removing per-frame matrix interpolation and scaling calculations on high-resolution background assets delivered a measurable performance boost. - -### Reproduction Benchmark - -| Metric | Before Optimization | After Optimization | Delta | -|---|---|---|---| -| **Render Duration** | 352.0 seconds | 218.3 seconds | **-38.0% (-133.7s)** | -| **Render Throughput** | 22.24 fps | 35.87 fps | **+1.61× speedup** | -| **Total Frames** | 7,830 frames | 7,830 frames | Identical (261s / 4m 21s) | -| **Output Resolution** | 1920 × 1080 (1080p @ 30fps) | 1920 × 1080 (1080p @ 30fps) | Identical | -| **Codec & Settings** | H.264 (CRF 18, preset medium) | H.264 (CRF 18, preset medium) | Identical | - -**Test Environment Specifications:** -- **CPU**: Intel Core i9-13900K (24 cores / 32 threads, boost up to 5.8 GHz) -- **GPU**: NVIDIA GeForce RTX 3060 (12GB GDDR6 VRAM, Driver 551.xx) -- **RAM**: 64GB DDR5 5600 MHz -- **OS**: Windows 11 Pro 64-bit -- **Software**: Node.js v20.x, Remotion v4.0.x with Chromium headless GPU rendering enabled - -Both benchmark runs were executed consecutively using identical media assets, audio spectrogram inputs, and composition parameters. The 38.0% reduction in render time directly translates to a **1.61× throughput speedup**, turning a process that was previously slower than realtime into an accelerated 35.8 fps export. - ---- - -## Related Guides in this Series -- **Pipeline Architecture**: [How I Built an Automated Music Video Pipeline with Remotion and Docker](/posts/how-i-built-an-automated-music-video-pipeline/) -- **Remote Publishing**: [Uploading 100MB+ Videos to YouTube via CDP: The Docker Archive Pattern](/posts/uploading-large-videos-to-youtube-via-cdp/) -- **Live Output**: [Watch the finished MV on YouTube](https://youtu.be/vZbyKeCCSRA) -```` - ---- - -## 文章 06 / 11:把字体嵌进 PDF,让它在任何机器上都长一样 -- **Slug**: `embedding-fonts-so-a-pdf-looks-the-same-everywhere` -- **英文标题**: Embedding Fonts So a PDF Looks the Same on Every Machine -- **分类**: `engineering` | **发布日期**: 2025-01-22 -- **线上地址**: https://blog.hoelee.com/posts/embedding-fonts-so-a-pdf-looks-the-same-everywhere/ (EN) | https://blog.hoelee.com/posts/zh/embedding-fonts-so-a-pdf-looks-the-same-everywhere/ (ZH) -- **本篇审核状态**: ⏳ 待审核 (Pending) - -### ✍️ 顾问审阅意见区 (Review Feedback) -```text -【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 -【事实与数字核对】: -【人设与用词卫生】: -【CRO与转化建议】: -``` - -### 🇨🇳 中文版原文 (Chinese Markdown Twin) -````markdown ---- -title: "把字体嵌进 PDF,让它在任何机器上都长一样" -description: "四个字族、八个字面、两个渲染引擎,外加一条 CSS 怪癖:为了不让生成的报告依赖服务器上恰好装了什么字体,我做了什么。" -pubDate: 2025-01-22 -updatedDate: 2026-10-16 -category: engineering -tags: ["pdf", "fonts", "mpdf", "typography", "php"] -ogImage: /og/zh-embedding-fonts-so-a-pdf-looks-the-same-everywhere.jpg -banner: /banners/embedding-fonts-so-a-pdf-looks-the-same-everywhere.jpg -draft: false ---- - -## 需求只有一句话 - -一个报告生成器必须产出在任何地方都长得一样的文档:中文标题用宋体、中文正文用黑体、英文标题与封面数字用一款展示衬线体、英文正文和表格用 Inter。字重也要对——强调用 medium、标题用 semibold——而且是三语、两个 PDF 渲染引擎都要对。 - -同时,**字体必须跟着文档走**。不是「服务器装过」,也不是「读者大概有」,而是**嵌进文件里**,这样另一个国家的印厂看到的页面是一样的。 - -老管线在最后这句上栽得很隐蔽:它依赖服务器上用包管理器装过的字体,而且**只嵌入了一款中文字体**。第二档字重根本不存在,于是「粗体」是渲染器的合成近似;而想发现这件事,唯一的办法是打开 PDF 去看里面到底装了什么。 - -## 规则一:从成品 PDF 里把字体读回来 - -「已嵌入」是一个关于**输出**的断言,所以我量的是输出。同一份文档,改前与改后: - -| | 改前 | 改后 | -|---|---|---| -| zh 页数 | 23 | **23** | -| en 页数 | 28 | **29** | -| bm 页数 | 30 | **30** | -| 真正嵌进去的字体 | 一款中文字体 + Roboto | 思源宋 Medium + SemiBold · 思源黑 Regular + Medium · Cormorant Garamond Medium + SemiBold · Inter Regular + SemiBold + Medium · 拉丁报告里的汉字走思源黑 | -| 渲染时间 / 峰值内存 | 基线 | 同一量级(±10%,属噪声) | -| 文件体积 | 基线 | 约 +3% | - -每个字面的字形数是收据:中文报告里 15,988 个字形落在正文黑体、2,247 个落在它的 medium 档、634 个落在标题宋体的 medium、222 个落在它的 semibold。这就是「字体在服务器上」与「字体在文件里」的区别——另一个国家的读者看到的是同样四个字面,而代价是某一种语言正好多一页(拉丁字体的度量比它替换掉的那个更宽)。 - -## 规则二:只出静态实例,理由写在解析器里 - -现代做法看起来该是「每个字族发一个可变字体」,但在这里是错的,有两个实测理由: - -1. **PDF 引擎的字体解析器只读 `glyf`/`loca`。** 喂它一个 PostScript/CFF 轮廓的 OpenType 文件,它直接拒绝:`Fonts with postscript outlines are not supported`。问题不是「可变」,是 CFF 轮廓。 -2. **它完全不读 `fvar` 表**,所以可变字体会**静默地**解析成它的**默认实例**——而中文字族的默认实例恰恰是最细的那一档(`name` 表里写得清清楚楚:Thin 100 与 ExtraLight 200)。整份报告会变成发丝体,而整条管线里不会报任何一个错。 - -所以构建步骤拿上游的可变字体**实例化成静态切面**:跑实例化器,然后把 `name`、`OS/2.usWeightClass` 和 `head.macStyle` 改写成它现在真实的字重(源文件的名字里还写着 Thin)。产物旁边有一份 manifest,逐文件记下 family、字重、sha256、字形数与码位数;许可证也随文件一起进仓库。 - -## 规则三:引擎只会说两种字重,那就映射到两个槽位 - -渲染引擎的 CSS 只认 `normal` 和 `bold`——它的源码自己就这么写("Does not support: bolder, lighter, 100..900")。所以数字字重对它毫无意义;而同一条管线里的无头 Chromium 又完全认它们。 - -可用的映射是:每个字族声明一个 **R 槽**和一个 **B 槽**(常规一档、更重一档),`font-weight: 500` 落到目标字族的 R 槽,`600` **只在 PDF 那一侧被改写成 `bold`**,落到 B 槽。Chromium 侧照写 `600`。两条测试钉住它:B 槽必须比 R 槽重(读 `usWeightClass`,不是假设),且 `font-weight: 600` 绝不允许出现在交给 PDF 引擎的样式表里。 - -有一处细节值得单写一段:在这个管线里,**medium 不是强调手段,而是一个字族成员**。中文标题用宋体的 medium 当常规、用 semibold 做强调;英文标题用展示衬线体做同样的事。这里搞错,屏幕上完全看不出来,而印出来一目了然。 - -## 规则四:不要按你控制不了输入的字集做子集化 - -第一版把中文字体按两个国家字集的并集做了子集,产物从约 50 MB 降到约 29 MB。然后我跑了姓名探针,发现这些字被裁掉了: - -```text -犇 骉 頔 祎 廸 玧 祾 赟 堃 -``` - -每一个都是真实的人名用字。报告会把客户姓名印在封面上,而姓名是自由输入——所以一套基于子集的构建,迟早会在产品最醒目的那一页上放一个豆腐块。全字形覆盖是约 31k 码位、约 50 MB 的嵌入字体;为了永远不给客户看一个空方块,这个价钱很便宜。 - -## 规则五:把「缺字」变成构建失败,而不是惊喜 - -闸门跑三项检查,任何一项不过就非零退出: - -- manifest 里声明的每个字体文件都在,且 sha256 与磁盘上的文件一致; -- 内容库(三语全部)+ 品牌字面 + 各类探针(简体、繁体、CJK 标点、全角、中英混排、数字、拉丁扩展、符号)+ 姓名用字,**每一个字在「它实际会被哪一档字体印出来」的那一档里都有字形**; -- 查字形用的是 PDF 引擎自己的解析器,而不是第三方库,所以这条检查不可能和渲染器互相矛盾。 - -已知边界写在明处,不藏起来:✅ ✔ 这类符号在这几款正文字体里都没有字形,而引擎也画不了彩色 emoji,所以它们不出现在报告正文;拉丁标题那款展示衬线体只有 974 个字形,不画 ① ★ ℃,这也是为什么内容库的检查覆盖**所有**槽位而不只是正文;而拉丁报告里的汉字必须走专门的 CJK 槽位——两条测试防止两个渲染器在这点上产生分歧。 - -## 如果重来一次 - -1. **在动样式之前先定字族与字重。** 版式做完之后再去加第二档字重,意味着每一页页数都要手工复核一遍。 -2. **选字体格式之前先读渲染器的源码。** 可变字体看着是审美问题,实际上是解析器问题——两个文件、十分钟就定了。 -3. **把要嵌进文档的一切当作许可证产物。** 字体文件连同许可证一起进仓库,否则就得进别人的法务审查。 -4. **量「到底嵌进去了什么」。** 页数、每个字面的字形数、文件体积、渲染时间:四项都动了,其中三项的方向和我猜的相反。 - -## 结果 - -改前:一款中文字体加一款界面字体、靠合成粗体、还取决于服务器装过什么。改后:四个字族、八个静态字面真正嵌在文件里,字重是各个字族真实的成员,页数与上一版相差不超过一页,而且有一条 lint 闸门:某个字没有字形时直接让构建失败——于是失败形态从「客户看到一个方块」变成了「CI 拒绝发版」。这跟这条管线里其它地方的取舍是同一个:**让错误发不出去,而不是让错误容易被看见。** -```` - -### 🇬🇧 英文版原文 (English Markdown Primary) -````markdown ---- -title: "Embedding Fonts So a PDF Looks the Same on Every Machine" -description: "Four families, eight faces, two renderers and one CSS quirk: what it took to stop a generated report depending on whatever fonts the server happened to have." -pubDate: 2025-01-22 -updatedDate: 2026-10-16 -category: engineering -tags: ["pdf", "fonts", "mpdf", "typography", "php"] -ogImage: /og/embedding-fonts-so-a-pdf-looks-the-same-everywhere.jpg -banner: /banners/embedding-fonts-so-a-pdf-looks-the-same-everywhere.jpg -draft: false ---- - -## The requirement was one sentence - -A report generator has to produce a document that looks the same everywhere: -Chinese headings in a serif, Chinese body text in a sans, Latin headings and -cover numerals in a display serif, Latin body text and tables in Inter. -Weights matter — medium for emphasis, semibold for headings — across three -languages and two PDF renderers. - -And the fonts must travel with the document. Not "the server has them -installed", not "the reader probably has them" — **embedded**, so a print -shop in another country sees the same pages. - -The old pipeline failed on the last clause in a way that was invisible: it -depended on fonts installed on the server by a package manager, and it only -ever embedded a single CJK face. The second weight did not exist, so "bold" -was the renderer's synthetic approximation, and the only way to notice was -to open the PDF and look at what was actually inside it. - -## Rule one: read the fonts back out of the finished PDF - -"Embedded" is a claim about the output, so I measured the output. The same -document, rendered before and after: - -| | before | after | -|---|---|---| -| zh page count | 23 | **23** | -| en page count | 28 | **29** | -| bm page count | 30 | **30** | -| fonts actually embedded | one CJK face + Roboto | Source Han Serif Medium + SemiBold · Source Han Sans Regular + Medium · Cormorant Garamond Medium + SemiBold · Inter Regular + SemiBold + Medium · Source Han Sans for the CJK runs inside Latin reports | -| render time / peak memory | baseline | same order (±10%, noise) | -| file size | baseline | roughly +3% | - -The glyph counts per face are the receipt: in the Chinese report, 15,988 -glyphs land in the body sans, 2,247 in its medium weight, 634 in the heading -serif medium, 222 in its semibold. That is the difference between "the font -is on the server" and "the font is in the file" — a reader in another -country sees the same four faces, and a page count that moved by exactly one -page in one language (the Latin metrics are wider than what they replaced) -is the honest cost. - -## Rule two: static instances only, and the reason is in the parser - -The obvious modern choice — ship one variable font per family — is wrong -here, for two measured reasons: - -1. **The PDF engine's font parser reads `glyf`/`loca` only.** Feed it an - OpenType file with PostScript/CFF outlines and it refuses: - `Fonts with postscript outlines are not supported`. A variable font is - not the problem; CFF outlines are. -2. **It does not read the `fvar` table at all**, so a variable font silently - resolves to its *default instance* — and the default instances of the CJK - families are the thinnest ones (Thin 100 and ExtraLight 200, visible in - the `name` table). Every page would render in a hairline weight, with no - error anywhere in the pipeline. - -So the build step takes the upstream variable fonts and **instantiates -static cuts**: it runs the instancer, then rewrites `name`, -`OS/2.usWeightClass` and `head.macStyle` so the file identifies itself as -the weight it now is (the source's own name still says "Thin"). A manifest -records family, weight class, sha256, glyph count and code-point count for -every file, and the licence files ship next to them. - -## Rule three: the engine speaks two weights, so map onto two slots - -The renderer's CSS handling honours exactly `normal` and `bold` — its source -says so in as many words ("Does not support: bolder, lighter, 100..900"). -Numeric weights are therefore meaningless to it, while the headless-Chromium -renderer in the same pipeline honours them properly. - -The mapping that works: each family declares an **R slot** and a **B slot** -(regular-ish and heavier), `font-weight: 500` lands on the R slot of the -intended family, and `600` is **rewritten to `bold`** on the PDF side only, -which lands on the B slot. Chromium keeps `600` as written. Two tests pin -it: the B slot must be heavier than the R slot (read from `usWeightClass`, -not assumed), and `font-weight: 600` must never appear in the stylesheet -handed to the PDF engine. - -One subtlety worth the paragraph: a "medium" weight is not an emphasis -mechanism in this pipeline, it is a *family member*. Chinese headings use -the serif's medium as their regular and its semibold for emphasis; Latin -headings do the same with the display serif. Getting that wrong is invisible -on a screen and obvious in print. - -## Rule four: do not subset against a character set you do not control - -The first attempt subset the CJK fonts to the union of two national -character sets and produced a ~29 MB bundle instead of ~50 MB. Then I ran -the name probe and found these were cut: - -```text -犇 骉 頔 祎 廸 玧 祾 赟 堃 -``` - -Every one of them is a real given name character. The report prints a -customer's name on the cover, and the name is free input — so a subset-based -build will eventually put a tofu box on the most prominent page of the -product. Full coverage is ~31k code points and roughly 50 MB of embedded -fonts; that is a fine price for never showing a customer an empty rectangle. - -## Rule five: make missing glyphs a build failure, not a surprise - -The gate runs three checks and exits non-zero on any of them: - -- every font file declared in the manifest is present, and its sha256 - matches the file on disk; -- every character in the content library (all three languages) plus the - brand strings, plus probe classes — simplified, traditional, CJK - punctuation, full-width forms, mixed-script, digits, Latin extended, - symbols — plus the name characters, has a glyph **in the face that will - actually print it**; -- the lookup uses the PDF engine's own font parser rather than a third-party - library, so the check cannot disagree with the renderer. - -The known edges are written down instead of hidden. Dingbats and emoji (✅ ✔) -exist in none of these text fonts and the engine cannot draw colour emoji, -so they are kept out of the report body. The display serif has only 974 -glyphs and does not draw symbols like ① ★ ℃, which is why the -content-library check covers *all* slots rather than just the body. And CJK -characters inside a Latin report must go through the dedicated CJK slot — -two tests keep the renderers from disagreeing about that. - -## What I would do differently - -1. **Choose faces and weights before styling anything.** Retrofitting a - second weight after the layout exists means re-checking every page count - by hand. -2. **Read the renderer's source before choosing a font format.** The - variable-font decision looked like a taste question and was actually a - parser question — two files settled it in ten minutes. -3. **Treat everything you ship inside a document as a licence artifact.** - Font files enter the repo with their licences, or they enter someone - else's legal review. -4. **Measure what got embedded.** Page count, glyph-per-face counts, file - size, render time: all four moved, and three of them moved in ways I - would have guessed wrong. - -## The result - -Before: one CJK face and a UI font, with synthetic bold, depending on what -the server had installed. After: four families and eight static faces -embedded in the file, weights that are real members of their families, page -counts within one page of the previous layout, and a lint gate that fails -the build when a character has no glyph — so the failure mode moved from "a -customer sees a box" to "CI refuses the release". Which is the same trade as -everywhere else in this pipeline: make the mistake impossible to ship rather -than easy to notice. -```` - ---- - -## 文章 07 / 11:那个把静默丢失更新变成 409 的 JPA 字段:@Version 乐观锁 -- **Slug**: `jpa-version-field-lost-update` -- **英文标题**: The JPA Field That Turns a Silent Lost Update Into a 409 -- **分类**: `engineering` | **发布日期**: 2026-08-19 -- **线上地址**: https://blog.hoelee.com/posts/jpa-version-field-lost-update/ (EN) | https://blog.hoelee.com/posts/zh/jpa-version-field-lost-update/ (ZH) -- **本篇审核状态**: ⏳ 待审核 (Pending) - -### ✍️ 顾问审阅意见区 (Review Feedback) -```text -【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 -【事实与数字核对】: -【人设与用词卫生】: -【CRO与转化建议】: -``` - -### 🇨🇳 中文版原文 (Chinese Markdown Twin) -````markdown ---- -title: "那个把静默丢失更新变成 409 的 JPA 字段:@Version 乐观锁" -description: "在 REST + JPA 的读-改-写流程里,两个编辑同时保存同一条记录时,后保存者会静默覆盖先保存者的修改,而 API 两次都返回成功——JPA 的 @Version 乐观锁把这个静默丢失更新变成 HTTP 409 冲突:请求携带期望版本号,版本不符就拒绝写入,并提示客户端重新读取再试。" -pubDate: 2026-08-19 -category: engineering -tags: [java, spring, jpa, hibernate, rest, testing] -ogImage: /og/zh-jpa-version-field-lost-update.jpg -banner: /banners/jpa-version-field-lost-update.jpg -draft: false ---- - -两个人同时打开同一篇文章,两个人都改了,两个人都保存。其中一次 -保存悄无声息地消失了——没有报错,没有警告,而且 API 对两次请求 -都返回了 HTTP 200。 - -这就是丢失更新(lost update)问题,是读-改-写(read-modify-write) -API 里最安静的数据丢失 bug。我在做 Spring Boot 作品集 demo 时撞上 -了它——这是一个 Spring Boot 3.5.16(Java 21)的 REST API,编辑器 -从浏览器页面创建和更新文章。修法最终落在三处:JPA 实体上的一个 -`@Version` 字段、请求契约里的一个字段、以及 API 层把它映射成 -HTTP 409 Conflict 的一个异常。这篇文章就沿着真实代码走一遍这条路。 - -## 问题:一条编辑消失了,却谁都怪不上 - -为什么两个人保存同一条记录时,其中一个人的修改会消失? - -跟着时间线走。编辑器 A 和编辑器 B 都拉取了同一篇文章。A 先保存: -行被更新,API 返回 200。B 稍后保存:行被*再次*更新,这次覆盖了 -A 的文字,API 又返回 200。每个请求都成功;每个响应都告诉它的调用 -方「你的保存就是这条记录的当前状态」——对其中一个人来说这是假话。 -A 的编辑就这么没了,两个客户端都没有任何办法知道。 - -失败是静默的,因为它就是读-改-写流程的正常行为,不是异常。这正是 -它在真实系统里存活的理由,也是为什么在要展示工程判断力的东西里, -值得把它修得干净。 - -## 我先试的方案:不带版本号的读-改-写,以及它为什么失败 - -我对更新流程的第一版草图是最直白的那种:`GET` 记录、编辑、 -`PUT` 回去,只带新的标题和正文,什么都不带。 - -```text -GET /api/posts/{id} # 读取记录 -PUT /api/posts/{id} # 写回新的标题和正文 -``` - -服务端加载行、套用更新、返回 200。它无从知道在这一行数据上,客户端 -在 `GET` 和 `PUT` 之间已经被别人动过——读取和写入是两个互不相干的 -请求,契约里没有任何东西把它们连起来。最后写入的人赢,而两个写入 -者都被告知成功。 - -在这里,200 比报错更糟。报错至少告诉输掉的那个客户端「出事了」, -给他们一个去查的理由。200 则告诉两个客户端「你们的保存就是记录 -当前的状态」——对其中一个是撒谎。输掉的那次编辑现在哪儿都不存在: -屏幕上没有,数据库里也没有;而因为客户端相信自己保存成功了, -没有人会去找这份数据。 - -## 修法:一个 @Version 字段、一份契约、一个冲突 - -修法一共五小步,全部都在 demo 的源码里。 - -### 1. 实体随身携带一个版本列 - -```java -@Entity -@Table(name = "posts", indexes = @Index(name = "idx_posts_title", columnList = "title")) -@EntityListeners(AuditingEntityListener.class) -public class Post { - - @Id - @GeneratedValue - @UuidGenerator - private UUID id; - - @Column(nullable = false, length = 160) - private String title; - - @Column(nullable = false, length = 10_000) - private String body; - - @Version - private long version; - // ... -} -``` - -`@Version` 告诉 Hibernate 把 `version` 当作乐观锁。它生成的每一条 -`UPDATE` 都变成有条件的: - -```sql -UPDATE posts -SET title = ?, body = ?, version = version + 1, ... -WHERE id = ? AND version = ? -``` - -如果这行数据的版本号已经和语句构造时的不一致,受影响行数为零, -Hibernate 就会拒绝这次 flush,而不是悄悄覆盖。实体从不用手自增 -计数器——更新方法只碰 `title` 和 `body`;版本号跟着写入一起走。 - -### 2. 版本号进入 API 契约 - -锁如果客户端无法参与,就没有用,所以版本号在两个方向上都穿过 -API。响应的 record 暴露它: - -```java -public record PostResponse(UUID id, long authorId, String title, String body, - long version, Instant createdAt, Instant updatedAt) { -} -``` - -更新请求则要求把它带回来: - -```java -public record UpdatePostRequest( - @NotBlank @Size(max = 160) String title, - @NotBlank @Size(max = 10_000) String body, - @NotNull @Min(0) Long version) { -} -``` - -`UpdatePostRequest` 旁边的学习注记说得很直白: -「the expected version is part of the update -contract, making optimistic locking visible to clients.」 -(期望的版本号是更新契约的一部分,让乐观锁对客户端可见。) - -### 3. 在拥有写事务的 service 里检查版本 - -```java -@CachePut(cacheNames = "posts", key = "#postId") -@Transactional -public PostResponse updatePost(UUID postId, UpdatePostRequest request) { - Post post = postRepository.findById(postId) - .orElseThrow(() -> new PostNotFoundException(postId)); - if (post.getVersion() != request.version()) { - throw new PostVersionConflictException(postId); +## The 60 Full-Length Song Archive + +All 60 tracks below were generated locally with YuE2 BF16, tagged with clean ID3v2.3 +metadata, paired with custom 1024×1024 Gemini-rendered full-bleed cover art (converted to +WebP), and hosted on CDN with HTTP 206 range-seeking support. + +*Tip: Use the interactive selector above to jump directly to any track.* + +
+
+ The Thimble Under the Moss cover art +
+
+
+ 01. The Thimble Under the Moss + MP3 + 3分11秒 (191.1s) · Celtic Folk · 清脆稚气女童声(类似 Cécile Corbel《Arrietty's Song》)|中速轻快(约 105 BPM) +
+ + +
+
+ +
+
+ Mist of Skellig Michael cover art +
+
+
+ 02. Mist of Skellig Michael + MP3 + 4分26秒 (266.2s) · Celtic Folk · 空灵圣洁的小女孩独唱(类似 Enya + 幼态音色)|慢速悠长(约 72 BPM,字少音长) +
+ + +
+
+ +
+
+ The Rose of Connemara cover art +
+
+
+ 03. The Rose of Connemara + MP3 + 4分43秒 (283.1s) · Celtic Folk · 纯净稚气少女音(类似 Cara Dillon 早期清亮少女感)|中慢速叙事(约 82 BPM) +
+ + +
+
+ +
+
+ Lanterns on the Moor cover art +
+
+
+ 04. Lanterns on the Moor + MP3 + 3分31秒 (211.2s) · Celtic Folk · 俏皮精灵般的女童声(类似 Cécile Corbel 欢快舞曲风)|快速三拍子(约 128 BPM) +
+ + +
+
+ +
+
+ The Weaver of Raglan Lane cover art +
+
+
+ 05. The Weaver of Raglan Lane + MP3 + 4分39秒 (279.3s) · Celtic Folk · 醇厚温暖的凯尔特民谣男声(类似 Luke Kelly,调剂男声)|中慢速(约 80 BPM) +
+ + +
+
+ +
+
+ 硝子の花束 cover art +
+
+
+ 06. 硝子の花束 + MP3 + 3分49秒 (230.0s) · Japanese Healing · 稚气通透、略带脆弱感的动漫少女音(祈妹风)|中慢速钢琴弦乐(约 78 BPM) +
+ + +
+
+ +
+
+ 銀の時計塔と宵の歌 cover art +
+
+
+ 07. 銀の時計塔と宵の歌 + MP3 + 4分34秒 (274.8s) · Japanese Healing · 清亮圣洁少女音 + 梶浦语吟唱|中速华尔兹三拍子(约 110 BPM) +
+ + +
+
+ +
+
+ 森の郵便屋さん cover art +
+
+
+ 08. 森の郵便屋さん + MP3 + 3分44秒 (225.0s) · Japanese Healing · 极度轻柔、如耳语般的稚气女童声|慢速木吉他与竖琴(约 68 BPM) +
+ + +
+
+ +
+
+ 白鳥の祈り cover art +
+
+
+ 09. 白鳥の祈り + MP3 + 4分06秒 (246.3s) · Japanese Healing · 空灵通透的高音少女/女童声,尾音带空灵共鸣|慢速大气(约 70 BPM) +
+ + +
+
+ +
+
+ 星屑のオルゴール cover art +
+
+
+ 10. 星屑のオルゴール + MP3 + 3分31秒 (211.8s) · Japanese Healing · 清甜稚气的少女声|中慢速轻盈感(约 88 BPM) +
+ + +
+
+ +
+
+ ひまわり行進曲 cover art +
+
+
+ 11. ひまわり行進曲 + MP3 + 3分18秒 (198.0s) · Japanese Energetic · 元气满满的小女孩独唱/齐唱感|中快速欢快节奏(约 118 BPM) +
+ + +
+
+ +
+
+ プリンは世界を救うのだ! cover art +
+
+
+ 12. プリンは世界を救うのだ! + MP3 + 3分23秒 (203.4s) · Japanese Energetic · 软萌夸张的稚气萝莉音(高音、语速快、字密)|快速电音流行(约 145 BPM) +
+ + +
+
+ +
+
+ こねこ探偵団のテーマ cover art +
+
+
+ 13. こねこ探偵団のテーマ + MP3 + 2分16秒 (136.1s) · Japanese Energetic · 奶声奶气的女童声(6~8岁童音感)|中速轻快爵士童谣(约 115 BPM) +
+ + +
+
+ +
+
+ 夏祭りのラムネ星 cover art +
+
+
+ 14. 夏祭りのラムネ星 + MP3 + 3分14秒 (195.0s) · Japanese Energetic · 清亮少年男声 + 稚气少女声(调剂少年音)|中快速夏日流行(约 122 BPM) +
+ + +
+
+ +
+
+ ほうきに乗って宅配便 cover art +
+
+
+ 15. ほうきに乗って宅配便 + MP3 + 3分16秒 (196.1s) · Japanese Energetic · 清脆阳光的小女孩声音|中速轻快复古流行(约 116 BPM) +
+ + +
+
+ +
+
+ 白露·竹间灯 cover art +
+
+
+ 16. 白露·竹间灯 + MP3 + 3分42秒 (222.6s) · Chinese Guofeng · 清甜稚气的少女/女童声|中速轻快电子国风(约 108 BPM) +
+ + +
+
+ +
+
+ 小鲤跃龙门 cover art +
+
+
+ 17. 小鲤跃龙门 + MP3 + 2分09秒 (129.9s) · Chinese Guofeng · 活泼软萌的稚气少女音(语速偏快、吐字灵动)|中快速(约 120 BPM) +
+ + +
+
+ +
+
+ 云海归鲲 cover art +
+
+
+ 18. 云海归鲲 + MP3 + 3分56秒 (236.9s) · Chinese Guofeng · 空灵仙气的少年假声/美声男声(调剂男声)|慢速悠远(约 68 BPM) +
+ + +
+
+ +
+
+ 纸伞巷 cover art +
+
+
+ 19. 纸伞巷 + MP3 + 3分34秒 (214.6s) · Chinese Guofeng · 清亮温婉的少女声(带一点点江南小调韵味)|中慢速(约 80 BPM) +
+ + +
+
+ +
+
+ 山间小道士 cover art +
+
+
+ 20. 山间小道士 + MP3 + 3分07秒 (187.6s) · Chinese Guofeng · 纯真稚气的小女孩/少女声音|中速轻快民谣古风(约 105 BPM) +
+ + +
+
+ +
+
+ 橘子汽水的夏天 cover art +
+
+
+ 21. 橘子汽水的夏天 + MP3 + 2分48秒 (169.0s) · Gentle Acoustic · 清澈稚气的少女声|中慢速木吉他民谣(约 82 BPM) +
+ + +
+
+ +
+
+ 外婆的小院 cover art +
+
+
+ 22. 外婆的小院 + MP3 + 3分32秒 (212.4s) · Gentle Acoustic · 纯真软糯的小女孩声音|慢速温情(约 72 BPM) +
+ + +
+
+ +
+
+ 开往北方的绿皮车 cover art +
+
+
+ 23. 开往北方的绿皮车 + MP3 + 3分36秒 (216.3s) · Gentle Acoustic · 低沉温暖的民谣男声(调剂男声)|慢速叙事(约 75 BPM) +
+ + +
+
+ +
+
+ 写给流浪猫的信 cover art +
+
+
+ 24. 写给流浪猫的信 + MP3 + 2分09秒 (129.9s) · Gentle Acoustic · 俏皮温柔的稚气少女音|中速轻快尤克里里/木吉他(约 98 BPM) +
+ + +
+
+ +
+
+ 平凡的傍晚 cover art +
+
+
+ 25. 平凡的傍晚 + MP3 + 3分41秒 (221.0s) · Gentle Acoustic · 温柔治愈的青年男声(调剂男声)|慢速钢琴与木吉他(约 74 BPM) +
+ + +
+
+ +
+
+ Light of the Eventide cover art +
+
+
+ 26. Light of the Eventide + MP3 + 4分09秒 (249.0s) · Angelic Choir · 天籁女童高音领唱 + 纯净童声合唱|极慢速庄严(约 66 BPM) +
+ + +
+
+ +
+
+ Bells of the Winter Star cover art +
+
+
+ 27. Bells of the Winter Star + MP3 + 2分47秒 (167.6s) · Angelic Choir · 清脆女童多声部齐唱與轮唱|中快速灵动节奏(约 125 BPM) +
+ + +
+
+ +
+
+ Paper Planes in the Wind cover art +
+
+
+ 28. Paper Planes in the Wind + MP3 + 3分25秒 (205.5s) · Angelic Choir · 清亮纯真的女童领唱 + 学院风童声合唱|中速温暖(约 96 BPM) +
+ + +
+
+ +
+
+ Lullaby of the Little Star cover art +
+
+
+ 29. Lullaby of the Little Star + MP3 + 3分47秒 (227.8s) · Angelic Choir · 稚气纯净的小女孩独唱(突出童真独唱感)|慢速温柔(约 70 BPM) +
+ + +
+
+ +
+
+ Hymn of the Morning Meadow cover art +
+
+
+ 30. Hymn of the Morning Meadow + MP3 + 4分19秒 (259.9s) · Angelic Choir · 神圣清澈的女童领唱 + 宏大童声和声(帕赫贝尔卡农式递进)|慢速治愈(约 72 BPM) +
+ + +
+
+ +
+
+ 地板下的借物小人 cover art +
+
+
+ 31. 地板下的借物小人 + MP3 + 3分07秒 (187.7s) · Celtic Folk (ZH) · 清脆稚气女童声|中速轻快凯尔特竖琴与锡哨(约 105 BPM) +
+ + +
+
+ +
+
+ 迷雾孤岛的竖琴 cover art +
+
+
+ 32. 迷雾孤岛的竖琴 + MP3 + 3分24秒 (204.4s) · Celtic Folk (ZH) · 空灵圣洁的小女孩独唱|慢速悠长(约 70 BPM,字少音长) +
+ + +
+
+ +
+
+ 石楠花开的高地 cover art +
+
+
+ 33. 石楠花开的高地 + MP3 + 3分36秒 (216.9s) · Celtic Folk (ZH) · 纯净稚气少女音|中慢速木吉他与凯尔特小提琴(约 82 BPM) +
+ + +
+
+ +
+
+ 橡树下的萤火舞会 cover art +
+
+
+ 34. 橡树下的萤火舞会 + MP3 + 3分43秒 (223.1s) · Celtic Folk (ZH) · 俏皮精灵般的女童声(语速快、节奏感强)|快速三拍子(约 128 BPM) +
+ + +
+
+ +
+
+ 老航海家的绿宝石 cover art +
+
+
+ 35. 老航海家的绿宝石 + MP3 + 3分49秒 (229.8s) · Celtic Folk (ZH) · 醇厚温暖的凯尔特民谣男声(调剂男声)|中慢速(约 80 BPM) +
+ + +
+
+ +
+
+ 玻璃温室的告别 cover art +
+
+
+ 36. 玻璃温室的告别 + MP3 + 3分37秒 (217.0s) · Japanese Healing (ZH) · 稚气通透、略带脆弱感的动漫少女音|中慢速钢琴与弦乐(约 78 BPM) +
+ + +
+
+ +
+
+ 银色钟塔与暮光咏叹 cover art +
+
+
+ 37. 银色钟塔与暮光咏叹 + MP3 + 4分01秒 (241.4s) · Japanese Healing (ZH) · 清亮圣洁少女音 + 造语吟唱|中速古典哥特华尔兹(约 110 BPM) +
+ + +
+
+ +
+
+ 森林邮差的蒲公英 cover art +
+
+
+ 38. 森林邮差的蒲公英 + MP3 + 3分26秒 (206.7s) · Japanese Healing (ZH) · 极度轻柔、如耳语般的稚气女童声|慢速木吉他与钢片琴(约 68 BPM) +
+ + +
+
+ +
+
+ 白鸟与雪原的祈愿 cover art +
+
+
+ 39. 白鸟与雪原的祈愿 + MP3 + 3分39秒 (220.0s) · Japanese Healing (ZH) · 空灵通透的高音女童/少女声|慢速大气钢琴与管弦(约 70 BPM) +
+ + +
+
+ +
+
+ 发条星尘八音盒 cover art +
+
+
+ 40. 发条星尘八音盒 + MP3 + 3分18秒 (198.2s) · Japanese Healing (ZH) · 清甜稚气的少女声|中慢速八音盒与木吉他(约 88 BPM) +
+ + +
+
+ +
+
+ 向日葵小队出发 cover art +
+
+
+ 41. 向日葵小队出发 + MP3 + 2分39秒 (159.4s) · Japanese Energetic (ZH) · 元气满满的小女孩领唱 + 童声合唱感|中快速欢快节奏(约 118 BPM) +
+ + +
+
+ +
+
+ 焦糖布丁保卫战! cover art +
+
+
+ 42. 焦糖布丁保卫战! + MP3 + 3分38秒 (218.9s) · Japanese Energetic (ZH) · 软萌夸张的稚气萝莉音(高音、语速快、字密)|快速电音流行(约 145 BPM) +
+ + +
+
+ +
+
+ 猫咪侦探事务所 cover art +
+
+
+ 43. 猫咪侦探事务所 + MP3 + 2分31秒 (151.4s) · Japanese Energetic (ZH) · 奶声奶气的女童声(6~8岁童音感)|中速轻快木琴与铜管(约 115 BPM) +
+ + +
+
+ +
+
+ 夏夜烟火与波子汽水 cover art +
+
+
+ 44. 夏夜烟火与波子汽水 + MP3 + 3分07秒 (187.8s) · Japanese Energetic (ZH) · 清亮少年男声 + 稚气少女声(调剂少年音)|中快速夏日流行(约 122 BPM) +
+ + +
+
+ +
+
+ 骑上扫帚送快递 cover art +
+
+
+ 45. 骑上扫帚送快递 + MP3 + 3分08秒 (188.5s) · Japanese Energetic (ZH) · 清脆阳光的小女孩声音|中速轻快木吉他与手鼓(约 116 BPM) +
+ + +
+
+ +
+
+ 小满·青梅煮雨 cover art +
+
+
+ 46. 小满·青梅煮雨 + MP3 + 3分34秒 (214.9s) · Chinese Guofeng New · 清甜稚气的少女/女童声|中速轻快电子国风(约 106 BPM) +
+ + +
+
+ +
+
+ 糖画摊前的小狐仙 cover art +
+
+
+ 47. 糖画摊前的小狐仙 + MP3 + 3分12秒 (192.2s) · Chinese Guofeng New · 活泼软萌的稚气少女音(字密语速快)|中快速(约 124 BPM) +
+ + +
+
+ +
+
+ 鲛人泪·沧海月 cover art +
+
+
+ 48. 鲛人泪·沧海月 + MP3 + 3分59秒 (239.8s) · Chinese Guofeng New · 空灵仙气的少年假声/美声男声(调剂男声)|慢速深邃(约 68 BPM) +
+ + +
+
+ +
+
+ 兰亭旧墨 cover art +
+
+
+ 49. 兰亭旧墨 + MP3 + 3分49秒 (229.3s) · Chinese Guofeng New · 清亮温婉的少女声|中慢速古筝与二胡(约 80 BPM) +
+ + +
+
+ +
+
+ 采药小童下山记 cover art +
+
+
+ 50. 采药小童下山记 + MP3 + 3分24秒 (204.4s) · Chinese Guofeng New · 纯真稚气的小女孩声音|中速轻快木吉他与竹笛(约 104 BPM) +
+ + +
+
+ +
+
+ 晒太阳的旧毛衣 cover art +
+
+
+ 51. 晒太阳的旧毛衣 + MP3 + 3分04秒 (184.9s) · Gentle Acoustic New · 清澈稚气的少女声|中慢速木吉他民谣(约 80 BPM) +
+ + +
+
+ +
+
+ 奶奶的桂花糕 cover art +
+
+
+ 52. 奶奶的桂花糕 + MP3 + 3分42秒 (222.4s) · Gentle Acoustic New · 纯真软糯的小女孩声音|慢速温情口琴与吉他(约 72 BPM) +
+ + +
+
+ +
+
+ 北方的末班渡轮 cover art +
+
+
+ 53. 北方的末班渡轮 + MP3 + 3分49秒 (229.6s) · Gentle Acoustic New · 低沉温暖的民谣男声(调剂男声)|慢速深沉(约 74 BPM) +
+ + +
+
+ +
+
+ 云朵收集指南 cover art +
+
+
+ 54. 云朵收集指南 + MP3 + 2分56秒 (176.4s) · Gentle Acoustic New · 俏皮温柔的稚气少女音|中速轻快(约 98 BPM) +
+ + +
+
+ +
+
+ 街角二十四小时书店 cover art +
+
+
+ 55. 街角二十四小时书店 + MP3 + 4分13秒 (253.4s) · Gentle Acoustic New · 温柔治愈的青年男声(调剂男声)|慢速钢琴与木吉他(约 74 BPM) +
+ + +
+
+ +
+
+ 暮光归途 cover art +
+
+
+ 56. 暮光归途 + MP3 + 4分02秒 (242.6s) · Angelic Choir (ZH) · 天籁女童高音领唱 + 纯净童声合唱|极慢速庄严管风琴与弦乐(约 66 BPM) +
+ + +
+
+ +
+
+ 冬夜银铃 cover art +
+
+
+ 57. 冬夜银铃 + MP3 + 2分59秒 (179.0s) · Angelic Choir (ZH) · 清脆女童多声部齐唱与轮唱|中快速灵动三拍子(约 125 BPM) +
+ + +
+
+ +
+
+ 迎风飞翔的纸飞机 cover art +
+
+
+ 58. 迎风飞翔的纸飞机 + MP3 + 3分53秒 (233.2s) · Angelic Choir (ZH) · 清亮纯真的女童领唱 + 学院风童声合唱|中速温暖(约 96 BPM) +
+ + +
+
+ +
+
+ 小星星的晚安曲 cover art +
+
+
+ 59. 小星星的晚安曲 + MP3 + 3分51秒 (232.0s) · Angelic Choir (ZH) · 稚气纯净的小女孩独唱|慢速竖琴与小提琴(约 70 BPM) +
+ + +
+
+ +
+
+ 晨曦草地的赞美诗 cover art +
+
+
+ 60. 晨曦草地的赞美诗 + MP3 + 4分26秒 (266.0s) · Angelic Choir (ZH) · 神圣清澈的女童领唱 + 宏大童声和声(卡农式递进)|慢速治愈(约 72 BPM) +
+ + +
+
+ + -### 4. 异常处理器把它映射成 409 - -异常本身带着客户端能直接照做的信息: - -```java -public class PostVersionConflictException extends RuntimeException { - - public PostVersionConflictException(UUID postId) { - super("Post %s has changed; fetch it again before retrying".formatted(postId)); - } -} -``` - -错误边界把它转成正确的 HTTP 应答: - -```java -@ExceptionHandler(PostVersionConflictException.class) -ProblemDetail handleConflict(PostVersionConflictException exception) { - return problem(HttpStatus.CONFLICT, "POST_VERSION_CONFLICT", exception.getMessage()); -} -``` - -`HttpStatus.CONFLICT` 就是 HTTP 409,响应是一份 problem -document——一个 `type` URI、一个稳定的机器码 -(`POST_VERSION_CONFLICT`)和一段人类可读的说明。demo 在配置里 -开启了框架的 problem-details 支持 -(`spring.mvc.problemdetails.enabled: true`),所以校验错误和所有 -其他错误都共用同一种响应形状。 - -### 5. 整条链路,从头到尾 - -```text -过期的 PUT /api/posts/{id} - -> PostService.updatePost 在事务内部重新读取这一行 - -> post.getVersion() != request.version() - -> PostVersionConflictException: "fetch it again before retrying" - -> ApiExceptionHandler.handleConflict - -> HTTP 409, ProblemDetail with code POST_VERSION_CONFLICT - -> 客户端知道自己的前提过期了 -``` - -一个 `@Version` 字段、请求契约里的一个 `version`、一个异常、一个 -handler 方法。Controller 什么都没改——`updatePost` 看起来还是普通 -的 `PUT`。 - -## 为什么答案是冲突,而不是重试 - -当两个编辑器产出同一份记录的两种不同版本时,服务端无法知道哪一方 -的意图才是被需要的。从各自作者的角度看,两次保存都正当;重放那条 -过期的写入,只是重放同一次数据丢失。 - -诚实的结论就是 HTTP 对 409 的定义:请求与资源的当前状态冲突, -并且客户端被明确告知如何解决——「fetch it again before retrying」 -(重新取一次再试)。输掉的客户端重新读取记录,看到另一位作者的 -修改,由人来决定保留什么。静默覆盖变成了一处看得见的决策点——这 -正是这件事的全部意义。 - -## 这个 demo 的其余部分证明了什么 - -版本字段只是一个小系统里的一层,而其余部分都能用同样的方式核实 -——下面每一行都是仓库里的一个类或配置文件,不是一句口号: - -| 层 | 做了什么 | 在哪 | -|---|---|---| -| 缓存 | 单篇文章读取使用有界 Caffeine 缓存(上限 500,TTL 10 分钟,都来自配置);读取用 `@Cacheable`、更新用 `@CachePut`、删除用 `@CacheEvict`;`GET /api/showcase/cache` 暴露请求数、命中数、未命中数和命中率 | `CacheConfig`、`CacheProperties`、`ShowcaseMetricsController` | -| 安全 | 无状态 HTTP Basic + BCrypt;页面与读 API 公开,所有写操作需要 `EDITOR` 角色;本地默认是专用的非机密 `demo-editor`/`changeit` 账户,可用环境变量覆盖 | `SecurityConfig`、`application.yml` | -| 错误 | 请求 record 在边界处校验;一个 `@RestControllerAdvice` 返回一致的 problem document 和机器码——`POST_NOT_FOUND`(404)、`POST_VERSION_CONFLICT`(409)、带字段错误表的 `VALIDATION_FAILED`(400) | `CreatePostRequest`、`UpdatePostRequest`、`ApiExceptionHandler` | -| 配置 | 本地 profile 使用内存 H2 数据库(PostgreSQL 模式),`ddl-auto: update` 并预置示例文章;`prod` 选择 PostgreSQL,所有凭据来自 `APP_*` 环境变量,`ddl-auto: validate` | `application.yml`、`application-prod.yml` | -| 测试 | 一个 `@SpringBootTest` 套件断言:渲染的 Thymeleaf 页面、未认证 401 对编辑器 201、`VALIDATION_FAILED` 问题响应、公开搜索,以及重复读取后的缓存命中 | `DemoApplicationIntegrationTest` | - -## 如果做真东西,我会怎么改 - -一旦这不再是本地 demo,有两件事立刻要变。项目 README 里两件都写了, -值得作为我自己的判断再重复一遍。 - -第一,schema 管理。我会在任何时候把 `ddl-auto` 设为 `validate` 之前, -先加 Flyway 或 Liquibase 迁移。demo 默认 profile 用的是 `update`, -在临时数据库上很方便,养成习惯就很危险——生产 schema 应该是 -有版本管理的代码,而不是启动时的副作用。 - -第二,密钥。本地编辑器账户是刻意的非机密 demo 账户,带默认凭据。 -做真东西的话,我会把凭据放进托管的密钥存储(managed secret store), -拿不到凭据就拒绝启动,而不是回退到默认值。`prod` profile 已经做到 -所有凭据来自环境变量、不提交任何密钥——这正是我想要的形态, -只是不要那些回退值。 - -## 结果 - -过期的更新现在返回 HTTP 409,机器码 `POST_VERSION_CONFLICT`,而不是 -一个静静丢掉另一位作者修改的 200。丢失不再可能悄悄发生:失败是 -响亮的、可操作的——「fetch it again before retrying」——并且集成 -测试套件端到端地断言了访问与校验行为。 - -整个修法就是一个字段上的一个注解,加上让版本号成为契约一部分的 -管道代码。如果一条记录可能同时被两个人读取,这个字段就是「编辑 -丢失」与「双方都看得见的冲突」之间的分界线。 - -我平时就做 Java/Spring 后端和全栈 Web 应用——从浏览器页面到数据库 -的 REST API:JPA、乐观锁、缓存、校验和一整套集成测试。如果你的表单 -或字段里也有「编辑悄悄消失」的问题,跟我说说: -[WhatsApp](https://wa.me/60127972969) · -[me@hoelee.com](mailto:me@hoelee.com?subject=Spring%20Boot%20help) · -[hoelee.com](https://hoelee.com)。 -```` - -### 🇬🇧 英文版原文 (English Markdown Primary) -````markdown ---- -title: "The JPA Field That Turns a Silent Lost Update Into a 409" -description: "How a JPA @Version field turns a silent lost update into a 409 conflict — optimistic locking makes a stale REST write fail loudly instead of overwriting." -pubDate: 2026-08-19 -category: engineering -tags: [java, spring, jpa, hibernate, rest, testing] -ogImage: /og/jpa-version-field-lost-update.jpg -banner: /banners/jpa-version-field-lost-update.jpg -draft: false --- -Two people open the same post. Both edit it. Both save. One of the saves -disappears without a trace — no error, no warning, and the API answered -HTTP 200 for both of them. +## Want This For Your Business? -That is the lost update problem, and it is the quietest data-loss bug in -read-modify-write APIs. I hit it while building my Spring Boot portfolio -demo — a Spring Boot 3.5.16 (Java 21) REST API where editors create and -update posts from a browser page. The fix turned out to be one `@Version` -field on the JPA entity, one field on the request contract, and one -exception that the API layer maps to HTTP 409 Conflict. This post traces -that path through the actual code. +I build and operate custom self-hosted AI media pipelines, automated video & audio +generation backends, and full-stack web platforms for small and medium enterprises. -## The problem: an edit that vanishes with no one to blame - -Why does one editor's change disappear when two people save the same -record? - -Follow the timeline. Editor A and editor B both fetch the same post. -A saves first: the row is updated and the API answers 200. B saves a -moment later: the row is updated *again*, this time over A's text, and -the API answers 200 again. Every request succeeded; every response told -its caller that their save is the state of the record. A's edit is -simply gone, and neither client has any way to know. - -The failure is silent because it is normal read-modify-write behaviour, -not an anomaly. That is exactly why the bug survives in real systems, and -why it is worth fixing properly in something meant to demonstrate -engineering judgement. - -## What I tried first, and why it failed - -My first sketch of the update flow was the obvious one: `GET` the record, -edit it, `PUT` it back with the new title and body and nothing else. - -```text -GET /api/posts/{id} # read the record -PUT /api/posts/{id} # write it back with a new title and body -``` - -The server loads the row, applies the update, and returns 200. It has no -way to notice that the row moved underneath the client between the `GET` -and the `PUT` — the read and the write are two unrelated requests, and -nothing in the contract connects them. The last write wins, and both -writers are told they succeeded. - -A 200 is worse than an error here. An error at least tells the losing -client that something happened and gives them a reason to look. A 200 -tells both clients that their save is the current state of the record, -which is a lie for one of them. The losing edit now exists nowhere — not -on screen, not in the database — and because the client believes it -saved, nobody goes looking for the data. - -## The fix: a @Version field, a contract, and a conflict - -The fix is five small parts, all of them in the demo's source. - -### 1. The entity carries a version column - -```java -@Entity -@Table(name = "posts", indexes = @Index(name = "idx_posts_title", columnList = "title")) -@EntityListeners(AuditingEntityListener.class) -public class Post { - - @Id - @GeneratedValue - @UuidGenerator - private UUID id; - - @Column(nullable = false, length = 160) - private String title; - - @Column(nullable = false, length = 10_000) - private String body; - - @Version - private long version; - // ... -} -``` - -`@Version` tells Hibernate to treat `version` as an optimistic lock. Every -`UPDATE` it generates becomes conditional: - -```sql -UPDATE posts -SET title = ?, body = ?, version = version + 1, ... -WHERE id = ? AND version = ? -``` - -If the row's version no longer matches the value the statement was built -with, zero rows change and Hibernate rejects the flush instead of quietly -overwriting. The entity never bumps the counter by hand — the update -method only touches `title` and `body`; the version moves with the write -itself. - -### 2. The version is part of the API contract - -A lock is useless if the client cannot take part in it, so the version -travels through the API in both directions. The response record exposes -it: - -```java -public record PostResponse(UUID id, long authorId, String title, String body, - long version, Instant createdAt, Instant updatedAt) { -} -``` - -and the update request requires it back: - -```java -public record UpdatePostRequest( - @NotBlank @Size(max = 160) String title, - @NotBlank @Size(max = 10_000) String body, - @NotNull @Min(0) Long version) { -} -``` - -The learning note next to `UpdatePostRequest` says it plainly: "the -expected version is part of the update contract, making optimistic -locking visible to clients." - -### 3. The service checks it inside the transaction that owns the write - -```java -@CachePut(cacheNames = "posts", key = "#postId") -@Transactional -public PostResponse updatePost(UUID postId, UpdatePostRequest request) { - Post post = postRepository.findById(postId) - .orElseThrow(() -> new PostNotFoundException(postId)); - if (post.getVersion() != request.version()) { - throw new PostVersionConflictException(postId); - } - post.update(request.title().trim(), request.body().trim()); - return PostResponse.from(postRepository.saveAndFlush(post)); -} -``` - -The load, the comparison and the save all happen inside one -`@Transactional` method, and that is the part that makes the check -honest: the version is compared against the row as it stands *at write -time*, not against a snapshot from an earlier request. If the read and -the write lived in different transactions, the check would compare -against a version the row has already left behind, and the whole scheme -would be theatre. The learning note on `PostService` names the rule: -"service methods centralize transaction boundaries, cache coherence, and -optimistic-locking rules." The demo also runs with -`spring.jpa.open-in-view: false`, so no lingering session serves a stale -entity across requests — the row is re-read inside the writing -transaction. - -The explicit check catches stale requests deterministically. The -`@Version` column still matters underneath: if another commit slips in -between the check and the flush, the conditional `UPDATE` affects zero -rows and Hibernate refuses the write anyway. - -### 4. The handler maps the exception to a 409 - -The exception itself carries the message a client can act on: - -```java -public class PostVersionConflictException extends RuntimeException { - - public PostVersionConflictException(UUID postId) { - super("Post %s has changed; fetch it again before retrying".formatted(postId)); - } -} -``` - -and the error boundary turns it into the right HTTP answer: - -```java -@ExceptionHandler(PostVersionConflictException.class) -ProblemDetail handleConflict(PostVersionConflictException exception) { - return problem(HttpStatus.CONFLICT, "POST_VERSION_CONFLICT", exception.getMessage()); -} -``` - -`HttpStatus.CONFLICT` is HTTP 409, and the response is a problem document -— a `type` URI, a stable machine code (`POST_VERSION_CONFLICT`) and a -human-readable detail. The demo enables the framework's problem-details -support in its configuration (`spring.mvc.problemdetails.enabled: true`), -so validation and every other error ride the same shape. - -### 5. The whole path, end to end - -```text -stale PUT /api/posts/{id} - -> PostService.updatePost re-reads the row inside its transaction - -> post.getVersion() != request.version() - -> PostVersionConflictException: "fetch it again before retrying" - -> ApiExceptionHandler.handleConflict - -> HTTP 409, ProblemDetail with code POST_VERSION_CONFLICT - -> the client knows its premise was stale -``` - -One `@Version` field, one `version` in the request contract, one -exception, one handler method. Nothing on the controller changed — -`updatePost` still looks like an ordinary `PUT`. - -## Why a conflict is the correct answer, not a retry - -When two editors produce two different versions of the same record, the -server cannot know which intent is the one meant. Both saves are -legitimate from their authors' point of view, and replaying the stale -write just replays the same data loss. - -The honest verdict is HTTP's own definition of 409: the request conflicts -with the current state of the resource, and the client is told exactly -how to resolve it — "fetch it again before retrying". The losing client -re-reads the record, sees the other writer's change, and a human decides -what to keep. The silent overwrite becomes a visible decision point, -which is the entire purpose of the exercise. - -## What the rest of the demo proves - -The version field is one layer of a small system, and the rest of it is -verifiable the same way — every row below is a class or a config file in -the repository, not a claim: - -| Layer | What it does | Where it lives | -|---|---|---| -| Caching | Bounded Caffeine cache on single-post reads (max 500, TTL 10 min, both from config); `@Cacheable` on read, `@CachePut` on update, `@CacheEvict` on delete; `GET /api/showcase/cache` exposes requests, hits, misses and hit rate | `CacheConfig`, `CacheProperties`, `ShowcaseMetricsController` | -| Security | Stateless HTTP Basic with BCrypt; pages and read APIs are public, every mutation needs the `EDITOR` role; local defaults are a throwaway `demo-editor`/`changeit` account overridable via env vars | `SecurityConfig`, `application.yml` | -| Errors | Request records validate at the boundary; one `@RestControllerAdvice` returns consistent problem documents with machine codes — `POST_NOT_FOUND` (404), `POST_VERSION_CONFLICT` (409), `VALIDATION_FAILED` (400) with a field-error map | `CreatePostRequest`, `UpdatePostRequest`, `ApiExceptionHandler` | -| Configuration | Local profile runs an in-memory H2 database in PostgreSQL mode with `ddl-auto: update` and seeded sample posts; `prod` selects PostgreSQL, takes every credential from `APP_*` env vars and sets `ddl-auto: validate` | `application.yml`, `application-prod.yml` | -| Tests | One `@SpringBootTest` suite asserts the rendered Thymeleaf pages, unauthenticated 401s versus editor 201s, the `VALIDATION_FAILED` problem response, public search, and cache hits after repeated reads | `DemoApplicationIntegrationTest` | - -## What I would do differently for anything real - -Two things change the moment this stops being a local demo. The project -README says both, and they are worth repeating as my own judgement. - -First, schema management. I would add Flyway or Liquibase migrations -before ever setting `ddl-auto` to `validate`. The demo's default profile -uses `update`, which is convenient on a scratch database and dangerous as -a habit — production schema should be versioned code, not a side effect -of startup. - -Second, secrets. The local editor account is intentionally a non-secret -demo account with default credentials. For anything real, I would keep -credentials in a managed secret store and refuse to boot without them, -instead of falling back to a default. The `prod` profile already takes -every credential from environment variables with no committed secrets — -that is the shape I would keep, minus the fallbacks. - -## The result - -A stale update now returns HTTP 409 with code `POST_VERSION_CONFLICT` -instead of a 200 that silently discards the other writer's change. The -loss can no longer happen quietly: the failure is loud, actionable — -"fetch it again before retrying" — and the integration test suite asserts -the access and validation behaviour end to end. - -The whole fix is one annotation on one field, plus plumbing that makes -the version part of the contract. If a record can be read by two people -at the same time, that field is the difference between a lost edit and a -conflict both clients can see. - -I build Java/Spring back ends and full-stack web applications — REST APIs -with JPA, optimistic locking, caching, validation and integration tests, -from the browser page down to the database. If you have a form or a field -where edits keep quietly disappearing, tell me about it: -[WhatsApp](https://wa.me/60127972969) · -[me@hoelee.com](mailto:me@hoelee.com?subject=Spring%20Boot%20help) · -[hoelee.com](https://hoelee.com). -```` - ---- - -## 文章 08 / 11:把 CodeIgniter 4 应用从 IIS 迁移到 OpenLiteSpeed -- **Slug**: `migrating-codeigniter-iis-to-openlitespeed` -- **英文标题**: Migrating a CodeIgniter 4 App From IIS to OpenLiteSpeed -- **分类**: `engineering` | **发布日期**: 2026-09-27 -- **线上地址**: https://blog.hoelee.com/posts/migrating-codeigniter-iis-to-openlitespeed/ (EN) | https://blog.hoelee.com/posts/zh/migrating-codeigniter-iis-to-openlitespeed/ (ZH) -- **本篇审核状态**: ⏳ 待审核 (Pending) - -### ✍️ 顾问审阅意见区 (Review Feedback) -```text -【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 -【事实与数字核对】: -【人设与用词卫生】: -【CRO与转化建议】: -``` - -### 🇨🇳 中文版原文 (Chinese Markdown Twin) -````markdown ---- -title: "把 CodeIgniter 4 应用从 IIS 迁移到 OpenLiteSpeed" -description: "我把一个 17,000 行的 CodeIgniter 4 应用从 Windows IIS 搬到了 CyberPanel 上的 OpenLiteSpeed。迁移后冒出两个致命错误——而 IIS 一直靠 SSO 把它们藏着。" -pubDate: 2026-09-27 -category: engineering -blueprint: sme-digital-suite -blueprintLayer: L1-high-conversion-web -tags: [codeigniter, php, openspeedway, cyberpanel, iis, migration, litespeed, linux] -ogImage: /og/zh-migrating-codeigniter-iis-to-openlitespeed.jpg -banner: /banners/migrating-codeigniter-iis-to-openlitespeed.jpg -draft: false ---- - -我维护着一个数字命理报告生成器:一个 CodeIgniter 4 应用,接收出生日期和姓名,跑一遍命理引擎,渲染出 19 页 A4 报告。它在 Windows Server + IIS 上跑了很多年。2026 年 9 月,我把它迁到 CyberPanel 上的 OpenLiteSpeed,跑在 Linux 上,换了个域名。 - -迁移本身没什么好说的——拷文件、把 docroot 指向 `public/`、装依赖。真正值得写下来的是:**新主机上第一个未认证请求,就在两条路由上直接致命崩溃——而这两条路由在 IIS 上"一直好好的"。** - -两个 bug 都是真的。两个从一开始就存在于 IIS 上。两个都看不见,因为 IIS 在出问题的路由前面恰好挡了一层 authentik SSO。 - -## 为什么这件事重要 - -如果你的自托管应用前面挂了一层认证网关,那这层网关做的事不止是保护数据——它同时**在帮你藏 bug**。任何"只对未认证用户出错"的东西永远不会以未认证身份运行,所以永远不会报错。而它会在最糟的时刻暴露:你迁移的时候、你拆掉网关的时候、你把路由暴露到公网的时候。 - -我这个应用,就"健康"了整整几年。我把新域名指过去的那一刻,两条路由返 HTTP 500。代码一行没改。唯一变的是网关没了。 - -两个修复加起来大概二十分钟。找到它们花了两个小时——因为真正的错误信息被 CodeIgniter 的 CLI 错误渲染器挡在了后面。 - -## 环境 - -这是一个相当普通的 CI4 项目,但有一个不太常见的架构细节:报告引擎不是库,而是**同一台主机上的 HTTP 端点**。控制器拼一个请求,`curl` 回自己域名的 `/api/single`,引擎返回算好的 JSON 数值,控制器再把它渲染成可打印的报告。 - -正是这个"自调用"设计,让 IIS 上必须有 `CONST_IIS_INTERNAL_BASE`。这点我后面会回来说——它才是真正有意思的部分。 - -| | 迁移前 | 迁移后 | -|---|---|---| -| 操作系统 | Windows Server | Ubuntu (CyberPanel) | -| Web 服务器 | IIS | OpenLiteSpeed 1.9.0 | -| PHP | 8.4 (Windows 版) | 8.4.25 (lsphp84) | -| Docroot | `C:\inetpub\calc.hoelee.com` | `/home/<域名>/public_html/public` | -| 认证网关 | authentik SSO 挡 `/lifecode`、`/api/*` | 无 | - -## 第一步:docroot 指向 `public/`,不是项目根目录 - -CI4 是两段式目录结构。`app/`、`vendor/`、`writable/` 和 `.env` 都在项目根目录,只有 `public/` 本该对 Web 可见。 - -CyberPanel 建的站点根目录叫 `public_html`。我的第一反应是把整个项目解压进 `public_html`,docroot 不动。 - -**那样会把 `app/`、`vendor/`、`.env` 文件和 `writable/` 的 session 数据全部暴露在 HTTP 之下。** 这个项目的 `.env` 里有一个 webhook 凭证。任何人猜到 `/../.env`——或者干脆直接请求 `/.env`,因为这文件就躺在被服务的目录下面——就拿到了。 - -正确做法是解压进 `public_html`,然后把 vhost 的 docroot 往下一层,改成 `public_html/public`: - -```bash -# 解压成 app/、vendor/、.env 位于 public_html 之下 -cd /home/<域名>/public_html -tar -xzf /tmp/deploy.tar.gz - -# docroot 必须是 public_html/public,不是 public_html -sudo sed -i 's#/home/<域名>/public_html\$#/home/<域名>/public_html/public#' \ - /usr/local/lsws/conf/vhosts/<域名>/vhost.conf - -sudo /usr/local/lsws/bin/lshttpd -t -sudo systemctl restart lsws -``` - -这是整个迁移里最重要的一步,也是大多数教程跳过的一步。其他什么都不做,这一步也得做。 - -## 第二步:IIS 藏起来的两个致命错误 - -### 致命错误一 —— `env()` 调用得太早 - -第一个 500 完全没有响应体。这不太寻常——CI4 正常会渲染点东西出来。一个空白的 500 通常意味着 PHP 在框架的错误处理器装上之前就死了。 - -CI4 的启动流程会在 `Boot::bootWeb()` 里很早加载 `app/Config/Constants.php`(通过 `Boot::loadConstants()`)。而这件事发生在 **`Common.php` 助手文件加载之前**——`env()` 就定义在那个文件里。 - -所以这一行: - -```php -// app/Config/Constants.php —— 错误写法 -define('CONST_fullBase', env('hoelee.fullBase')); -``` - -会失败于: - -``` -Fatal error: Uncaught Error: Call to undefined function env() -in app/Config/Constants.php:96 -``` - -规则是绝对的:**`Constants.php` 里只能放普通常量。** 不能有 `env()`、不能有 `getenv()`、不能有配置助手。如果你真需要依赖环境的值,就定义到启动流程更靠后的位置——或者把这个常量降级成 fallback,真正的值后面再读。 - -我做的正是后者。`CONST_fullBase` 变回普通字符串,消费它的助手函数改为**先**查框架自己的 `app.baseURL`(那个才是 `.env` 驱动的): - -```php -// app/Helpers/hoelee_helper.php -function getFullBase(bool $selfCall = false): string -{ - // .env 驱动的 baseURL 优先;CONST_fullBase 只是 fallback - if ($selfCall && defined('CONST_IIS_INTERNAL_BASE') && CONST_IIS_INTERNAL_BASE) { - return rtrim(CONST_IIS_INTERNAL_BASE, '/'); - } - $appBase = config('App')->baseURL; - if ($appBase) return rtrim($appBase, '/'); - if (defined('CONST_fullBase') && CONST_fullBase) return rtrim(CONST_fullBase, '/'); - return ''; -} -``` - -**这个是我自己搞出来的。** 同一周做凭证清理重构时引入的——我把一个硬编码 URL 挪进 `.env`,然后在 `Constants.php` 里用 `env()` 读它。在我机器上是通的,因为本地 `.env` 走的是另一条路径被读到。干净启动下它从来没通过。我是在**部署测试**后一小时内抓到的;如果只是代码审查,很可能就这么放过去了。 - -### 致命错误二 —— CI4 控制器里的 `parent::__construct()` - -第二个失败在 `/lifecode`。这个是应用里**原本就存在**的 bug,不是我引入的。 - -绕过 CLI 渲染器之后,真正的报错是: - -``` -Error: Cannot call constructor -``` - -CI4 的基础类 `CodeIgniter\Controller` **根本没有构造函数**。它实现的是 `initController()`,由框架把 request、response、logger 三个对象传进去。标准写法是: - -```php -// CI4 的正确写法 -public function initController( - RequestInterface $request, - ResponseInterface $response, - LoggerInterface $logger -) { - parent::initController($request, $response, $logger); - // 你的初始化代码 -} -``` - -但 `Lifecode.php` 和 `ApiEn.php` 用的是传统构造函数,还在调 `parent::__construct()`: - -```php -// 错误 —— CodeIgniter\Controller 没有 __construct() -public function __construct() -{ - parent::__construct(); - // ... -} -``` - -对一个没有定义 `__construct()` 的父类调 `parent::__construct()`,在 PHP 8 里是致命错误。把两个控制器改成 `initController()` 就修好了——同时要为新签名补上三个 interface 的 `use` 语句。 - -我没有盲信报错信息,而是先确认父类**确实**没有构造函数: - -```bash -grep -n 'function __construct\|function initController' \ - vendor/codeigniter4/framework/system/Controller.php -``` - -只出来 `initController()`。这一步值得做——"Cannot call constructor" 在父类**有**构造函数但内部报错时也会出现,重写签名之前你得先搞清楚自己是哪种情况。 - -## 为什么这两个 bug 在 IIS 上都不出现 - -这是让我改变部署观念的部分。 - -在 IIS 主机上,`/lifecode` 和 `/api/*` 挡在 authentik SSO 后面。对这两条路由的未认证请求返回 **HTTP 302 跳转到 `auth.hoelee.com`**——压根不会碰到控制器。那个坏掉的构造函数从来没被执行过。这条路由大概从写出来那天就是坏的,而它从来没被要求真正处理过一次请求。 - -我直接对比了两台主机来确认: - -```bash -curl -sI https://calc.hoelee.com/lifecode | head -1 -# HTTP/2 302 <- authentik 跳转;控制器根本没运行 - -curl -sI http://<新主机>/lifecode | head -1 -# HTTP/1.1 500 <- 没有网关;控制器运行并致命崩溃 -``` - -那个 302 就是这个 bug 活下来的原因。应用看起来健康,只是因为它不健康的部分根本触不到。 - -**教训说白了就是:一条路由前面挂了认证网关,就意味着这条路由自己的代码没有任何有效的测试覆盖。** 如果你要迁移或者拆网关,请专门留出时间,用未认证身份把每一条曾被网关挡着的路由都打一遍,再宣布迁移完成。小应用上这只是十行 `curl` 循环。在我这里,它本来几秒钟就能找出这两个 bug,而不是两个小时: - -```bash -for p in / /read/single /read/partner /lifecode /api/date /api/single; do - printf '%-16s %s\n' "$p" "$(curl -s -o /dev/null -w '%{http_code}' https://<主机>$p)" -done -``` - -## 第三步:那个不再是 loopback 的自调用 - -现在是这个架构里真正有意思的后果。 - -报告引擎是靠控制器 `curl` 自己的主机来调用的。在 IIS 上,`CONST_IIS_INTERNAL_BASE` 把这个调用指向 `http://localhost:7296`——loopback 接口,请求不出机器,也不碰 DNS 和 TLS。 - -在 LiteSpeed 上这个常量被**故意不定义**,于是 `getFullBase()` 落到 `app.baseURL`。这意味着每一次生成报告,现在都是**一个真实的对外 HTTPS 请求,打到应用自己的公网 URL,再从 Cloudflare 绕回来**。 - -那问题就来了:这到底能不能跑? - -答案是能,但值得专门测一次,因为它的失败模式很容易误导人。这是确切的测法——**在服务器上跑**,不是在你的笔记本上: - -```bash -curl -s -o /dev/null -w 'HTTPS self-call: %{http_code}\n' \ - -X POST 'https://<域名>/api/single' -d 'nameCn=test&dob=1990-01-01' -``` - -两个要注意的地方: - -- **在服务器上跑。** 我从 Windows 机器上打同一个 URL,拿到的是 404 和 500——那是我这台机器 DNS 解析和 Cloudflare 机器人防护的产物,不是服务器的问题。在错误的主机上测试,会得出很有把握的错误结论。 -- **看 JSON,不只看状态码。** 一个 200 配一个被截断的 body,比干脆失败更糟。我在信任之前先确认了响应能被解析。 - -这里藏着一个真实的取舍,我还没完全解决:走公网 URL 的自调用意味着生成报告依赖 Cloudflare 在线、每次报告多一次 TLS 握手、并且在整个过程中占用两个 PHP worker。在 LiteSpeed 上 worker 池不大的情况下,并发报告一多就可能死锁——每个请求都在等另一个请求,而后者拿不到空闲 worker。以目前的流量没问题。但在规模上去之前,这个自调用应该换成绕过 CDN 的内部路径。 - -## 第四步:验证真实产出,不是状态码 - -`/` 返 200 只证明落地页能渲染。它不证明报告引擎能用,而引擎才是整个产品。所以最后一步是端到端生成一份真报告: - -```bash -curl -s -X POST 'https://<域名>/read/single' \ - -d 'nameCn=test&dob=1990-01-01&gender=m' \ - -o report.html -w 'HTTP:%{http_code} bytes:%{size_download}\n' -``` - -结果:**HTTP 200、99,189 字节、19 页 A4。** 我又用中文字符输入跑了一遍,把引擎的 UTF-8 路径也走通——HTTP 200、99,205 字节、19 页、姓名渲染正常、输出里零 PHP 警告。 - -真正有意义的检查,是新旧主机之间页数可比。它证明字体、DPI 和分页逻辑都完整地熬过了这次搬迁。 - -关于那个 UTF-8 测试的插曲:我第一次跑的时候返回了 500,差点就一头扎进去查 bug。原因是我自己的 shell——中文字符在进 `curl` 的路上被终端编码搞坏了,应用收到的是非法字节。把同一个请求写成服务器上的脚本再跑,编码在我控制之内,就返回了 200。**在你调试编码故障之前,先确认服务器真正收到的字节就是你打算发出去的字节。** - -## 如果重来一次,我会怎么改 - -**迁移前就测未认证路由,而不是迁移后。** 那两个小时的排查,用一个遍历路由列表的 `curl` 循环就能完全避免。我现在把"列出所有路由、以未认证身份逐个请求、记录状态码"当成任何迁移的第零步。 - -**不要在 `Constants.php` 里调 `env()`。** 我在文件里留了注释专门写这件事,因为下一个人——多半是六个月后的我自己——一定会想这么干。 - -**迁移前先查框架版本对应的 project-space 配置。** 同一周我把 CI4 从 4.6.3 升到 4.7.4,它在两个升级指南里根本没提的属性上致命崩溃了两次:`Config\App::$permittedURIChars`(4.7 的 Router 要求)和 `Config\Format::$jsonEncodeDepth`(JSONFormatter 要求,而第二个正好打断了引擎的 JSON 自调用)。Composer 会更新 `vendor/`,但**永远**不会合并 `app/Config/*.php`,因为那些属于 project-space。我最后往 14 个配置文件里手工合并了新属性。那是另一篇文章,但迁移的教训是同一个形状:**框架会告诉你 `vendor/` 里改了什么;没有任何东西会告诉你 `app/` 里改了什么。** - -**先确认 docroot,再动别的。** 如果我解压进 `public_html` 就收手,应用是能跑的——同时静静地把 `.env` 通过 HTTP 服务出去。能跑的迁移,不等于安全的迁移。 - -## 结果 - -一个晚上。六条路由全部验证 200,中英文输入的报告产出在字节层面可比,零 PHP 警告,另外还从代码库里清掉了两个长期潜伏的 bug——而这两个 bug 一直被 IIS 的认证网关遮着。 - -应用现在跑在 OpenLiteSpeed 上,docroot 正确分离,主机可自动化管理,凭证放在 `.env` 而不是写死在常量里。 - ---- - -**想让你的应用也做这套迁移?** 我可以在 IIS、Apache、nginx 和 LiteSpeed 之间迁移 PHP 应用——包括那些麻烦的部分:自调用架构、藏 bug 的 SSO 网关,以及会碰到 project-space 配置的框架升级。 - -[WhatsApp +60 12-797 2969](https://wa.me/60127972969) · [me@hoelee.com](mailto:me@hoelee.com?subject=CodeIgniter%20迁移) · [hoelee.com](https://hoelee.com) -```` - -### 🇬🇧 英文版原文 (English Markdown Primary) -````markdown ---- -title: "Migrating a CodeIgniter 4 App From IIS to OpenLiteSpeed" -description: "I moved a 17,000-line CodeIgniter 4 app from Windows IIS to OpenLiteSpeed on CyberPanel. Two fatal errors appeared that IIS had been hiding behind SSO." -pubDate: 2026-09-27 -category: engineering -blueprint: sme-digital-suite -blueprintLayer: L1-high-conversion-web -tags: [codeigniter, php, openspeedway, cyberpanel, iis, migration, litespeed, linux] -ogImage: /og/migrating-codeigniter-iis-to-openlitespeed.jpg -banner: /banners/migrating-codeigniter-iis-to-openlitespeed.jpg -draft: false ---- - -I maintain a numerology report generator: a CodeIgniter 4 application that takes a birth date and a name, runs them through a numerology engine, and renders a 19-page A4 report. It had run on Windows Server with IIS for years. In September 2026 I moved it to OpenLiteSpeed on CyberPanel, on Linux, on a different domain. - -The migration itself was unremarkable — copy the files, point the docroot at `public/`, install dependencies. What made it worth writing about is that **the first unauthenticated request to the new host fatally crashed on two routes that had been working fine on IIS for years.** - -Both bugs were real. Both were present on IIS the whole time. Neither was visible, because IIS had an authentik SSO gate in front of the exact routes that were broken. - -## Why this matters - -If you run a self-hosted app behind an authentication gateway, your auth layer is doing more than protecting data — it is also **hiding your bugs**. Anything that only breaks for unauthenticated users never runs unauthenticated, so it never fails. The failure surfaces at the worst possible moment: when you migrate, remove the gate, or expose the route to the public internet. - -In my case the app had been reporting "healthy" for as long as I'd owned it. The moment I pointed a new domain at it, two routes returned HTTP 500. Nothing had changed in the code. The only thing that changed was that the gate was gone. - -The fix for both took about twenty minutes. Finding them took two hours, because the actual error messages were hidden behind CodeIgniter's CLI error renderer. - -## The setup - -The app is a fairly ordinary CI4 project with an unusual architecture detail: the report engine is not a library, it is a **set of HTTP endpoints on the same host**. The controllers generate a request, `curl` it back to `/api/single` on their own domain, and the engine returns JSON with the computed numbers. The controller then renders that into the printable report view. - -That self-call design is what made `CONST_IIS_INTERNAL_BASE` necessary on IIS. Let me come back to it — it turns out to be the interesting part. - -| | Before | After | -|---|---|---| -| OS | Windows Server | Ubuntu (CyberPanel) | -| Web server | IIS | OpenLiteSpeed 1.9.0 | -| PHP | 8.4 (Windows build) | 8.4.25 (lsphp84) | -| Docroot | `C:\inetpub\calc.hoelee.com` | `/home//public_html/public` | -| Auth gate | authentik SSO on `/lifecode`, `/api/*` | none | - -## Step 1: Point the docroot at `public/`, not the project root - -CI4 ships with a two-folder layout. `app/`, `vendor/`, `writable/` and `.env` live in the project root. Only `public/` is meant to be web-accessible. - -CyberPanel creates the document root as `public_html`. My first instinct was to extract the whole project into `public_html` and leave the docroot alone. - -**That would have exposed `app/`, `vendor/`, the `.env` file, and `writable/` session data over HTTP.** The `.env` in this project contains a webhook credential. Anyone who guessed `/../.env` — or just fetched `/.env`, since the file sits directly under a served directory — gets it. - -The correct layout is to extract into `public_html` and then repoint the vhost docroot one level deeper, at `public_html/public`: - -```bash -# extract the project so that app/, vendor/ and .env sit UNDER public_html -cd /home//public_html -tar -xzf /tmp/deploy.tar.gz - -# the docroot must be public_html/public, NOT public_html -sudo sed -i 's#/home//public_html\$#/home//public_html/public#' \ - /usr/local/lsws/conf/vhosts//vhost.conf - -sudo /usr/local/lsws/bin/lshttpd -t -sudo systemctl restart lsws -``` - -This is the single most important step in the migration, and it is the one most guides skip. If you do nothing else, do this. - -## Step 2: The two fatals IIS was hiding - -### Fatal 1 — `env()` called too early - -The first 500 had no body at all. That is unusual — CI4 normally renders something. An empty 500 usually means PHP died before the framework's error handler was installed. - -CI4's bootstrap loads `app/Config/Constants.php` very early in `Boot::bootWeb()`, via `Boot::loadConstants()`. That happens **before** the `Common.php` helper file is loaded, which is where `env()` is defined. - -So this line: - -```php -// app/Config/Constants.php — BROKEN -define('CONST_fullBase', env('hoelee.fullBase')); -``` - -fails with: - -``` -Fatal error: Uncaught Error: Call to undefined function env() -in app/Config/Constants.php:96 -``` - -The rule is absolute: **`Constants.php` may only contain plain constants.** No `env()`, no `getenv()`, no config helper. If you need environment-dependent values there, define them further along the bootstrap — or make the constant a fallback and read the real value later. - -That is exactly what I did. `CONST_fullBase` became a plain string, and the helper that consumes it checks the framework's own `app.baseURL` (which *is* `.env`-driven) first: - -```php -// app/Helpers/hoelee_helper.php -function getFullBase(bool $selfCall = false): string -{ - // the .env-driven baseURL wins; CONST_fullBase is only a fallback - if ($selfCall && defined('CONST_IIS_INTERNAL_BASE') && CONST_IIS_INTERNAL_BASE) { - return rtrim(CONST_IIS_INTERNAL_BASE, '/'); - } - $appBase = config('App')->baseURL; - if ($appBase) return rtrim($appBase, '/'); - if (defined('CONST_fullBase') && CONST_fullBase) return rtrim(CONST_fullBase, '/'); - return ''; -} -``` - -**This one was my own doing.** I had introduced it during a secrets-cleanup refactor in the same week — I moved a hardcoded URL into `.env` and called `env()` in `Constants.php` to read it. It worked on my machine because the local `.env` was being read through a different path. It never worked on a clean boot. I caught it within an hour *only because* I deployed and tested; a code review would plausibly have waved it through. - -### Fatal 2 — `parent::__construct()` in a CI4 controller - -The second failure was on `/lifecode`, and this one is a genuine pre-existing bug in the application — not something I introduced. - -The error, once I got past the CLI renderer, was: - -``` -Error: Cannot call constructor -``` - -CI4's base `CodeIgniter\Controller` class **has no constructor**. It implements `initController()`, which the framework calls with the request, response, and logger objects. The standard pattern is: - -```php -// correct CI4 pattern -public function initController( - RequestInterface $request, - ResponseInterface $response, - LoggerInterface $logger -) { - parent::initController($request, $response, $logger); - // your setup here -} -``` - -But `Lifecode.php` and `ApiEn.php` declared a classic constructor and called `parent::__construct()`: - -```php -// BROKEN — CodeIgniter\Controller has no __construct() -public function __construct() -{ - parent::__construct(); - // ... -} -``` - -`parent::__construct()` on a parent class that does not define `__construct()` is a fatal in PHP 8. Converting both controllers to `initController()` fixed it — and required adding the three `use` statements for the interface types in the new signature. - -I checked whether the base class *really* had no constructor rather than trusting the error message: - -```bash -grep -n 'function __construct\|function initController' \ - vendor/codeigniter4/framework/system/Controller.php -``` - -Only `initController()` came back. Worth doing — "Cannot call constructor" also fires when a parent *has* a constructor that errors internally, and you want to know which case you are in before you rewrite the signature. - -## Why neither bug showed up on IIS - -This is the part that changed how I think about the deployment. - -On the IIS host, `/lifecode` and `/api/*` sat behind authentik SSO. An unauthenticated request to either returned **HTTP 302 to `auth.hoelee.com`** — it never reached the controller at all. The broken constructor was never executed. The route had presumably been broken since it was written, and it had never once been asked to serve a request. - -I confirmed this by comparing the two hosts directly: - -```bash -curl -sI https://calc.hoelee.com/lifecode | head -1 -# HTTP/2 302 <- authentik redirect; controller never runs - -curl -sI http:///lifecode | head -1 -# HTTP/1.1 500 <- no gate; controller runs and fatals -``` - -The 302 is why the bug survived. The app looked healthy because the unhealthy parts were unreachable. - -**The lesson, stated plainly: an auth gate in front of a route means that route has no working test coverage for its own code.** If you migrate or remove the gate, budget time to hit every previously-gated route unauthenticated before you call the migration done. On a small app that is a ten-line `curl` loop. Here it would have found both bugs in seconds instead of two hours: - -```bash -for p in / /read/single /read/partner /lifecode /api/date /api/single; do - printf '%-16s %s\n' "$p" "$(curl -s -o /dev/null -w '%{http_code}' https://$p)" -done -``` - -## Step 3: The self-call that stops being a loopback - -Now the interesting architectural consequence. - -The report engine is reached by the controller `curl`-ing its own host. On IIS, `CONST_IIS_INTERNAL_BASE` pointed that call at `http://localhost:7296` — the loopback interface — so the request never left the machine and never touched TLS or DNS. - -On LiteSpeed that constant is deliberately left **undefined**, so `getFullBase()` falls through to `app.baseURL`. Which means every report generation now makes a **real outbound HTTPS request to the app's own public URL** and comes back in through Cloudflare. - -Which raises the obvious question: does that work at all? - -The answer is yes, but it is worth testing explicitly, because the failure mode is confusing. Here is the exact test — run it **on the server**, not from your laptop: - -```bash -curl -s -o /dev/null -w 'HTTPS self-call: %{http_code}\n' \ - -X POST 'https:///api/single' -d 'nameCn=test&dob=1990-01-01' -``` - -Two things to watch for: - -- **Run it from the server.** From my Windows machine the same URL returned 404 and 500 — an artefact of DNS resolution and Cloudflare bot protection on my caller, not a server problem. Testing from the wrong host produces confident, wrong conclusions. -- **Watch the JSON, not just the status code.** A 200 with a truncated body is worse than a clean failure. I checked the response was parseable before trusting it. - -There is a real trade-off hiding here, and I have not fully resolved it: a public-URL self-call means report generation depends on Cloudflare being up, costs a TLS handshake per report, and occupies two PHP workers for the duration. On LiteSpeed with a small worker pool, a burst of concurrent reports could deadlock — each request waiting on another request that has no free worker. For the current traffic level it is fine. Before this scales, the self-call should move to an internal path that bypasses the CDN. - -## Step 4: Verify the actual output, not the status code - -A 200 on `/` proves the landing page renders. It does not prove the report engine works, and the engine is the entire product. So the last step was generating a real report end to end: - -```bash -curl -s -X POST 'https:///read/single' \ - -d 'nameCn=test&dob=1990-01-01&gender=m' \ - -o report.html -w 'HTTP:%{http_code} bytes:%{size_download}\n' -``` - -The result: **HTTP 200, 99,189 bytes, 19 A4 pages.** I ran it again with Chinese-character input to exercise the UTF-8 path through the engine — HTTP 200, 99,205 bytes, 19 pages, name rendering correctly, zero PHP warnings in the output. - -Byte-comparable page counts between the old and new host is the check that matters. It proves the fonts, the DPI, and the pagination logic all survived the move. - -A side note on the UTF-8 test: my first attempt at it returned a 500 and I nearly went bug-hunting. The cause was my own shell — the Chinese characters were being mangled by the terminal encoding on the way into `curl`, so the app received invalid bytes. Running the same request from a script on the server, where the encoding is under my control, returned 200. **Before you debug an encoding failure, confirm the bytes actually arriving at the server are the bytes you meant to send.** - -## What I'd do differently - -**Test unauthenticated routes before migrating, not after.** The whole two-hour debugging session was avoidable with a `curl` loop over the route list. I now treat "list every route, hit it unauthenticated, record the status" as step zero of any migration. - -**Do not call `env()` in `Constants.php`.** I have left a comment in the file itself saying so, because the next person — probably me in six months — will be tempted. - -**Check the framework version's project-space config before the move.** The same week, I upgraded CI4 from 4.6.3 to 4.7.4, and it fataled twice on properties the upgrade guide did not mention: `Config\App::$permittedURIChars`, required by the 4.7 Router, and `Config\Format::$jsonEncodeDepth`, required by the JSONFormatter — the second of which broke the engine's JSON self-call specifically. Composer updates `vendor/` but never merges `app/Config/*.php`, because those are project-space files. I ended up merging new properties into 14 config files. That is a separate post, but the migration lesson is the same shape: **the framework tells you what changed in `vendor/`; nothing tells you what changed in `app/`.** - -**Confirm the docroot before anything else.** If I had extracted into `public_html` and stopped, the app would have worked — and quietly served `.env` over HTTP. A migration that works is not the same as a migration that is safe. - -## The result - -One evening. Six routes verified 200, byte-comparable report output on both Chinese and ASCII input, zero PHP warnings, and two long-standing latent bugs removed from the codebase that IIS had been concealing behind an auth gate. - -The app is now running on OpenLiteSpeed with a properly separated docroot, on a host I can automate, with the credential in `.env` rather than a constant. - ---- - -**Want this done for your own application?** I migrate PHP applications between IIS, Apache, nginx and LiteSpeed — including the awkward parts: self-calling architectures, SSO gates that hide bugs, and framework upgrades that touch project-space config. - -[WhatsApp +60 12-797 2969](https://wa.me/60127972969) · [me@hoelee.com](mailto:me@hoelee.com?subject=CodeIgniter%20migration) · [hoelee.com](https://hoelee.com) -```` - ---- - -## 文章 09 / 11:用「热浏览器会话」爬取有反爬墙的电商网站 -- **Slug**: `scraping-bot-walled-marketplace-warm-browser-session` -- **英文标题**: Scraping a Bot-Walled Marketplace With a Warm Browser Session -- **分类**: `engineering` | **发布日期**: 2026-09-13 -- **线上地址**: https://blog.hoelee.com/posts/scraping-bot-walled-marketplace-warm-browser-session/ (EN) | https://blog.hoelee.com/posts/zh/scraping-bot-walled-marketplace-warm-browser-session/ (ZH) -- **本篇审核状态**: ⏳ 待审核 (Pending) - -### ✍️ 顾问审阅意见区 (Review Feedback) -```text -【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 -【事实与数字核对】: -【人设与用词卫生】: -【CRO与转化建议】: -``` - -### 🇨🇳 中文版原文 (Chinese Markdown Twin) -````markdown ---- -title: "用「热浏览器会话」爬取有反爬墙的电商网站" -description: "为一位做二手手机生意的客户:爬取有反爬墙的电商商品列表——热 CDP 会话、失败即止的健康检查、分段等待渲染。" -pubDate: 2026-09-13 -category: engineering -tags: ["scraping", "cdp", "headless-chrome", "anti-bot", "shopee", "python"] -ogImage: "/og/zh-scraping-bot-walled-marketplace-warm-browser-session.jpg" -banner: "/banners/scraping-bot-walled-marketplace-warm-browser-session.jpg" -draft: false ---- - -一位客户请我做一个听起来很简单的东西:每天把一个大电商平台上的二手手机列出来,按价格排序,好让他的进货决策靠数据而不是靠感觉。这位客户靠倒卖二手电子产品吃饭——一台手机差几百马币就是他的利润。 - -结果完全不是一段干净的 `requests` + BeautifulSoup 脚本。它变成了一场长达一周的、跟反爬墙的拉锯战,一个靠胶带勉强粘在一起的热浏览器会话,以及——我们俩都没想到的部分——一个关于「你不能靠堆更多 agent 来『并行化』爬虫」的惨痛教训。 - -这就是那个故事,按照我经历的顺序来讲:问题、我试过却失败的每一件事、最终奏效的办法,以及下次我会怎么做。 - -## 问题,用别人真正会搜索的方式表述 - -> "如何从一个拦截无头浏览器的网站爬取商品列表?" - -或者更诚实地说:**当一个电商网站已经把「防爬」当成它唯一的本职工作,你要怎么爬它?** Shopee 不会礼貌地把 HTML 喂给 `curl`。它会检测自动化、抛出一个 `/verify` 验证码,然后静默地给你一个「看起来正常但里面什么都没有」的页面。 - -客户的需求清单很短: - -- 搜索二手手机,只筛选「二手」成色,存储 128 GB 及以上。 -- 提取每个商品的所有存储规格和价格。 -- 按价格升序排序。 -- 不搞一百个 headless 实例的 `chromedriver` 农场——倒卖的利润养不起一百个住宅 IP,我的也一样。 - -从这里开始,全部都是调试故事。 - -## 我试过的,以及为什么失败 - -### 尝试 1:通过 CDP 用冷的无头 Chrome——「直接把 Chrome 远程调试开起来」 - -我用 `--headless --remote-debugging-port=9222` 启动了 Chrome,用 Chrome DevTools Protocol 连上去,然后导航到搜索 URL。大约十秒钟里我觉得自己很聪明。 - -**失败:** 页面加载了,但每个商品卡片都是空的。DOM 是个空壳。Shopee 指纹识别了这个无头浏览器(没有真正的 GPU、user-agent 指纹不一致、`navigator.webdriver` 标志),把我重定向进了一个我永远过不去的 `/verify` 验证码循环。冷的无头 profile 一上来就撞墙。 - -教训很无聊但很重要:**如果你的浏览器本身在「身份」上撒谎,选择器写得再好也没用。** - -### 尝试 2:并行子 agent——「直接开 N 个 worker」 - -这是我最想让它成功的方案。我有一套多 agent 的架构。本能反应就是:开五个 agent,每个爬一个不同的搜索词,收集结果,合并。 - -**失败:** 它们全都连到**同一个**浏览器会话上。它们不会各自拿到一个浏览器——只会各自拿到共享 Chrome 实例里的一个标签页,或者更糟:全都挤在同一个标签页上。每一次 `Page.navigate` 都会把上一个 agent 的上下文抹掉。而且关键在于: - -1. **热会话是共享资源。** 只有一个没被标记的 Canary profile。五个 agent 交错访问同一个标签页,在 Shopee 眼里,跟一个浏览器疯狂快速导航没有区别。而这恰恰是**触发**反爬墙的行为。 -2. **反爬的「节奏」是累积的。** 我的可用方案依赖导航之间约 7 秒的间隔来显得像真人。五个 agent 并发导航,就等于五个导航以零间隔打向同一个会话。 - -所以「横向扩展」的本能——加更多 worker——对我赖以存活的那件事(看起来像真人)是有害的。这里的并发上限不是 CPU 也不是内存,而是**一个热浏览器,一次一个标签页。** - -### 尝试 3:靠「Buy With Voucher」按钮来拿价格 - -一旦列表能渲染出来了,我假设购买按钮的文案里带着价格。大多数电商网站确实如此。但这个渲染出来的按钮写的是 `Add To Cart` / `Buy Now`。我用来匹配「Buy With Voucher … RM…」的正则什么都匹配不到,我在原地打转了好一会儿,才真正去读了 DOM。 - -**失败:** Shopee 商品页的价格不在按钮里。它被渲染成**拆分的 span**——`RM` 在一个元素里、`850` 在另一个里、`00` 又在另一个里——所以朴素的叶子文本匹配只会抓到碎片,或者当商品有多个规格时,抓到一个**区间**(`RM850.00 - RM1150.00`)。 - -### 尝试 4:点击规格选项来拿精确价格 - -对于单轴规格选择器(比如一个存储下拉:128GB / 256GB / 512GB),点击一个选项会把价格收敛成单个值,我的提取方法能正常工作。 - -**失败:** 对于**双轴**选择器(品牌 × 存储),点击第一个轴(某个品牌)会锁定一个价格,但加上第二个轴(某个存储规格)又把它**解散**回商品全区间。这个面板渲染的是「所有可购买组合」的区间,而不是我选中的那个具体组合;而且「已选中」状态是用一个「同时匹配其他所有选项框」的 class 来标记的。我没法可靠地知道我到底锁定了哪个组合。 - -我在这个上面花了实打实的时间,最后才接受这个诚实的答案:**对于真正的双轴商品,正确的数据是价格区间,而不是一个瞎猜的「每个组合」数字。** 发布一个「有时候能用」的脆弱覆盖方案,比老实报告一个区间更糟糕。 - -## 修复——真正奏效的东西 - -三块,都很小,都是吃了亏才学会的。 - -### 1. 热的人性化节奏的浏览器会话(地基) - -别跟墙硬刚。用一个已经登录过、正常浏览过的浏览器 profile——一个「热」profile。用真实的 7 秒间隔来导航。它更慢,但它是唯一能稳定活下来的方式。 - -```python -# 不是真正的代码——是它的「形状」。先导航,然后像真人一样等待。 -goto_url(target) -time.sleep(7) # 真人节奏,不可妥协 -wait_for_selector(".shopee-search-item-result__item") -``` - -### 2. 失败即止,别傻等超时 - -在任何爬取之前,先打 CDP 的 HTTP 端点,检查会话状态。如果 Canary 挂掉了、或标签页停在 `/verify` 上,就在约 1 秒内中止,而不是在「怎么还不渲染」的超时里浪费 40 秒。 - -```python -import json, urllib.request - -def session_healthy(): - try: - tabs = json.load(urllib.request.urlopen("http://127.0.0.1:9222/json")) - except Exception: - return False - for t in tabs: - if t.get("type") == "page" and "/verify" in t.get("url", ""): - return False # 撞到验证码墙——重新热会话,别爬了 - return True -``` - -就这么一个改动,把「静默的 40 秒死胡同」变成了「即时、可执行的失败」。 - -### 3. 正确的价格选择器:最深的纯 RM 节点 - -购买按钮是个谎言。价格是**那个文本内容纯粹是一个 RM 值的、最深的元素**——在选中规格之前是一个区间(`RM850.00 - RM1150.00`),之后是单个值(`RM850.00`)。遍历 DOM,取文本能匹配上的最深元素: - -```python -import re - -RM = re.compile(r"^RM\s?[\d,.]+(\s?[-–]\s?RM\s?[\d,.]+)?$") - -def find_price(root): - best, depth = None, -1 - for el in root.querySelectorAll("*"): - txt = (el.textContent or "").strip() - if txt and RM.match(txt) and " " not in txt.split("RM")[0]: - d = depth_of(el) - if d > depth: - best, depth = el, d - return best.textContent.strip() if best else None -``` - -这就是全部的诀窍。没有脆弱的 class 名。没有瞎猜。一个「整个文本就是一个价格」的节点,就是价格本身。 - -## 结果——一个可量化的成果 - -从单个热会话、一次串行遍历中,我提取了 **20+ 个二手手机商品及其各规格价格**,筛选到 128 GB 及以上,按价格升序排序。最便宜的真实目标——一台 128GB 机型——以 **RM299** 的价格浮出水面,另外还有几台 128/256GB 的选项在 RM450–880 区间。现在一条命令(`sweep.py ...`)就能重新检查整份候选清单并输出 JSONLines;客户每天进货前跑一次。 - -但我最庆幸的数字是这个:**零验证码。** 「热会话 + 人性化节奏 + 失败即止」这套组合,在整次遍历中一次都没触发过 `/verify`。 - -## 下次我会怎么做 - -1. **我会一开始就写「失败即止」的健康检查**,在任何爬取代码之前。三十秒的活,换来未来每次失败省四十秒。 -2. **我会从第一天就抵抗并行化的冲动。** 「爬虫太慢」的答案是把更多工作打包进一次串行遍历(批量搜索、对多个 URL 跑 `sweep.py`),而不是「再加 worker」。共享的浏览器状态让并发变得更糟,而不是更好。 -3. **我会立刻接受双轴的限制**,老实报告区间,而不是在一个根本没法可靠化的选择器上烧一个下午。 -4. **我会别再猜 DOM 结构,先去探测它。** 几乎每一个错误假设(URL 路径里 `/i.` vs `-i.`、把 `Buy With Voucher` 当价格锚点、「过滤器是个真正的 `` 复选框」)都来自**没有先读真实的 DOM**。 - -## 可复用的部分 - -所有这一切被做成了一个小的独立工具集——每个脚本都是一次自包含的 `python x.py ...` 调用: - -| 脚本 | 作用 | -|---|---| -| `search.py` | 粗粒度搜索 → 商品卡片 | -| `used_search.py` | 点击「二手」条件复选框,校验 URL 里的 `USED_ITEM`,再提取 | -| `detail.py` | 从商品页提取各规格价格(最深 RM 节点法 + 分段等待) | -| `sweep.py` | 一次会话内对 N 个 URL 做批量详情提取,按 item-id 去重,写 JSONLines,打印表格 | -| `cdp_common.py` | 共享的健康检查 + 导航辅助 | - -真正可复用的教训不是那些 Shopee 专属的选择器——而是**姿态**:**假设页面在 DOM 上撒谎,失败即止,用批量化而不是并行 worker 来扩展。** - ---- - -*这是一次真实的调试过程,不是事后补写的教程。这个爬虫工具集、以及这里的每一次失败,都发生在为一个做二手电子产品倒卖的客户构建它的过程中——我保留了能泛化的部分,砍掉了那些只对某个马来西亚电商网站、某个时间点有效的部分。* - ---- - -## 想为你的业务做这个吗? - -我做定制爬虫和数据提取管道——热会话 CDP 爬虫、反爬墙感知的采集器、批量价格监控扫描——也做全栈 Web 应用(PHP/CodeIgniter、Java/Spring、React/TypeScript)和自托管自动化(n8n、Telegram 机器人、NAS 上的 Docker)。 - -如果你需要从某个「会反抗」的网站拿商品或价格数据,直接点进来,告诉我你想提取什么: - -- 💬 [WhatsApp](https://wa.me/60127972969) — 直接私信我 -- ✉️ [Email](mailto:me@hoelee.com?subject=Custom%20scraping%20pipeline) — 告诉我网站和数据 -- 🌐 [hoelee.com](https://hoelee.com) — 看看我还做了些什么 -```` - -### 🇬🇧 英文版原文 (English Markdown Primary) -````markdown ---- -title: "Scraping a Bot-Walled Marketplace With a Warm Browser Session" -description: "Scraping bot-walled marketplace listings for a client's used-electronics business: warm CDP session, fail-fast health checks, split-wait rendering." -pubDate: 2026-09-13 -category: engineering -tags: ["scraping", "cdp", "headless-chrome", "anti-bot", "shopee", "python"] -ogImage: "/og/scraping-bot-walled-marketplace-warm-browser-session.jpg" -banner: "/banners/scraping-bot-walled-marketplace-warm-browser-session.jpg" -draft: false ---- - -A client asked me to build something that sounds simple: every day, list the second-hand phones on a big marketplace, sorted by price, so their restocking decisions come from data instead of gut feel. The client resells used electronics for a living — a few hundred ringgit either way on a phone is the whole margin. - -The result was nothing like a clean `requests` + BeautifulSoup script. It was a week-long fight against an anti-bot wall, a warm browser session held together with duct tape, and — the part neither of us saw coming — a hard lesson about why you cannot just "parallelize" a scraper by throwing more agents at it. - -This is that story, told in the order I lived it: the problem, everything I tried that failed, the thing that finally worked, and what I'd do differently. - -## The problem, phrased the way someone would actually search it - -> "How do I scrape product listings from a site that blocks headless browsers?" - -Or, more honestly: **how do you scrape a marketplace that has already made scraping its sole job description?** Shopee doesn't politely serve HTML to `curl`. It detects automation, throws a `/verify` captcha, and silently serves you a page that looks fine but contains nothing. - -The client's requirement list was small: - -- Search for used phones, filter to "used condition only", storage 128 GB and up. -- Extract every listing's storage variants and prices. -- Sort by price ascending. -- Do it without a `chromedriver` farm of a hundred headless instances — a reseller's margins don't pay for a hundred residential IPs, and neither do mine. - -Everything after this point is the debugging story. - -## What I tried, and why it failed - -### Attempt 1: cold headless Chrome via CDP — "just point Chrome's remote debugger at it" - -I launched Chrome with `--headless --remote-debugging-port=9222`, connected with the Chrome DevTools Protocol, and navigated to a search URL. It felt clever for about ten seconds. - -**Failure:** the page loaded, but every product card was empty. The DOM was a shell. Shopee had fingerprinted the headless browser (no real GPU, no real user-agent fingerprint consistency, `navigator.webdriver` flag) and redirected me into a `/verify` captcha loop I never got past. Cold headless profiles hit the wall immediately. - -The lesson is boring but important: **anti-bot systems don't care how good your selectors are if the browser itself is lying about what it is.** - -### Attempt 2: parallel subagents — "just spawn N workers" - -This was the one I really wanted to work. I have a multi-agent setup. The natural instinct is: spawn five agents, each scraping a different search query, gather the results, merge. - -**Failure:** all of them attach to the *same* browser session. They don't get their own browser — they get their own *tab* in one shared Chrome instance, or worse, they all fight over the same single tab. Every `Page.navigate` un-does the previous agent's context. And critically: - -1. **The warm session is a shared resource.** There is one Canary profile that isn't flagged. Five agents navigated the same tab in an interleaved order, which is indistinguishable — to Shopee — from one browser doing rapid-fire navigation. That's exactly the behavior that *triggers* the wall. -2. **Anti-bot pacing is cumulative.** My working setup depends on ~7-second gaps between navigations to look human. Five agents navigating concurrently means five navigations hitting the same session with effectively zero gap. - -So the "horizontal scaling" instinct — more workers — is actively hostile to the one thing keeping me alive: looking human. The concurrency ceiling here isn't CPU or memory. It's **one warm browser, one tab at a time.** - -### Attempt 3: trusting the "Buy With Voucher" button for the price - -Once I had listings rendering, I assumed the buy button's label contained the price. On most marketplaces it does. On this render, the button said `Add To Cart` / `Buy Now`. My regex for "Buy With Voucher … RM…" matched nothing, and I went around in circles for a while before actually reading the DOM. - -**Failure:** the price on Shopee product pages isn't in the button. It's rendered as **split spans** — `RM` in one element, `850` in another, `00` in a third — so a naive leaf-text match returns fragments, or a **range** (`RM850.00 - RM1150.00`) when the listing has multiple variants. - -### Attempt 4: clicking variant options to get an exact price - -For a single-axis variant selector (e.g. one dropdown of storage options — 128GB / 256GB / 512GB), clicking one option collapses the price to a single value, and my extraction worked. - -**Failure:** for a **two-axis** selector (brand × storage), clicking the first axis (a brand) locks a price, but adding the second axis (a storage size) *un-collapses* it back to the product-wide range. The panel renders the range of all purchasable combinations, not the exact combination I selected, and the "selected" state is marked by a class that also matches every other option box. There is no reliable way to know which combination I actually locked. - -I spent real time on this before accepting the honest answer: **for genuinely two-axis listings, the correct data is the price range, not a guessed per-combination number.** Shipping a fragile override that "sometimes works" would be worse than reporting an honest range. - -## The fix — what actually worked - -Three pieces, all small, all learned the hard way. - -### 1. A warm, human-paced browser session (the foundation) - -Don't fight the wall. Use a browser profile that has already logged in and browsed normally — a "warm" profile. Navigate with real 7-second gaps. It is slower and it is the only thing that reliably survives. - -```python -# not real code — the *shape* of it. Navigate, then wait like a human. -goto_url(target) -time.sleep(7) # human pacing, non-negotiable -wait_for_selector(".shopee-search-item-result__item") -``` - -### 2. Fail fast, don't time out - -Before any scrape, hit the CDP HTTP endpoint and check the session state. If Canary is down or the tab is sitting on `/verify`, abort in ~1 second instead of wasting 40 seconds on a "did not render" timeout. - -```python -import json, urllib.request - -def session_healthy(): - try: - tabs = json.load(urllib.request.urlopen("http://127.0.0.1:9222/json")) - except Exception: - return False - for t in tabs: - if t.get("type") == "page" and "/verify" in t.get("url", ""): - return False # captcha wall — re-warm the session, don't scrape - return True -``` - -This one change turned "silent 40-second dead-ends" into "instant, actionable failure." - -### 3. The right price selector: deepest pure-RM node - -The buy button is a lie. The price is the **deepest element whose text is a pure RM value** — a range (`RM850.00 - RM1150.00`) before a variant is selected, a single value (`RM850.00`) after. Walk the DOM and take the deepest element whose text matches: - -```python -import re - -RM = re.compile(r"^RM\s?[\d,.]+(\s?[-–]\s?RM\s?[\d,.]+)?$") - -def find_price(root): - best, depth = None, -1 - for el in root.querySelectorAll("*"): - txt = (el.textContent or "").strip() - if txt and RM.match(txt) and " " not in txt.split("RM")[0]: - d = depth_of(el) - if d > depth: - best, depth = el, d - return best.textContent.strip() if best else None -``` - -That's the whole trick. No brittle class names. No guessing. A node whose entire text *is* a price is the price. - -## The result — one quantified outcome - -From a single warm session, in one serial pass, I extracted **20+ used-phone listings with per-variant prices**, filtered to 128 GB and up, sorted by price. The cheapest real target — a 128GB model — surfaced at **RM299**, alongside several 128/256GB options in the RM450–880 range. One command (`sweep.py ...`) now re-checks the whole shortlist and dumps JSONLines; the client runs it once a day before restocking. - -But the number I'm most glad about is this: **zero captchas.** The warm-session + human-pacing + fail-fast combo survived the entire sweep without tripping `/verify` once. - -## What I'd do differently - -1. **I'd write the fail-fast health check first**, before a single scraping line. It's thirty seconds of work that saves forty seconds per future failure. -2. **I'd resist the parallelization instinct day one.** The answer to "the scraper is slow" is "bundle more work into one serial pass" (batch search, `sweep.py` over many URLs), not "more workers." Shared browser state makes concurrency worse, not better. -3. **I'd accept the two-axis limitation immediately** and report ranges, instead of burning an afternoon on a selector that can't be made reliable. -4. **I'd stop guessing DOM structure and probe it.** Almost every mistaken assumption (`/i.` vs `-i.` in the URL path, `Buy With Voucher` as the price anchor, "the filter is a real `` checkbox") came from *not reading the actual DOM first*. - -## The reusable pieces - -All of this became a small, standalone toolkit — each script is one self-contained `python x.py ...` call: - -| Script | What it does | -|---|---| -| `search.py` | Coarse search → listing cards | -| `used_search.py` | Clicks the "Used" condition checkbox, verifies `USED_ITEM` in the URL, extracts | -| `detail.py` | Pulls per-variant prices from a product page (deepest-RM-node method + split-wait) | -| `sweep.py` | Batch detail over N URLs in one session, dedupes by item-id, writes JSONLines, prints a table | -| `cdp_common.py` | Shared health check + navigation helpers | - -The genuinely reusable lesson isn't the Shopee-specific selectors — it's the *posture*: **assume the page is lying about its DOM, fail fast, and scale by batching, not by parallel workers.** - ---- - -*This is a real debugging session, not a tutorial written after the fact. The scraping toolkit and every one of these failures happened while building it for a client who resells used electronics — I kept the parts that generalize and cut the parts that only matter to one Malaysian marketplace at one point in time.* - ---- - -## Want this for your business? - -I build custom scraping and data-extraction pipelines — warm-session CDP scrapers, bot-wall-aware crawlers, and batch price-monitoring sweeps — as well as full-stack web apps (PHP/CodeIgniter, Java/Spring, React/TypeScript) and self-hosted automation (n8n, Telegram bots, Docker on NAS). - -If you need product or price data off a site that fights back, tap through and tell me what you're trying to extract: - -- 💬 [WhatsApp](https://wa.me/60127972969) — message me directly -- ✉️ [Email](mailto:me@hoelee.com?subject=Custom%20scraping%20pipeline) — tell me the site + the data -- 🌐 [hoelee.com](https://hoelee.com) — see what else I build -```` - ---- - -## 文章 10 / 11:JavaScript 文件静默失效的两种方式:而页面看上去一切正常 -- **Slug**: `two-ways-a-javascript-file-stops-working-and-looks-fine` -- **英文标题**: Two Ways a JavaScript File Stops Working and Looks Fine -- **分类**: `engineering` | **发布日期**: 2025-02-20 -- **线上地址**: https://blog.hoelee.com/posts/two-ways-a-javascript-file-stops-working-and-looks-fine/ (EN) | https://blog.hoelee.com/posts/zh/two-ways-a-javascript-file-stops-working-and-looks-fine/ (ZH) -- **本篇审核状态**: ⏳ 待审核 (Pending) - -### ✍️ 顾问审阅意见区 (Review Feedback) -```text -【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 -【事实与数字核对】: -【人设与用词卫生】: -【CRO与转化建议】: -``` - -### 🇨🇳 中文版原文 (Chinese Markdown Twin) -````markdown ---- -title: "JavaScript 文件静默失效的两种方式:而页面看上去一切正常" -description: "一个被参数名遮住的函数名,加一个声明在首次调用之后的 let,让整段脚本停摆——而页面渲染得完美好看,因为屏幕上什么都没变。" -pubDate: 2025-02-20 -updatedDate: 2026-10-16 -category: engineering -tags: ["javascript", "i18n", "debugging", "frontend"] -ogImage: /og/zh-two-ways-a-javascript-file-stops-working-and-looks-fine.jpg -banner: /banners/two-ways-a-javascript-file-stops-working-and-looks-fine.jpg -draft: false ---- - -## 一次「什么都没发生」的改动 - -我给一个自己用的媒体转码队列看板加了语言切换:三份语言包、一个 `t(key, vars)` 函数、界面 chrome 上的 `data-i18n`、顶栏一个 `` in the top bar. - -After deploying it, the page looked exactly as it had before. Not broken — -*unchanged*. Same layout, same Chinese labels, no missing panels, no error -card, no console banner. The switcher was simply not there, and neither was -anything else the new code was supposed to do. - -That is the shape of bug I want to write down, because the page was not -"mostly working". **The script had stopped executing partway through — -twice, for two unrelated one-line reasons — and the page rendered perfectly -anyway.** - -## Why nothing looked broken - -Two design decisions I would make again, and both of them hid the failure. - -The first is that the default language lives in the markup. The Chinese text -is written inside the elements; `data-i18n` is only a hook that *overrides* -it when you switch. That is deliberate — the page needs no fetch to render, -and if a language pack goes missing you get Chinese instead of a row of -`top.theme_to_dark` keys. It also means a completely dead i18n layer -produces a page that is, visually, correct. - -The second is that the buttons are wired with inline handlers -(`onclick="rtFoo()"`), which after a script abort point at functions that -were never defined. Nothing warns you. The page only reveals the truth when -a human clicks something. - -So the symptom was "my change had no effect", which is the least informative -symptom a web page can give you. - -## Failure one: a parameter that swallowed a function - -The file has a theme block and an i18n block. The theme block had this -signature: - -```js -function applyTheme(t) { // t = the theme - label.textContent = t('top.theme_to_dark'); // TypeError: t is not a function -} -``` - -`applyTheme` was written before the i18n layer existed, and `t` was a -perfectly reasonable name for "theme". When the i18n layer arrived, `t` in -that scope stopped meaning the theme and started meaning *the function I -wanted to call* — except the parameter shadows it, so the call became -"invoke a string". - -A `TypeError` at the top level of a classic script does not just fail one -line. Everything after it never runs: the language-pack loader, the -`data-i18n` sweep, the switcher rendering. One wrong letter removed an -entire feature, silently. - -The fix is one character — rename the parameter to `th` — plus a comment -where the next person will look: - -```js -function applyTheme(th) { // NOT `t`: t() is the i18n function in this file -``` - -## Failure two: a declaration that arrived too late - -The second cause was in the same file, and it is a JavaScript rule people -know and still trip over. The theme block runs at load and calls `t('…')`. -The i18n block, further down the file, began with: - -```js -let LANG = localStorage.getItem('rt_lang') || 'zh-CN'; -``` - -`let` and `const` are hoisted but **not initialised**: between the start of -the scope and that line they live in the temporal dead zone, and any access -throws `Cannot access 'LANG' before initialization`. Because the theme block -sits *above* the i18n block, the failure was not a race — it was guaranteed -on every single load. - -Note the distinction from `var`, which would have quietly given me -`undefined` and a working page. The TDZ is the language protecting me from -exactly the bug I was about to write; the only reason it looked like -"nothing happened" is the markup fallback again. - -The fix is ordering, and ordering here is a *dependency*, not a style -choice: if a block calls `t()`, the i18n declarations have to be above it. -The file had been organised by topic ("theme, then i18n") because that is -how it grew. - -## Why my checks did not catch either one - -I had tests. They checked intent, not effect: - -- the three language packs exist and parse; -- every key used in the markup exists in every pack; -- no pack contains a dead key (a typo detector); -- the `{var}` placeholder sets in the three packs match. - -All true. All green. None of them executes the page, so none of them can see -a script that aborts on line 12 of 900. Static checks are structurally -unable to catch "the file is valid and the program is dead". - -## Assert on effects, in a browser - -What found both bugs was asking the live page questions that only a running -program can answer: - -```js -typeof t === 'function' // is the entry point still callable? -document.querySelectorAll('[data-i18n]').length // hooks present -rtCheckHandlers() // do the inline handlers still resolve? -``` - -That last one is worth more than it looks. The page carries **219 inline -`onclick` attributes naming 217 distinct functions**; the check enumerates -them and asserts each name is defined on `window`. It turns a hand-clicked -smoke test into a two-second automated one, and it is the check that turns -"the page looks right" into a measurable property. - -The second tool is cheaper and nastier: a **pseudo-language**. -`?lang=pseudo` takes every string in the pack, prefixes it with `[~~` and -stretches it 1.6×. Then assert two things — no horizontal overflow at -1440px, and no element in the nav still lacks the `[~~` prefix. The first -catches layout that only breaks in a longer language; the second catches -nodes that never got a translation hook at all. It found a real one in the -same run. - -Honest scope note: a pseudo-locale does not prove your Malay translation is -*good*. It proves the *plumbing* is complete — every string flows through -the mechanism, and the layout survives length. Judgement about the words -stays with a human. - -## What I would do differently - -1. **Load the page in a real browser and assert `typeof` on the entry points - before believing a client-side refactor worked.** A dead script is - invisible to every static check you own. -2. **Never let a parameter name shadow a function the same file calls.** One - letter bought me an entire afternoon; the comment is the part that stops - it recurring. -3. **Treat declaration order as a dependency, not aesthetics.** If a block - calls a function or reads a constant, that declaration goes above it — - especially in one long script. -4. **Generate the language packs from one table.** Then "the keys match" is - a test rather than a hope, and drift cannot be merged. -5. **When a change does nothing, suspect the script before the change.** - "Nothing happened" is the default failure mode of a rendered page, not - evidence that your code was inert. - -## The result - -Two one-line causes, both in the same file, both found by browser-side -assertions rather than by reading code again. The dashboard switches -language at runtime now, the default render is byte-for-byte what it was -before the change, and the three packs come from a single generated table — -so a missing key shows up as a red test instead of as a word that quietly -stays Chinese. - -The generalisation is the part I keep: **a crash tells you where to look. A -silent stop tells you nothing, and looks like success.** If a feature can -fail without moving a single pixel, then "the page still looks right" is not -a check. -```` - ---- - -## 文章 11 / 11:逐页验证一份 19 页的 PDF 报告 -- **Slug**: `verifying-a-pdf-report-page-by-page` -- **英文标题**: Verifying a 19-Page PDF Report Page by Page -- **分类**: `engineering` | **发布日期**: 2026-09-28 -- **线上地址**: https://blog.hoelee.com/posts/verifying-a-pdf-report-page-by-page/ (EN) | https://blog.hoelee.com/posts/zh/verifying-a-pdf-report-page-by-page/ (ZH) -- **本篇审核状态**: ⏳ 待审核 (Pending) - -### ✍️ 顾问审阅意见区 (Review Feedback) -```text -【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 -【事实与数字核对】: -【人设与用词卫生】: -【CRO与转化建议】: -``` - -### 🇨🇳 中文版原文 (Chinese Markdown Twin) -````markdown ---- -title: "逐页验证一份 19 页的 PDF 报告" -description: "如何逐页验证生成的 PDF 报告:用浏览器打印同一份 HTML 作基线,逐页比对几何尺寸,把每一处偏差都压到 2pt 以内。" -pubDate: 2026-09-28 -updatedDate: 2026-09-29 -category: engineering -blueprint: sme-digital-suite -blueprintLayer: L4-managed-ops-handover -tags: [php, codeigniter, pdf, css, print, testing] -ogImage: /og/zh-verifying-a-pdf-report-page-by-page.jpg -banner: /banners/verifying-a-pdf-report-page-by-page.jpg -draft: false ---- - -你怎么知道一份生成出来的 PDF 每一页都真的正确——不只是第一页? -我维护着一个 CodeIgniter 4 应用:输入一个人的出生信息,生成一份 -中文命理/生命密码报告——十九张密排的 A4 sheet,封面、数字图表、 -方向九宫格、「一到九」的个人特征页。以前这份报告按网站原本的设计 -交付:操作员在浏览器里按 Ctrl+P,手工另存成 PDF。我把它换成了 -服务端渲染(mPDF),一夜之间,产品的质量取决于一个我看不见 -如何排版的引擎。 - -这就是这个问题可被搜索的版本:如何把一份多页 PDF 报告逐页地、 -用数字而不是肉眼,去和浏览器自己的打印输出对版?这个过程抓到 -了真实的 bug——包括一行被渲染成 2.5pt、从第二页起几乎看不见的 -页眉——最后全部十九页与浏览器基线的偏差都压进了 2pt。 - -## 为什么「看起来没问题」不算测试 - -没有人能用肉眼验证一份 19 页的报告。过去的流程是:打开 PDF, -扫一眼封面,交付。第 17 页标题漂移、页脚插图压住版权行、页眉 -小到读不出来——快速翻一遍永远发现不了,而花钱买报告的顾客 -看到的是全尺寸。 - -天真的做法会失败,是结构性的原因。服务端 PDF 渲染器不会像 -浏览器那样排你的 HTML:分页、页边距、基线、字距全都会漂移—— -而且不存在一个「看起来没问题」的测试,能让你在下周有人改了 -CSS 之后再跑一次。我第一次单趟渲染出来是 27 页,而设计预期 -是 19 页:mPDF 没有 CSS 裁剪,而 sheet 靠 `overflow: hidden` -藏住溢出。报告的 `@page` 规则更糟:mPDF 为这条规则本身 -翻了一页,19 张 sheet 炸成 12,789 页。页数都不稳定,所以 -「扫一眼第一页」不是验证——是碰运气。 - -## 基线:让浏览器去打印你的 HTML - -操作员的 Ctrl+P,就是 Chrome 用打印 CSS 打印报告自己的 HTML。 -所以参照标准不是「我觉得它应该长什么样」,而是浏览器自己的 -打印输出——在同一台机器、同一套网页字体下生成。做法:把报告 -目录用本地静态服务起起来(字体必须同源,否则 webfont 拒绝 -加载),再用 headless Chrome 打印。报告 CSS 声明了 -`@page { margin: 0 }`,所以浏览器输出是无边距满幅,再配合 -`-webkit-print-color-adjust: exact` 保住背景图——等价于操作员 -勾选「背景图形」: - -```bash -python -m http.server 8123 --bind 127.0.0.1 --directory - -"C:\Program Files\Google\Chrome\Application\chrome.exe" --headless=new --disable-gpu \ - --no-pdf-header-footer --user-data-dir=%TEMP%\chromeprofile --virtual-time-budget=30000 \ - --print-to-pdf=chrome-win.pdf "http://127.0.0.1:8123/report-local.html" -``` - -然后在 VM 上,用同一份 HTML 出服务端版本: - -```bash -php tools/pdf-render.php /tmp/report-v10.html /tmp/mpdf.pdf -``` - -## 逐页比对,而不是整体对比 - -以浏览器的 PDF 为基准,我在 Windows 这边用 -`uv run --with pymupdf` 逐页对比两份文档:页面尺寸、文字条数、 -图片包围盒(x0/y0/宽/高)、附图说明文字的 y 坐标。判定阈值: -**偏差 ≤2pt(0.7mm)算对齐**;超过 5pt 就要查根因。而且只比 -「同一元素在两份 PDF 里的差」——永远不要比绝对页数,因为页数 -一致是前提,不是测试本身。 - -## 逐页比对抓到了什么 - -下面每个 bug 都有可测量的前后数字,而且都修在库或模板里—— -不是用管道糊过去。 - -**看不见的页眉行。** 从第二页起每页顶部有一行小字,用户直接 -反馈说小到读不出来。页眉是一个 `font-size: 10px` 的 div, -里面套一张 auto 宽的 table,第一格写着 `width: 100%`。mPDF -把这解读成「表格超宽」,于是连同字号一起把整行缩到三分之一: -**2.5pt,而 Chrome 是 7.5pt**。修法(`fixPageHeaderTables()`): -给表格显式宽度 + 显式字号(px→pt),并去掉第一格的 -`width: 100%`: - -```php -$pt = round((float) $m[2] * 0.75, 2); // 10px = 7.5pt -``` - -**匹配过宽的外边距规则。** `.sheet { margin: 5mm auto }` 是为 -屏幕预览准备的(sheet 之间的阴影缝隙)。mPDF 当真了,把 -296mm 的 sheet 推到 301mm——越过 297mm 的页面——于是 sheet -在页边被切开,auto-fit 把整页缩小 3%,带白边。最直观的修法、 -在样式表末尾追加一条 `.sheet { margin: 0; }`,完全没用:mPDF -对同名选择器的两条规则只认「先出现的赢」。所以库要原地改写 -这条规则(`stripSheetMargins()`),而匹配器必须小心什么才算 -「sheet 规则」。护栏是一个负向回顾断言: - -```php -'~(?` 标签 -居中,而 mPDF 8 的 `Center` 标签处理器是空类——标签整个被 -丢弃,所有居中的标题和表格全部左对齐(「前言」实测 x=30, -Chrome 是 x=280)。`expandCenterTags()` 把 `
` 改写成 -`
`,并给居中块里的表格补上 -`align="center"`——因为父级的 `text-align` 传不到表格。 -修复后:x=281,Chrome 280。 - -**行距比浏览器高 15%。** 模板的 normalize.css 声明了 -`html { line-height: 1.15 }`;mPDF 不继承它,退回自己的字体 -度量(1.33)。这累积成每页下半部 20–40pt 的漂移——sheet 3 -甚至溢出到第二页,触发整页缩小。把 `useFixedNormalLineHeight` -设成模板自己的值之后,正文行距 15.5pt,Chrome 是 15.7。 -表格还要显式加 `td, th { padding: 1px }`——mPDF 默认的 -单元格内边距比浏览器大 2px。 - -**字体是错的。** mPDF 读不了网页用的 `.woff`,文字回退到 -自带的 Sun-ExtA;而正文栈里的「微软雅黑」在 Linux 服务器上 -根本不存在。我注册了三套真 TTF——标题手写体 MaShanZheng、 -拉丁与数字 Roboto、正文 CJK 用 wqy-microhei——并把模板的 -字体栈映射过去。一个坑:必须关掉 mPDF 的自动按脚本选字, -否则它挑「第一个支持中文的已注册字体」——整页正文都变成 -手写体。 - -**还有一个与 mPDF 无关的 bug。** 第 7 页的主插图在**两份** -PDF 里都是破图——比对显示 Chrome 和 mPDF 里是同一个破损 -占位块。模板硬编码了 `https://cdn.hoelee.com/...`,这个域名 -已经不再解析(NXDOMAIN),所以每个引擎都抓不到图。把模板 -改回应用自己的 base URL,并让 `localiseAssets()` 把任何 -host 的 `/static/` 路径都映射到本地文件,两个引擎里的插图 -都恢复了。只有并排比对才能暴露这一类 bug——单独看哪个引擎 -都「正常」。 - -## 一张 sheet,一页 - -渲染器这么设计是有意的:库把 HTML 按 `
` -切开,每张 sheet 单独渲染成一份单页文档,合并时只取第 1 页—— -物理上保证「一张 sheet = 正好一页 A4」,永远不会跨页断裂。 -mPDF 量中文宽度和 Chrome 略有不同,个别 sheet 会高出几毫米。 -与其丢内容,库按一把缩放梯子——1.0, 1.005, 1.01, 1.02, 1.03, -1.06, 1.10, 1.15, 1.22——取第一个能落进一页的比例,缩小整张 -sheet 而不是裁内容。隐藏溢出是浏览器打印做的事 -(`overflow: hidden`);一份收费产品如果 PDF 里静默丢了页内 -内容,就是无声的交付事故,所以设计选择是绝不丢内容。sheet 3 -现在需要 x1.005——0.5%,肉眼不可见——以前是 x1.03。 - -**「19/7 页」是什么意思。** 报告模板永远按固定顺序渲染十九张 -sheet;「版本」是这些 sheet 上的一个过滤器,不是第二份模板。 -完整版是 **19 页**;RM49 的精华版是**这 19 张里的 7 张**, -页码重编,每张入选的 sheet 都登记了一个文字标记——模板被 -改动/重排导致取错页时会大声失败,而不是把错误的章节交给 -顾客。两个版本走同一条管线,也用同一种方式验收: -`tools/pdf-verify.php --expect=19` 和 -`--expect=7` 双双 PASS -——页数加逐页 ink 检查(ghostscript 50dpi)证明没有任何 -空白页。 - -## 为什么收据是独立文档 - -收据不是报告裁剪出来的。它是自己的一份单页 A4 文档:真 -16mm 页边距(报告刻意做满幅无边距)、三语、单趟渲染—— -因为里面没有 sheet。它在发「已收款」邮件时才懒生成:付款 -回调必须毫秒级应答,0.3–1 秒的 PDF 渲染不属于回调。它落进 -同一个交付存储,文件名带 `-receipt` 后缀,永远不会和报告 -文件撞名,而且幂等:重试、重寄、顾客自己来拿,拿到的都是 -同一份。做它的过程从另一个方向印证了同一个论点——连单页 -文档都和浏览器不一样:`` 上的 `display: block` -不生效,左右并排的两张表把右列的数值裁出页面右边界, -合计行必须写在明细表内部,否则标签会浮在半空。 - -## 我会怎么做不一样 - -对版方法现在躺在项目笔记里,是一份文档化的流程,不是仓库 -里的脚本——这就是差距。仓库里自动化的验收工具只证明页数和 -逐页 ink,永远抓不到 2.5pt 的页眉或 15% 的行距漂移。我会把 -浏览器基线比对做成仓库验证工具链里的一个脚本:用同一份 -HTML 分别喂 Chrome 和库,diff 几何,任何超过 5pt 的偏差 -直接失败。这样,一次让打印布局悄悄回退的 CSS 改动会在构建 -时炸掉,而不是送到顾客手里。 - -我还会在写任何 mPDF 补偿代码之前就先出 Chrome 基线。 -「用操作员用的同一个引擎打印,然后测量」才是解锁点;之后 -每个修复都是机械活。还有两件诚实的遗留工作:伴侣合盘与 -家庭套餐还没跑过这套逐页对版,19 页的 PDF(背景图加嵌入 -字体约 20 MB)也还需要在交付前压缩。 - -## 结果 - -修复后的完整版验收: - -```text -$ php tools/pdf-verify.php /tmp/report-v10.html --expect=19 -out : 20,225,818 bytes, 19 pages, 10.4s, peak 188 MB -per-page ink check: all pages have content | report pages=19 -expected 19 pages => MATCH -RESULT: PASS -``` - -- **19 页 vs Chrome 基线的 19 页 — MATCH**,一张 sheet 一页, - 无跨页断裂。 -- 每一项实测偏差都**在 2pt(0.7mm)以内**:第 6 页偏了 - 213.5pt 的页脚插图、从 2.5pt 恢复到浏览器同款 7.5pt 的 - 页眉、归位的居中标题、15.5pt vs Chrome 15.7 的正文行距、 - 与网页字体一致的嵌入字体。 -- ink 检查确认**没有任何空白页**,PDF 文字可提取——封面能 - 读出真实文字,这对一份顾客要复制内容的报告很重要。 -- 精华版:**7 页 PASS**,4.99 MB,2.8 秒。 - -这就是「第一页看起来没问题」和「全部十九页都在浏览器两个点 -以内」的区别。前者是肉眼扫一遍就交付的结果;后者是拿浏览器 -自己当测试得到的结果。 - ---- - -我平时就做这类 Web 应用与打印/PDF 报告管线,也做网站设计与 -开发。如果你有一份服务器渲染的文档——报告、收据、发票—— -想在它送到顾客手里之前确认每一页都正确,跟我说说: -[WhatsApp](https://wa.me/60127972969) · [me@hoelee.com](mailto:me@hoelee.com?subject=PDF%20report%20pipeline) · -[hoelee.com](https://hoelee.com)。 -```` - -### 🇬🇧 英文版原文 (English Markdown Primary) -````markdown ---- -title: "Verifying a 19-Page PDF Report Page by Page" -description: "Verify a PDF report page by page: print the same HTML from your browser as a baseline, compare the per-page geometry, and keep every deviation under 2pt." -pubDate: 2026-09-28 -updatedDate: 2026-09-29 -category: engineering -blueprint: sme-digital-suite -blueprintLayer: L4-managed-ops-handover -tags: [php, codeigniter, pdf, css, print, testing] -ogImage: /og/verifying-a-pdf-report-page-by-page.jpg -banner: /banners/verifying-a-pdf-report-page-by-page.jpg -draft: false ---- - -How do you know a generated PDF actually looks right on every page — not just -page one? I maintain a CodeIgniter 4 app that turns birth details into a -Chinese numerology report. Until recently the operator printed it with Ctrl+P -and saved a PDF by hand. I replaced it with a server-side renderer (mPDF), and -overnight the product's quality depended on a layout engine I could not see. - -This post is the searchable version of that problem: verifying a multi-page -PDF report page by page against the browser's own print output, with numbers -instead of eyeballs. It caught real bugs — a header line rendered at 2.5pt, -effectively invisible on every page after the first — and ended with all -nineteen pages within 2pt of the browser. - -## Why "looks fine" is not a test - -Nobody can verify a 19-page report by eye. The old ritual was: open the PDF, -skim the cover, ship it. A drifting heading on page 17, a footer illustration -over the copyright line, an unreadable header — a quick flick never catches -those, and the customer who paid sees them at full size. - -Naive approaches fail structurally. A server-side PDF renderer does not lay -out HTML the way a browser does, so page breaks, margins, baselines and -spacing all drift — and there is no "looks fine" test you can re-run after -someone edits the CSS. My first single-pass render came out as 27 pages where -the design expects 19 — mPDF has no CSS clipping and the sheets hide overflow -with `overflow: hidden`. The report's own `@page` rule was worse: mPDF emitted -a page break for the rule itself, and 19 sheets exploded into 12,789 pages. -Page counts were not even stable, so eyeballing page one was not verification; -it was hope. - -## The baseline: make the browser print your HTML - -The operator's Ctrl+P is Chrome printing the report's own HTML with its print -CSS — same machine, same web fonts. So the reference is not "what I think it -should look like"; it is the browser's own print output. I served the report -directory locally (fonts must be same-origin or webfonts refuse to load) and -printed with headless Chrome. The report CSS declares `@page { margin: 0 }`, -so the output is borderless full-bleed, and `-webkit-print-color-adjust: -exact` keeps the background graphics the operator ticks: - -```bash -python -m http.server 8123 --bind 127.0.0.1 --directory - -"C:\Program Files\Google\Chrome\Application\chrome.exe" --headless=new --disable-gpu \ - --no-pdf-header-footer --user-data-dir=%TEMP%\chromeprofile --virtual-time-budget=30000 \ - --print-to-pdf=chrome-win.pdf "http://127.0.0.1:8123/report-local.html" -``` - -Then the server-side output, from the same HTML, on the VM: - -```bash -php tools/pdf-render.php /tmp/report-v10.html /tmp/mpdf.pdf -``` - -## Compare page by page, not overall - -I compared the two PDFs page by page with `uv run --with pymupdf`: page size, -text-block count, image bounding boxes (x0/y0/width/height), and caption text -y. Threshold: **within 2pt (0.7mm) counts as aligned**; over 5pt gets a root -cause. Compare the same element across the two PDFs — never absolute page -counts; page parity is the prerequisite, not the test. - -## What the comparison caught - -Each bug below had a measurable before/after and a fix in the library or -template. - -**The invisible header line.** A user reported the small header line, present -on every page after the cover, was unreadable. It is a `font-size: 10px` div -wrapping an auto-width table whose first cell declares `width: 100%` — mPDF -read that as "table too wide" and scaled the whole line, font included, to a -third of its size: **2.5pt vs Chrome's 7.5pt**. `fixPageHeaderTables()` gives -the table an explicit width and font size in points (px → pt) and drops the -offending cell: - -```php -$pt = round((float) $m[2] * 0.75, 2); // 10px = 7.5pt -``` - -**The margin rule that matched too much.** `.sheet { margin: 5mm auto }` -spaces the sheets on screen. mPDF took it literally and pushed the 296mm sheet -to 301mm — past the 297mm page — so the sheet was cut at the page edge and -auto-fit shrank the whole page by 3%, white border included. Appending `.sheet -{ margin: 0; }` does nothing — mPDF honours the *first* rule for a duplicated -selector. So the library rewrites the rule in place (`stripSheetMargins()`), -and the matcher must not over-match — the guard is a negative lookbehind: - -```php -'~(?` tag; mPDF 8's `Center` handler is an empty class, so the tag is -dropped and every centred heading and table came out left-aligned (the preface -heading measured x=30 against Chrome's x=280). `expandCenterTags()` rewrites -`
` to `
` and adds `align="center"` to -tables inside centred blocks, because parent `text-align` does not reach -tables. After the fix: x=281, Chrome 280. - -**Line spacing 15% taller than the browser's.** The template's normalize.css -declares `html { line-height: 1.15 }`; mPDF does not inherit it and fell back -to its own font metrics (1.33) — 20–40pt of drift accumulated on the lower -half of every page, and sheet 3 overflowed onto a second page, triggering a -whole-page shrink. Setting `useFixedNormalLineHeight` to the template's own -value brought body leading to 15.5pt against Chrome's 15.7. Tables needed `td, -th { padding: 1px }` — mPDF's default cell padding is 2px larger than a -browser's. - -**The fonts were wrong.** mPDF cannot read the `.woff` files the web views -use, so text fell back to its built-in Sun-ExtA, and "Microsoft YaHei" does -not exist on the Linux server. I registered the real TTFs — MaShanZheng for -headings, Roboto for Latin, wqy-microhei for CJK — and mapped the template's -stacks onto them. One trap: mPDF's automatic script-to-font selection must be -off, or it picks the first registered font that supports Chinese — the entire -body came out in handwriting. - -**And one bug that had nothing to do with mPDF.** Page 7's main illustration -was broken in *both* PDFs — the same broken stub in Chrome and mPDF. The -template hardcoded `https://cdn.hoelee.com/...`, a domain that no longer -resolves (NXDOMAIN), so every engine fetched nothing. Fixing the template to -use the app's own base URL and mapping any host's `/static/` path to local -files restored it in both engines. Only a side-by-side comparison surfaces -this — each engine alone looks "fine". - -## One sheet, one page - -The library splits the HTML into its `
` blocks and -renders each sheet as its own one-page document, importing page 1 and merging -— a physical guarantee that one sheet is exactly one A4 page, never split -across pages. mPDF measures CJK text widths slightly differently from Chrome, -so some sheets come out a few millimetres too tall. Rather than lose content, -the library re-renders the sheet at the smallest scale factor from a ladder — -1.0, 1.005, 1.01, 1.02, 1.03, 1.06, 1.10, 1.15, 1.22 — that fits, shrinking -the whole sheet instead of clipping. The browser's print clips with `overflow: -hidden`; a PDF that silently dropped in-sheet content would be a delivery -accident, so the design never drops content. Sheet 3 needs x1.005 today (0.5%, -invisible) where it used to need x1.03. - -**What "19/7 pages" means.** The report template always renders nineteen -sheets in a fixed order; the "edition" is a filter over those sheets, not a -second template. The full report is **19 pages**; the RM49 essence edition is -**7 of those 19 sheets**, renumbered, each selected sheet carrying a marker so -a rearranged template fails loudly instead of shipping the wrong chapters. -Both editions run the same pipeline and verify the same way: -`tools/pdf-verify.php --expect=19` and `--expect=7` both PASS — page count -plus a per-page ink check (ghostscript at 50dpi) proving no blank pages. - -## Why the invoice is a separate document - -The receipt is not a cut-down report. It is its own one-page A4 document: real -16mm page margins (the report is deliberately full-bleed), three languages, -and a single-pass render because there are no sheets. It is generated lazily -at email time — the payment callback must answer in milliseconds, and a 0.3–1s -render does not belong in it. It lands in the same delivery store under a -`-receipt` filename, never colliding with the report file, and it is -idempotent: retries get the same file. Even one page differed from the -browser: `display: block` on `` was ignored, side-by-side tables -clipped the right column's values off the page edge, and the total row had to -live inside the items table or its label floated in mid-air. - -## What I'd do differently - -The method lives in the project notes as a documented ritual, not a committed -script — that is the gap. The repo's automated acceptance tool proves page -count and per-page ink, which would never catch a 2.5pt header or a 15% -leading drift. I would turn the browser-baseline comparison into a script in -the repo's verification tooling: render the same HTML in Chrome and in the -library, diff the geometry, fail on any deviation over 5pt. Then a CSS change -that silently regresses the print layout fails the build instead of reaching a -customer. - -I would also have generated the Chrome baseline before writing any mPDF -compensation code — "print with the same engine the operator uses, then -measure" was the unlock. Two honest items remain: the partner and family -reports have not had this page-by-page pass yet, and the 19-page PDF (20 MB -with backgrounds and embedded fonts) still needs compression before delivery. - -## The result - -Full report verification, after the fixes: - -```text -$ php tools/pdf-verify.php /tmp/report-v10.html --expect=19 -out : 20,225,818 bytes, 19 pages, 10.4s, peak 188 MB -per-page ink check: all pages have content | report pages=19 -expected 19 pages => MATCH -RESULT: PASS -``` - -- **19 pages vs the Chrome baseline's 19 — MATCH**, one A4 page per sheet, - no splits. -- Every measured deviation is **within 2pt (0.7mm)** of the browser's print - output: footer art 213.5pt off on page 6 aligned, header restored to the - browser's 7.5pt, centred headings back, leading 15.5pt vs 15.7, embedded - fonts matching the web fonts. -- The ink check confirms **no blank pages**, and the PDF text is extractable — - the cover reads back as real text, which matters for a report customers - copy from. -- Essence edition: **7 pages PASS**, 4.99 MB, 2.8 seconds. - -That is the difference between "the first page looks fine" and "all nineteen -pages within two points of the browser": the first ships when you eyeball a -PDF; the second is what you get when the browser itself is the test. - ---- - -I build web applications and print/PDF report pipelines like this one, and I -do website design and development. If you have a document your server renders -— a report, a receipt, an invoice — and you want to be sure it is right on -every page before it reaches a customer, tell me about it: -[WhatsApp](https://wa.me/60127972969) · -[me@hoelee.com](mailto:me@hoelee.com?subject=PDF%20report%20pipeline) · -[hoelee.com](https://hoelee.com). +- **WhatsApp**: [012-7972969](https://wa.me/60127972969) +- **Email**: [me@hoelee.com](mailto:me@hoelee.com?subject=Inquiry%20regarding%20AI%20Audio%20Pipeline) +- **Website**: [hoelee.com](https://hoelee.com) ```` --- diff --git a/docs/consultant-review/batches/batch-07.md b/docs/consultant-review/batches/batch-07.md index 8b0754c..fd7fb75 100644 --- a/docs/consultant-review/batches/batch-07.md +++ b/docs/consultant-review/batches/batch-07.md @@ -1,10 +1,10 @@ # 博客文章顾问审阅资料包 — Batch-07 > **批次编号**:`Batch-07` -> **包含文章数**:16 篇 -> **本批次总字符量**:168,304 字(严格限制 < 200,000 字) +> **包含文章数**:5 篇 +> **本批次总字符量**:159,503 字(严格限制 < 200,000 字) > **模式**:BILINGUAL -> **生成时间**:2026-10-27 03:02:03 +> **生成时间**:2026-10-27 04:23:31 # 外部顾问审阅前置须知与工程背景规范 @@ -39,30 +39,19 @@ ## 本批次文章目录索引 -1. [engineering] **30 天提交 51.8 万行,生产环境只留下 23.5 万行** (`why-500000-lines-of-commit-churn-only-left-230000-in-production`) — ~12,919 字符 -2. [notes] **给别人家的邮件服务器加一个域名** (`adding-a-domain-to-someone-elses-mail-server`) — ~10,624 字符 -3. [notes] **你好,世界 —— 关于这个博客** (`hello-world`) — ~2,749 字符 -4. [notes] **我的备份爬得比爬虫还慢,因为我在用别人的 API 配额** (`my-backup-was-using-someone-elses-api-quota`) — ~12,287 字符 -5. [notes] **NocoDB SSO 是授权功能:环境变量不会告诉你的事** (`nocodb-sso-is-a-licensed-feature`) — ~15,352 字符 -6. [notes] **与其看供应商文档,不如直接读容器自带的 API 文档** (`reading-a-containers-own-api-docs`) — ~13,865 字符 -7. [notes] **smartctl 退出码 32:专门跳过你最该看的硬盘的那个“错误”** (`smartctl-exit-code-32-skips-the-disks-that-matter`) — ~8,382 字符 -8. [notes] **确定性的活,别再用 Agent Prompt 去跑** (`stop-writing-agent-prompts-for-deterministic-work`) — ~7,167 字符 -9. [notes] **密码正确,Synology API 登录却返回 401,问题出在哪** (`synology-api-401-with-the-correct-password`) — ~8,106 字符 -10. [notes] **NocoDB 附件字段怎么改都不生效,和一个漏网的正则** (`the-nocodb-attachment-that-wouldnt-update`) — ~5,726 字符 -11. [notes] **CodeIgniter 4.6 升级到 4.7:官方指南没说到的破坏性变更** (`upgrading-codeigniter-46-to-47`) — ~14,880 字符 -12. [notes] **为什么本地语音合成一直在念 “Percent”?语音管线里的 URL 编码与沙盒避坑记** (`why-is-my-tts-model-repeating-percent`) — ~11,915 字符 -13. [notes] **为什么多个 AI 一起写代码总会烂尾?传话失真与隐式决策困境** (`why-multi-agent-coding-fails`) — ~8,640 字符 -14. [notes] **为什么你的 Windows 桌面 MCP 调用会静默失败:攻破 10 秒空闲门禁与避坑实录** (`why-your-windows-mcp-calls-silently-fail`) — ~8,459 字符 -15. [tutorials] **校准 Intel Quick Sync HEVC:28 与 30 之间的悬崖,和一个毫无作用的 preset** (`calibrating-intel-quick-sync-hevc-quality`) — ~16,121 字符 -16. [tutorials] **转成 HEVC 到底会不会让文件变小?我实测了** (`does-hevc-actually-shrink-your-files`) — ~11,112 字符 +1. [tutorials] **给没有时间戳的歌曲自动生成字幕** (`generating-subtitles-for-songs-without-timestamps`) — ~88,620 字符 +2. [tutorials] **购买主机前,如何核实一家服务商的真实情况** (`how-to-verify-a-hosting-provider-before-you-buy`) — ~9,649 字符 +3. [web3] **一个基于 Chainlink VRF v2.5 与 Automation 的自动化彩票合约** (`chainlink-vrf-v2-lottery-contract`) — ~25,244 字符 +4. [web3] **全链上 SVG NFT:把艺术作品放进合约里** (`fully-on-chain-svg-nfts`) — ~24,005 字符 +5. [web3] **为什么在 Windows 上克隆后,我的链上 NFT 图像变了** (`why-my-on-chain-nft-art-changed-on-windows`) — ~11,985 字符 --- -## 文章 01 / 16:30 天提交 51.8 万行,生产环境只留下 23.5 万行 -- **Slug**: `why-500000-lines-of-commit-churn-only-left-230000-in-production` -- **英文标题**: I Committed 518,000 Lines in 30 Days. Production Kept 235,000. -- **分类**: `engineering` | **发布日期**: 2026-10-18 -- **线上地址**: https://blog.hoelee.com/posts/why-500000-lines-of-commit-churn-only-left-230000-in-production/ (EN) | https://blog.hoelee.com/posts/zh/why-500000-lines-of-commit-churn-only-left-230000-in-production/ (ZH) +## 文章 01 / 05:给没有时间戳的歌曲自动生成字幕 +- **Slug**: `generating-subtitles-for-songs-without-timestamps` +- **英文标题**: Generating Subtitles for Songs That Ship Without Timestamps +- **分类**: `tutorials` | **发布日期**: 2026-10-20 +- **线上地址**: https://blog.hoelee.com/posts/generating-subtitles-for-songs-without-timestamps/ (EN) | https://blog.hoelee.com/posts/zh/generating-subtitles-for-songs-without-timestamps/ (ZH) - **本篇审核状态**: ⏳ 待审核 (Pending) ### ✍️ 顾问审阅意见区 (Review Feedback) @@ -76,4485 +65,3641 @@ ### 🇨🇳 中文版原文 (Chinese Markdown Twin) ````markdown --- -title: "30 天提交 51.8 万行,生产环境只留下 23.5 万行" -description: "过去 30 天,自主编程 Agent 在 5 个仓库中累计新增了 51.8 万行代码,但最终留存仅 23.5 万行。为什么在 AI 时代,验证闸门与代码剪枝比生成速度重要十倍?" -pubDate: "2026-10-18" -category: "engineering" +title: "给没有时间戳的歌曲自动生成字幕" +description: "AI 音乐工具只给你音频 —— 没有逐行时间,没有卡拉 OK。这是我给 18 首歌生成 LRC 与 SRT 字幕的完整流程,为什么单纯转写不行,以及让歌词框滚到底的两个 bug。" +pubDate: 2026-10-20 +category: tutorials blueprint: ai-agent-automation -blueprintLayer: L2-llm-gateway-agents -tags: ["ai", "git", "devops", "testing", "refactoring"] -ogImage: "/og/zh-why-500000-lines-of-commit-churn-only-left-230000-in-production.jpg" -banner: "/banners/why-500000-lines-of-commit-churn-only-left-230000-in-production.jpg" ---- - -上周我做了一件平时几乎不会做的事:数了数自己的提交。不是数我记得写过的那些,而是数仓库里真实记录下来的那些。自建 Gitea 上 5 个生产仓库、三十天、一个人:865 次 Commit、新增 518,233 行、删除 130,892 行。 - -然后我数了数活下来的部分。对主生产项目的最新版本跑一次干净扫描,有效代码总量是 234,976 行;同一时间窗口里净增 58,240 行的视频转码器,今天整个仓库只有 43,050 行。 - -那 28 万行进哪儿去了?没有丢。它们被写出来、跑过测试、被判为不对,然后删掉——或者被一个更小、做同一件事的东西替换掉。我想把这条循环记下来,因为它这一年对我工作方式的影响,比任何一次模型升级都大。 - -## 一开始我不信的这几个数字 - -以下是 2026 年 9 月 17 日至 10 月 17 日,名下 5 个活跃仓库的精确 Git 统计: - -| 仓库名称 | 30 天 Commit | 累计新增 (+Add) | 累计删除 (-Del) | 净变动 (Net) | 当前存量有效代码/文本 | 核心技术栈 | -|---|---|---|---|---|---|---| -| **numerology-report** | 432 | +331,672 | -98,937 | +232,735 | **234,976** | PHP, Markdown, JSON | -| **hevc-transcode** | 187 | +58,240 | -15,508 | +42,732 | **43,050** | Python, HTML, Shell | -| **dsm-resource-management** | 132 | +58,234 | -14,076 | +44,158 | **368,793** | Python, TypeScript, Astro | -| **hoelee-blog** | 88 | +23,603 | -709 | +22,894 | **55,933** | Astro, TypeScript, Markdown | -| **hoelee-agent-dist** | 26 | +46,484 | -1,662 | +44,822 | *(Dist)* | Python, Shell, Markdown | -| **合计** | **865** | **+518,233** | **-130,892** | **+387,341** | — | — | - -其中两行你可以自己复算,这就是完整的量法: - -```bash -git -C numerology-report log --since=2026-09-17 --until=2026-10-17 \ - --numstat --pretty=format: | awk '{add+=$1; del+=$2} END {print add, del}' -``` - -在人类团队里,这样的更替量通常意味着出事了:需求在代码底下不停移动、有人偷偷在重写、架构反复塌陷。这几种情况我一条都不占——这 5 个仓库都是我每天在跑、离不开的东西,每一次提交都发生在能读到 diff 的会话里。 - -生成成本变低之后,这种更替量就是重构的样子:Agent 起草一段改动,我跑闸门,闸门不同意,这段就被丢掉或者改小重写。凡是闸门写对的那几天,代码总量往下掉得比功能上来的速度还快。 - -## Agent 实际接手的是什么 - -大多数人第一次让 AI 写代码,是在一个浏览器标签页里:把函数粘进对话框,再把答案拷回编辑器。这条路的瓶颈是剪贴板,而且模型离真正重要的两样东西都很远——仓库自己的约定,以及运行它刚写出来的东西的能力。 - -所以我的是跑在终端里、跑在这台机器上的,手里有真工具: - -1. **文件与语法工具**:直接读已有模块,用模糊匹配打补丁而不是整文件覆盖,保存前先过语法与 AST 校验。 -2. **测试与执行器**:PHPUnit 单元测试、pytest 套件、无头 Chrome 探针,在前台跑起来并把输出读回来。 -3. **版本控制上下文**:读 `git diff`、显式暂存指定路径、翻一个文件的历史看上一个决定为什么这么做。 - -这套组合很快,比我亲手打第一版快一个数量级;但它本身也是让代码库腐烂得更快的方法——这一半通常没人提醒。 - -## 臃肿是从哪里长出来的 - -不受约束的模型天生爱写代码。给它一个细小的边界情况,它的第一反应是新建一个私有辅助类、把一个已有工具函数复制一份改个参数,或者给一个库套上三层抽象——那三层只有在这段 diff 里才讲得通。放它自己跑一周,就是几千行语气笃定、看起来合理、其实没必要的代码。 - -我这么讲是因为我自己的历史里就有那一周。每天读这些 diff,最后落成两条规矩: - -- 新建一个类,要跟一个我本来就有的标准库调用竞争位置。 -- 生成出来的东西默认有罪,直到某个确定性检查说它没问题。模型说「看起来对」不算证据,红的测试才算。 - -## 真正把代码删掉的是三道闸门 - -在最近一次主生产系统的 V2 架构重构中,三十天里删掉了 98,000 多行。这些几乎不是我坐下来专门去删的,而是三道闸门不断把回来的东西打回,最后留下的就是更小的版本: - -### 1. 用确定性脚手架,而不是问「这段看着对不对」 - -让模型审查自己写的代码,多数时候产出的是自信,不是正确。有用的做法是把它接到一个没法被说服成绿灯的东西上: - -- PHP 应用里,所有公开路由参数必须带显式默认值,由专用的反射探针(`ControllerAutoRouteSafetyTest.php`)守着——这个测试存在,是因为一条裸路由在生产上真的 500 过。 -- 报告生成管线里,无头 PDF 解析器先数一遍渲染出的汉字数量,数不对就不许构建通过;这样字体或排版改动如果悄悄漏字,就是构建失败,而不是发出一份坏 PDF。 -- 转码队列里,台账比的是精确字节数而不是 MB 估算,因为圆整过的数字把一次体积回退藏了好几个星期。 - -闸门红了,Agent 要么改到过,要么把这段撤掉。没有任何东西能豁免。 - -### 2. 把剪枝当成日常动作,而不是一次大扫除 - -每次会话都会分出一段时间专门删东西:这个 200 行的辅助类,能不能换成一行已有的原生调用?这个新的映射层,是不是在重复 `app/Libraries/` 里放了一年的某个函数?上面那 13 万行删除不是重写的副产品,而是活过头了的脚手架、只有一个调用方的迁移层,以及换了名字出现两遍的同一段逻辑。 - -### 3. 确定性的活留给确定性代码 - -我在 AI 项目里反复看到的坑,是让模型去做它根本不该碰的计算。如果一条 Shell 管道、一个 SQL 约束、一个幂等脚本或者一个 Cron 任务就能给出答案,那 LLM 就不该出现在那里。 - -模型擅长起草初始实现、生成三语词库、摸清三方 API 的脾气;但状态流转、钱、队列调度,我不会交给它——一个确定性问题上概率性的答案,是一颗带延时引信的 bug。 - -## 我的工作方式变了什么 - -我职业生涯的大部分时间里,物理瓶颈是打字速度和记语法。产出就是指标,一个高效的一周看起来就是新建了很多文件。 - -现在语法是免费的。我可以一边读上一次改动的 diff,一边让 Agent 起草一份带单元测试的 500 行迁移。于是瓶颈转移到了模型替我看不了的三件事上: - -- **边界设计**:模块从哪里分开,哪些状态允许跨过去。 -- **验证体系**:那个能抓住类型检查看不见的语义漂移的脚手架。 -- **剪枝的决断力**:愿不愿意删掉那 28 万行探索性、冗余、已死掉的代码,只把 23.5 万行送进生产。 - -所以我现在不再把提交曲线当生产率图表看。一个月新增 50 万行,只能说明工具在转;真正说明这一个月值不值的是那删掉的 13 万行、底下的重构,和一套仍然全绿的测试。 - -## 需要一套能长期不倒的系统? - -我运营 **Hoelee Enterprise**,为马来西亚中小企业做网站设计与系统开发。上面这套 Agent 工作流、测试脚手架和自托管基础设施,就是我给客户交付并长期维护系统时用的同一套东西。 - -如果你需要全栈系统研发、业务流程自动化,或者能扛住自己维护周期的自建基础设施: -- **WhatsApp:** [+60 12-797 2969](https://wa.me/60127972969) -- **Email:** [me@hoelee.com](mailto:me@hoelee.com) -- **官网:** [hoelee.com](https://hoelee.com) -```` - -### 🇬🇧 英文版原文 (English Markdown Primary) -````markdown ---- -title: "I Committed 518,000 Lines in 30 Days. Production Kept 235,000." -description: "Over 30 days, autonomous coding agents added 518,000 lines across 5 repos, yet production kept 235,000. Here is why verification gates matter more than generation." -pubDate: "2026-10-18" -category: "engineering" -blueprint: ai-agent-automation -blueprintLayer: L2-llm-gateway-agents -tags: ["ai", "git", "devops", "testing", "refactoring"] -ogImage: "/og/why-500000-lines-of-commit-churn-only-left-230000-in-production.jpg" -banner: "/banners/why-500000-lines-of-commit-churn-only-left-230000-in-production.jpg" ---- - -Last week I did something I almost never bother to do: I counted my own -commits. Not the ones I remember writing — the ones the repositories -actually recorded. Five production repos on my self-hosted Gitea, thirty -days, one person: 865 commits, 518,233 lines added, 130,892 deleted. - -Then I counted what survived. A clean scan of the current revision of my -main production application returns 234,976 lines. The video transcoder that -gained 58,240 lines in the same window is 43,050 lines long today. - -So where did the other 280,000 lines go? Nothing was lost. They were -written, run, judged wrong, and deleted — or replaced by something smaller -that did the same job. That loop, not the writing, is what I want to write -down, because it changed how I work this year more than any model update -did. - -## The numbers I didn't believe - -Here is the exact commit breakdown across the five repositories, between 17 -September and 17 October 2026: - -| Repository | Commits (30d) | Additions (+) | Deletions (-) | Net Change | Current Total LOC | Primary Stack | -|---|---|---|---|---|---|---| -| **numerology-report** | 432 | +331,672 | -98,937 | +232,735 | **234,976** | PHP, Markdown, JSON | -| **hevc-transcode** | 187 | +58,240 | -15,508 | +42,732 | **43,050** | Python, HTML, Shell | -| **dsm-resource-management** | 132 | +58,234 | -14,076 | +44,158 | **368,793** | Python, TypeScript, Astro | -| **hoelee-blog** | 88 | +23,603 | -709 | +22,894 | **55,933** | Astro, TypeScript, Markdown | -| **hoelee-agent-dist** | 26 | +46,484 | -1,662 | +44,822 | *(Dist)* | Python, Shell, Markdown | -| **Total** | **865** | **+518,233** | **-130,892** | **+387,341** | — | — | - -Two lines are easy to check yourself; this is the whole measurement: - -```bash -git -C numerology-report log --since=2026-09-17 --until=2026-10-17 \ - --numstat --pretty=format: | awk '{add+=$1; del+=$2} END {print add, del}' -``` - -In a human team, churn like that usually means trouble: requirements moving -under the code, a rewrite nobody admits to, an architecture that keeps -collapsing. None of those applied here. Every one of these five repos is -something I run and depend on, and every commit was authored in a session -where I could read the diff before it landed. - -The churn is what refactoring looks like when generation is cheap. An agent -drafts a slice of the change, I run the gates, the gates disagree, and the -slice gets thrown away or rewritten smaller. On the days I got the gates -right, the size drop came faster than the features arrived. - -## What the agents actually touch - -Most people's first experience of AI code is a browser tab: paste a function -into a chat window, copy the answer back into an editor. The bottleneck -there is the clipboard. It also keeps the model far away from the two things -that matter — the codebase's own conventions and the ability to run what it -wrote. - -So mine run in a terminal, on the machine, with real tools: - -1. **Filesystem and syntax tools.** They read existing modules, patch by - fuzzy match instead of overwriting whole files, and run syntax or AST - checks before anything is saved. -2. **Test and execution runners.** PHPUnit suites, pytest harnesses, and - headless Chrome probes, executed in the foreground with the output read - back. -3. **Version control.** They read `git diff`, stage explicit paths, and look - at the history of a file to see why the previous decision was made. - -That combination is fast — an order of magnitude faster than me typing the -first draft. It is also, on its own, a way to make a codebase rot faster, -which is the part nobody warns you about. - -## Where the bloat comes from - -Unsupervised models love to write code. Give one a small edge case and its -instinct is to add a private helper class, clone an existing utility with -one extra parameter, or wrap a library in three layers of abstraction that -only make sense to the diff that introduced them. Left alone for a week, -that is a few thousand lines of confident, plausible, unnecessary code. - -I know because I have that week in my own history. Two things came out of -reading these diffs every day: - -- A new class has to earn its place against a standard-library call I - already have. -- Anything generated is guilty until a deterministic check says otherwise. - "Looks correct" from a model is not evidence; a red test is. - -## The gates that actually deleted the code - -During the V2 architecture overhaul of my main production application, more -than 98,000 lines went out in thirty days. Almost none of that was me -sitting down to delete things. It went because three gates kept rejecting -what came back: - -### 1. Deterministic harnesses instead of "does this look right?" - -Asking a model to review its own code mostly produces confidence, not -correctness. The useful move is to wire the work to something that cannot be -talked out of failing: - -- In the PHP application, every public route parameter has to carry an - explicit default, enforced by a reflection probe - (`ControllerAutoRouteSafetyTest.php`) — that test exists because a bare - route crashed with a 500 in production. -- In the report pipeline, a headless PDF extractor counts the rendered - Chinese characters before a build is allowed to pass, so a font or layout - change that silently drops glyphs fails the build instead of shipping a - broken PDF. -- In the transcoder, the ledger compares exact byte counts rather than - approximating in megabytes, because rounded numbers hid a size regression - for weeks. - -If a gate goes red, the agent either fixes the change or drops it. Nothing -reaching a commit is exempt from that. - -### 2. Pruning as a standing task, not a cleanup project - -A portion of every session goes to deleting. Can a 200-line helper be -replaced by a ten-line call into something that already exists? Is this new -mapper duplicating a function that has lived in `app/Libraries/` for a year? -The 130,000 deletions above are not an accident of a rewrite; they are -scaffolding that outlived its purpose, migration layers with one caller, and -logic that arrived twice under two names. - -### 3. Keeping deterministic work deterministic - -The trap I keep seeing in AI-assisted projects is a model being asked to do -arithmetic it should never touch. If a shell pipeline, a SQL constraint, an -idempotent script, or a cron job can answer it, an LLM has no business -there. - -Models are good at drafting an initial implementation, generating a -three-language dictionary, or mapping a third-party API's quirks. They are -not where I put state transitions, money, or queue scheduling, because a -probabilistic answer to a deterministic question is a bug with a delay fuse. - -## What changed in how I work - -For most of my career the physical constraint was typing speed and -remembering syntax. Output was the metric, and a productive week looked like -a lot of new files. - -Syntax is free now. I can get a 500-line migration with tests drafted while -I read the diff of the previous one. So the constraint moved to the three -things a model cannot check for me: - -- **Boundary design** — where components separate, and which state is - allowed to cross. -- **Test architecture** — the harness that catches semantic drift the type - checker never sees. -- **Pruning discipline** — the willingness to delete 280,000 lines of - exploratory, redundant, or dead code so 235,000 lines can go to - production. - -Which is why I no longer read a commit graph as a productivity chart. Half a -million added lines in a month tells me the tools were running. The 130,000 -deleted lines, the refactor underneath them, and a suite that is still green -tell me whether the month was worth anything. - -## Building something that has to stay up? - -I run **Hoelee Enterprise**, a website design and development studio for -Malaysian SMEs. The agent workflow, the test harnesses and the self-hosted -infrastructure in this post are the same setup I build and maintain client -systems on. - -If you need full-stack engineering, workflow automation, or infrastructure -that survives its own maintenance: -- **WhatsApp:** [+60 12-797 2969](https://wa.me/60127972969) -- **Email:** [me@hoelee.com](mailto:me@hoelee.com) -- **Website:** [hoelee.com](https://hoelee.com) -```` - ---- - -## 文章 02 / 16:给别人家的邮件服务器加一个域名 -- **Slug**: `adding-a-domain-to-someone-elses-mail-server` -- **英文标题**: Adding a Domain to Someone Else's Mail Server -- **分类**: `notes` | **发布日期**: 2025-05-06 -- **线上地址**: https://blog.hoelee.com/posts/adding-a-domain-to-someone-elses-mail-server/ (EN) | https://blog.hoelee.com/posts/zh/adding-a-domain-to-someone-elses-mail-server/ (ZH) -- **本篇审核状态**: ⏳ 待审核 (Pending) - -### ✍️ 顾问审阅意见区 (Review Feedback) -```text -【审阅结论】:[ ] 通过 [ ] 需微调 [ ] 需重构 -【事实与数字核对】: -【人设与用词卫生】: -【CRO与转化建议】: -``` - -### 🇨🇳 中文版原文 (Chinese Markdown Twin) -````markdown ---- -title: "给别人家的邮件服务器加一个域名" -description: "收信只要四条 DNS 记录,一次就通了;而从它发信、以及转发它,撞上两堵任何 DNS 记录都修不了的墙。" -pubDate: 2025-05-06 -updatedDate: 2026-10-16 -category: notes -blueprint: sme-digital-suite -blueprintLayer: L2-sifumail-communication -tags: ["email", "dns", "mailcow", "smtp", "deliverability"] -ogImage: /og/zh-adding-a-domain-to-someone-elses-mail-server.jpg -banner: /banners/adding-a-domain-to-someone-elses-mail-server.jpg +blueprintLayer: L3-local-gpu-inference +stream: creative-lab +tags: ["subtitles", "lrc", "srt", "whisper", "forced-alignment", "ai-music", "python"] +ogImage: "/og/zh-generating-subtitles-for-songs-without-timestamps.jpg" +banner: "/banners/generating-subtitles-for-songs-without-timestamps.jpg" draft: false --- +我试过的每一个 AI 音乐工具,交出来的东西形状都一样:一个音频文件。没有一个会告诉你**每一句是什么时候唱的**。只想听的话没问题,但只要你想把歌词放到屏幕上 —— 卡拉 OK 的那一行、视频字幕、播放器下面的滚动框 —— 就完全不够用。 -## 这件事看起来像个 DNS 活 +时间轴才是全部难点。音频反而是简单的部分。 -有个域名要收信。邮件服务器是我自己那台跑 mailcow 的 VPS,所以这就是「加域名、加记录、建信箱」——二十分钟的活,而且我做过好几次。 +这是我最后跑通的一套流程,用在本地生成的 18 首英文歌上,外加它在浏览器里崩掉的两个地方。下面全部可复现:它唯一需要你提供的东西,是**你已经写好的歌词**。 -这次花了更久,原因是我关于邮件服务器的两个假设并不成立,另外还因为互联网有一条任何服务器配置都改不了的性质。 +## 你真正需要的两样东西 -## 收信:四条记录,加一次真测试 +两种字幕格式,共用同一份数据结构: -收信恰好只需要四样东西,而且都住在域名自己的 DNS 里(这里是 Cloudflare): +| 格式 | 用在哪 | 长什么样 | +|---|---|---| +| **LRC** | 音乐播放器、卡拉 OK 块、`