Kaynağa Gözat

⚡️ (reader): 阅读段落按块批量渲染,段落 / 章节 / 内容索引缓存

v3 tipitaka-reading、Laravel 阅读器、三藏下载共用 PaliContentService 取正文。原来逐段、逐句查库
(200 段约 2000 次查询,批注逐句一次),命中缓存仍要 400 次。改为:

- readParagraphs():没命中的段一起渲染,channel / 句子 / 批注各查一次,整块一次交给 Markup,
  段后脚注正文也一次渲染;readParagraph() 改为调它。缓存整段成品(含外壳与脚注),取消只缓存句子的旧缓存
- readChapters():阅读器按平铺章节(level < 8 的段到下一个 level < 8 之前,不嵌套)缓存,一段只属一章
- 新增 V3\PaliTextService:pali_texts 按书缓存 30 天(标题行一个 key,段落每 1000 段一块),
  以后 pali_texts 的业务逻辑放这里;导入命令后 forgetBook()
- 新增 ReadingIndexService:某 channel 有译文的书号 / 段号索引,page() 的候选、游标、进度改在索引上算
- 失效只随 sentences:改句子删该段与所在章;有译文的段可能变时(增删、strlen 跨 0、搬家)才删索引。
  批注仍删段与章、不碰索引。提交后才清(DB::afterCommit)
- TTL:段落 / 章节 24 小时(mint.cache.read_paragraph_ttl),索引 7 天

实测 cs6 book 213 一块 200 段:冷启动 1954 → 4 次查询、1215 → 165 ms,命中 403 → 0 次;
cs6 整个 channel html 打包 2286 → 217 秒,输出逐字相同。

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
visuddhinanda 1 gün önce
ebeveyn
işleme
0a44c630c7

+ 3 - 0
api-v13/app/Console/Commands/InstallPaliText.php

@@ -3,6 +3,7 @@
 namespace App\Console\Commands;
 namespace App\Console\Commands;
 
 
 use App\Models\PaliText;
 use App\Models\PaliText;
+use App\Services\V3\PaliTextService;
 use App\Tools\Tools;
 use App\Tools\Tools;
 use Illuminate\Console\Command;
 use Illuminate\Console\Command;
 use Illuminate\Support\Facades\DB;
 use Illuminate\Support\Facades\DB;
@@ -143,6 +144,8 @@ class InstallPaliText extends Command
                 }
                 }
 
 
             });
             });
+            // 阅读、导出缓存的 pali_texts(按书缓存一个月)
+            app(PaliTextService::class)->forgetBook((int) $from);
 
 
             $bar->advance();
             $bar->advance();
         }
         }

+ 3 - 0
api-v13/app/Console/Commands/UpgradePaliText.php

@@ -9,6 +9,7 @@ namespace App\Console\Commands;
 
 
 use App\Models\BookTitle;
 use App\Models\BookTitle;
 use App\Models\PaliText;
 use App\Models\PaliText;
+use App\Services\V3\PaliTextService;
 use App\Tools\Tools;
 use App\Tools\Tools;
 use Illuminate\Console\Command;
 use Illuminate\Console\Command;
 use Illuminate\Support\Facades\Log;
 use Illuminate\Support\Facades\Log;
@@ -243,6 +244,8 @@ class UpgradePaliText extends Command
                     $paragraph_info[] = [$book, $paragraph, $length, $prev, $next, $parent];
                     $paragraph_info[] = [$book, $paragraph, $length, $prev, $next, $parent];
                 }
                 }
             }
             }
+            // 阅读、导出缓存的 pali_texts(按书缓存一个月)
+            app(PaliTextService::class)->forgetBook($from);
         }
         }
 
 
         $this->info('all done in '.time() - $startTime.'s');
         $this->info('all done in '.time() - $startTime.'s');

+ 25 - 31
api-v13/app/Http/Controllers/Library/BookController.php

@@ -12,6 +12,7 @@ use App\Services\ChapterService;
 use App\Services\PaliContentService;
 use App\Services\PaliContentService;
 use App\Services\PaliTextService;
 use App\Services\PaliTextService;
 use App\Services\TipitakaCatalogService;
 use App\Services\TipitakaCatalogService;
+use App\Services\V3\PaliTextService as PaliTexts;
 use Illuminate\Http\RedirectResponse;
 use Illuminate\Http\RedirectResponse;
 use Illuminate\Http\Request;
 use Illuminate\Http\Request;
 use Illuminate\Support\Facades\Cookie;
 use Illuminate\Support\Facades\Cookie;
@@ -39,6 +40,7 @@ class BookController extends Controller
         protected PaliTextService $paliTextService,
         protected PaliTextService $paliTextService,
         protected PaliContentService $paliContentService,
         protected PaliContentService $paliContentService,
         protected TipitakaCatalogService $catalog,
         protected TipitakaCatalogService $catalog,
+        protected PaliTexts $paliTexts,
     ) {}
     ) {}
 
 
     /**
     /**
@@ -267,43 +269,45 @@ class BookController extends Controller
      */
      */
     private function resolveDisplayRange(int $book, int $para): array
     private function resolveDisplayRange(int $book, int $para): array
     {
     {
-        $currBook = $this->bookStart($book, $para);
+        // 标题段取自缓存的经文静态数据(V3\PaliTextService),不查库
+        $currBook = $this->paliTexts->bookStart($book, $para);
         abort_if($currBook === null, 404);
         abort_if($currBook === null, 404);
-        $bookStart = $currBook->paragraph;
-        $bookEnd = $currBook->paragraph + $currBook->chapter_len - 1;
+        $bookStart = $currBook['para'];
+        $bookEnd = $currBook['para'] + $currBook['chapter_len'] - 1;
 
 
         // 本书内全部 chapter 节点(level < 8,即 book/chapter/subhead 等可导航节点)
         // 本书内全部 chapter 节点(level < 8,即 book/chapter/subhead 等可导航节点)
-        $paragraphs = PaliText::where('book', $book)
-            ->whereBetween('paragraph', [$bookStart, $bookEnd])
-            ->where('level', '<', 8)
-            ->orderBy('paragraph')
-            ->get();
+        $paragraphs = [];
+        foreach ($this->paliTexts->headings($book) as $paragraph => $heading) {
+            if ($paragraph >= $bookStart && $paragraph <= $bookEnd) {
+                $paragraphs[] = ['paragraph' => $paragraph] + $heading;
+            }
+        }
 
 
-        $curr = $paragraphs->firstWhere('paragraph', $para);
+        $curr = collect($paragraphs)->firstWhere('paragraph', $para);
         // 选中的不是可导航的 chapter 节点(如正文段落 level=100)
         // 选中的不是可导航的 chapter 节点(如正文段落 level=100)
         abort_if($curr === null, 404);
         abort_if($curr === null, 404);
-        $endParagraph = $curr->paragraph + $curr->chapter_len - 1;
+        $endParagraph = $curr['paragraph'] + $curr['chapter_len'] - 1;
 
 
-        if ($curr->chapter_strlen > $this->maxChapterStrlen) {
+        if ($curr['chapter_strlen'] > $this->maxChapterStrlen) {
             // 选中节点过大:向后下钻,找到第一个不超过阈值的子 chapter
             // 选中节点过大:向后下钻,找到第一个不超过阈值的子 chapter
             foreach ($paragraphs as $key => $paragraph) {
             foreach ($paragraphs as $key => $paragraph) {
-                if ($paragraph->paragraph <= $curr->paragraph) {
+                if ($paragraph['paragraph'] <= $curr['paragraph']) {
                     continue;
                     continue;
                 }
                 }
-                if ($paragraph->chapter_strlen <= $this->maxChapterStrlen) {
-                    $endParagraph = $paragraph->paragraph + $paragraph->chapter_len - 1;
+                if ($paragraph['chapter_strlen'] <= $this->maxChapterStrlen) {
+                    $endParagraph = $paragraph['paragraph'] + $paragraph['chapter_len'] - 1;
                     break;
                     break;
                 }
                 }
-                if ($paragraph->level <= $curr->level) {
+                if ($paragraph['level'] <= $curr['level']) {
                     // 已离开选中节点的子树,无法继续下钻,止步于上一个节点
                     // 已离开选中节点的子树,无法继续下钻,止步于上一个节点
-                    $endParagraph = $paragraphs[$key - 1]->paragraph + $paragraphs[$key - 1]->chapter_len - 1;
+                    $endParagraph = $paragraphs[$key - 1]['paragraph'] + $paragraphs[$key - 1]['chapter_len'] - 1;
                     break;
                     break;
                 }
                 }
             }
             }
         }
         }
 
 
         return [
         return [
-            'start' => $curr->paragraph,
+            'start' => $curr['paragraph'],
             'end' => $endParagraph,
             'end' => $endParagraph,
         ];
         ];
     }
     }
@@ -311,31 +315,21 @@ class BookController extends Controller
     /**
     /**
      * 聚合区间内全部段落的阅读模式 HTML。
      * 聚合区间内全部段落的阅读模式 HTML。
      *
      *
-     * 与 TipitakaReadParaController 一致,逐段调用 PaliContentService::readParagraph
-     * 获取 HTML 并按段落顺序拼接;缺失或获取失败的段落跳过。章节标题优先取
-     * ProgressChapter.title,回退到 PaliText.toc。
+     * 交给 PaliContentService::readChapters():按平铺章节缓存,命中时每章一次 GET、不查库,
+     * 没命中的一起渲染。章节标题不进缓存:优先取 ProgressChapter.title,回退到巴利标题(toc)。
      *
      *
      * @return array{display: string, title: string, category: array}
      * @return array{display: string, title: string, category: array}
      */
      */
     private function fetchRangeContent(int $book, string $channelId, int $start, int $end, int $selectedPara): array
     private function fetchRangeContent(int $book, string $channelId, int $start, int $end, int $selectedPara): array
     {
     {
-        $display = '';
-        foreach (range($start, $end) as $para) {
-            $paragraph = $this->paliContentService->readParagraph($book, $para, $channelId, 'html');
-            if (empty($paragraph['display'])) {
-                continue;
-            }
-            $display .= $paragraph['display'];
-        }
+        $display = $this->paliContentService->readChapters($book, $start, $end, $channelId, 'html');
 
 
         $title = ProgressChapter::where('book', $book)
         $title = ProgressChapter::where('book', $book)
             ->where('para', $selectedPara)
             ->where('para', $selectedPara)
             ->where('channel_id', $channelId)
             ->where('channel_id', $channelId)
             ->value('title');
             ->value('title');
         if (empty($title)) {
         if (empty($title)) {
-            $title = PaliText::where('book', $book)
-                ->where('paragraph', $selectedPara)
-                ->value('toc');
+            $title = $this->paliTexts->heading($book, $selectedPara)['toc'] ?? null;
         }
         }
 
 
         return [
         return [

+ 16 - 10
api-v13/app/Models/Discussion.php

@@ -9,6 +9,7 @@ use Illuminate\Database\Eloquent\Model;
 use Illuminate\Database\Eloquent\Relations\BelongsTo;
 use Illuminate\Database\Eloquent\Relations\BelongsTo;
 use Illuminate\Database\Eloquent\Relations\HasMany;
 use Illuminate\Database\Eloquent\Relations\HasMany;
 use Illuminate\Database\Eloquent\SoftDeletes;
 use Illuminate\Database\Eloquent\SoftDeletes;
+use Illuminate\Support\Facades\DB;
 
 
 /**
 /**
  * 表 `discussions`。
  * 表 `discussions`。
@@ -224,16 +225,21 @@ class Discussion extends Model
             if ($discussion->res_type !== 'sentence' || empty($discussion->res_id)) {
             if ($discussion->res_type !== 'sentence' || empty($discussion->res_id)) {
                 return;
                 return;
             }
             }
-            $sentence = Sentence::where('uid', $discussion->res_id)
-                ->first(['book_id', 'paragraph', 'channel_uid']);
-            if (! $sentence) {
-                return;
-            }
-            PaliContentService::forgetParagraph(
-                (int) $sentence->book_id,
-                (int) $sentence->paragraph,
-                (string) $sentence->channel_uid
-            );
+            $sentenceId = $discussion->res_id;
+            // 提交之后才清,免得并发的读在提交前把旧数据写回缓存
+            DB::afterCommit(function () use ($sentenceId) {
+                $sentence = Sentence::where('uid', $sentenceId)
+                    ->first(['book_id', 'paragraph', 'channel_uid']);
+                if (! $sentence) {
+                    return;
+                }
+                // 只删段落成品;批注不影响内容索引
+                PaliContentService::forgetParagraph(
+                    (int) $sentence->book_id,
+                    (int) $sentence->paragraph,
+                    (string) $sentence->channel_uid
+                );
+            });
         };
         };
         static::saved($forget);
         static::saved($forget);
         static::deleted($forget);
         static::deleted($forget);

+ 38 - 10
api-v13/app/Models/Sentence.php

@@ -6,6 +6,7 @@ use App\Services\PaliContentService;
 use Illuminate\Database\Eloquent\Factories\HasFactory;
 use Illuminate\Database\Eloquent\Factories\HasFactory;
 use Illuminate\Database\Eloquent\Model;
 use Illuminate\Database\Eloquent\Model;
 use Illuminate\Database\Eloquent\SoftDeletes;
 use Illuminate\Database\Eloquent\SoftDeletes;
+use Illuminate\Support\Facades\DB;
 
 
 class Sentence extends Model
 class Sentence extends Model
 {
 {
@@ -37,19 +38,46 @@ class Sentence extends Model
         'channel_uid' => 'string',
         'channel_uid' => 'string',
     ];
     ];
 
 
+    /**
+     * 增改删句子时清阅读缓存:段落成品(L1)删掉;「有译文的段」可能变了才删内容索引(L2)。
+     * 见 {@see PaliContentService::paragraphChanged()}。改了 book / paragraph / channel 的,新旧两处都要清。
+     * 提交之后才清,免得并发的读在提交前把旧数据写回缓存。
+     */
     protected static function booted(): void
     protected static function booted(): void
     {
     {
-        $forget = function (Sentence $sentence) {
-            PaliContentService::forgetParagraph(
-                (int) $sentence->book_id,
-                (int) $sentence->paragraph,
-                (string) $sentence->channel_uid
-            );
+        $created = function (Sentence $sentence) {
+            $now = [(int) $sentence->book_id, (int) $sentence->paragraph, (string) $sentence->channel_uid];
+            $hasText = (int) $sentence->strlen > 0;
+            DB::afterCommit(fn () => PaliContentService::paragraphChanged(...$now, indexChanged: true, mayAddBook: $hasText));
+        };
+        // updated 事件里 getOriginal() 还是改之前的值(含软删恢复:deleted_at 从有到无)
+        $updated = function (Sentence $sentence) {
+            $now = [(int) $sentence->book_id, (int) $sentence->paragraph, (string) $sentence->channel_uid];
+            $before = [(int) $sentence->getOriginal('book_id'), (int) $sentence->getOriginal('paragraph'), (string) $sentence->getOriginal('channel_uid')];
+            $hasText = (int) $sentence->strlen > 0;
+            $hadText = (int) $sentence->getOriginal('strlen') > 0;
+            $restored = $sentence->getOriginal('deleted_at') !== null && $sentence->deleted_at === null;
+            DB::afterCommit(function () use ($now, $before, $hasText, $hadText, $restored) {
+                $moved = $before !== $now;
+                PaliContentService::paragraphChanged(
+                    ...$now,
+                    indexChanged: $restored || $moved || $hasText !== $hadText,
+                    mayAddBook: $hasText,
+                    mayRemoveBook: ! $moved && $hadText && ! $hasText,
+                );
+                if ($moved) {
+                    PaliContentService::paragraphChanged(...$before, indexChanged: true, mayRemoveBook: $hadText);
+                }
+            });
+        };
+        $removed = function (Sentence $sentence) {
+            $now = [(int) $sentence->book_id, (int) $sentence->paragraph, (string) $sentence->channel_uid];
+            DB::afterCommit(fn () => PaliContentService::paragraphChanged(...$now, indexChanged: true, mayRemoveBook: true));
         };
         };
-        static::saved($forget);
-        static::deleted($forget);
-        static::restored($forget);
-        static::forceDeleted($forget);
+        static::created($created);
+        static::updated($updated);
+        static::deleted($removed);
+        static::forceDeleted($removed);
     }
     }
 
 
     protected $dates = [
     protected $dates = [

+ 286 - 92
api-v13/app/Services/PaliContentService.php

@@ -22,7 +22,9 @@ use App\Services\Markup\Annotation\AnnotationSet;
 use App\Services\Markup\Format;
 use App\Services\Markup\Format;
 use App\Services\Markup\MarkupService;
 use App\Services\Markup\MarkupService;
 use App\Services\Markup\RenderOptions;
 use App\Services\Markup\RenderOptions;
+use App\Services\V3\PaliTextService;
 use Illuminate\Support\Arr;
 use Illuminate\Support\Arr;
+use Illuminate\Support\Collection;
 use Illuminate\Support\Facades\Log;
 use Illuminate\Support\Facades\Log;
 use Illuminate\Support\Str;
 use Illuminate\Support\Str;
 
 
@@ -656,50 +658,121 @@ class PaliContentService
     }
     }
 
 
     /**
     /**
-     * 阅读模式渲染单个段落。
-     * 直接从 sentences 表取单个 channel 的记录,渲染成 html。
-     * 与 paragraphs() 不同:没有译文的句子不保留占位,有多少句子输出多少句子。
+     * 阅读模式渲染单个段落,即只给一段的 {@see self::readParagraphs()}。
+     * 直接从 sentences 表取单个 channel 的记录。与 paragraphs() 不同:没有译文的句子不保留占位,
+     * 有多少句子输出多少句子。
      *
      *
-     * @return array{para: int, display: string, sentences: array<int, array{sid: string, html: string}>}
+     * @return array{para: int, display: string, sentences: list<array{sid: string, html: string}>}
      */
      */
     public function readParagraph(int $book, int $para, string $channelUid, string $format = 'html'): array
     public function readParagraph(int $book, int $para, string $channelUid, string $format = 'html'): array
     {
     {
-        $level = $this->paragraphLevel($book, $para);
-        // 缓存句子,段落外壳与标题级别有关,不进缓存
-        $key = self::paragraphCacheKey($book, $para, $channelUid, $format);
-        $cached = RedisCache::remember(
-            $key,
-            config('mint.cache.expire'),
-            function () use ($book, $para, $channelUid, $format) {
-                return $this->renderReadSentences($book, $para, $channelUid, $format);
+        return $this->readParagraphs($book, [$para], $channelUid, $format)[$para];
+    }
+
+    /**
+     * 阅读模式渲染同一本书的多个段落。v3 阅读、Laravel 阅读器、三藏下载都从这里取正文。
+     *
+     * 每段的**完整结果**(含段落外壳与段后脚注列表)按 (book, para, channel, format) 缓存,
+     * 命中时不查库;没有译文的段也缓存(display 为空)。没命中的段一起渲染
+     * ({@see self::renderReadParagraphs()}):channel、句子、批注各查一次,全部句子一次交给 Markup,
+     * 术语、引用句子等每类只查一次。
+     *
+     * 缓存由 Sentence / Discussion 的模型事件删除({@see self::paragraphChanged()}、{@see self::forgetParagraph()});术语释义、
+     * 引用的句子、channel 名称改了没有失效信号,最多旧 `mint.cache.read_paragraph_ttl`。
+     *
+     * @param  list<int>  $paras
+     * @return array<int, array{para: int, display: string, sentences: list<array{sid: string, html: string}>}> 段落号 => 结果,顺序同 $paras
+     */
+    public function readParagraphs(int $book, array $paras, string $channelUid, string $format = 'html'): array
+    {
+        $results = [];
+        $misses = [];
+        foreach (array_unique($paras) as $para) {
+            $cached = RedisCache::get(self::paragraphCacheKey($book, $para, $channelUid, $format));
+            $results[$para] = is_array($cached) ? $cached : null;
+            if ($results[$para] === null) {
+                $misses[] = $para;
             }
             }
-        );
+        }
+        if ($misses === []) {
+            return $results;
+        }
 
 
-        $result = [
-            'para' => $para,
-            'display' => '',
-            'sentences' => $cached['sentences'],
-        ];
-        if (count($cached['display']) === 0) {
-            return $result;
+        $ttl = (int) config('mint.cache.read_paragraph_ttl');
+        foreach ($this->renderReadParagraphs($book, $misses, $channelUid, $format) as $para => $result) {
+            RedisCache::put(self::paragraphCacheKey($book, $para, $channelUid, $format), $result, $ttl);
+            $results[$para] = $result;
         }
         }
 
 
-        $pClass = PaliText::where('book', $book)
-            ->where('paragraph', $para)
-            ->value('class');
+        return $results;
+    }
 
 
-        if ($format === 'html') {
-            // html 格式加段落外壳;段后追加段落脚注列表(本段义注/复注条目)
-            $content = implode('', $cached['display']);
-            $inner = $level > 0 ? "<h{$level}>{$content}</h{$level}>" : "<div class='para-block'>{$content}</div>";
-            $footnoteList = $this->renderFootnoteList($cached['notes'] ?? []);
-            $result['display'] = "<div id='para-{$para}' class='{$cached['area']} {$pClass}' data-para='{$para}'>{$inner}{$footnoteList}</div>";
-        } else {
-            // 其他格式一行一句
-            $result['display'] = implode("\n", $cached['display']);
+    /**
+     * 区间 [start, end] 的阅读模式正文(html),阅读器按章读用。
+     *
+     * 按平铺章节缓存({@see PaliTextService::flatChapters()}:标题段到下一个标题段之前是一章,不嵌套),
+     * 一章一个 key,命中时整章一次 GET、不查库。区间完整覆盖的章走章节缓存,没命中的章一起交给
+     * {@see self::readParagraphs()}(各段多半已在段落成品缓存里)拼好回写;区间边缘没盖全的章、
+     * 第一个标题段之前的段直接逐段取。章节缓存与段落成品一起失效({@see self::forgetParagraph()})。
+     */
+    public function readChapters(int $book, int $start, int $end, string $channelUid, string $format = 'html'): string
+    {
+        // 区间切成片:[起, 止, 是否整章]
+        $pieces = [];
+        $cursor = $start;
+        foreach (app(PaliTextService::class)->flatChapters($book) as $chapterStart => $chapterEnd) {
+            if ($chapterEnd < $cursor || $chapterStart > $end) {
+                continue;
+            }
+            if ($chapterStart > $cursor) {
+                $pieces[] = [$cursor, $chapterStart - 1, false];
+                $cursor = $chapterStart;
+            }
+            $whole = $chapterStart >= $start && $chapterEnd <= $end;
+            $pieces[] = [$cursor, min($chapterEnd, $end), $whole];
+            $cursor = min($chapterEnd, $end) + 1;
+        }
+        if ($cursor <= $end) {
+            $pieces[] = [$cursor, $end, false];
         }
         }
 
 
-        return $result;
+        $chapters = [];
+        $paras = [];
+        foreach ($pieces as $i => [$from, $to, $whole]) {
+            if ($whole) {
+                $cached = RedisCache::get(self::chapterCacheKey($book, $from, $channelUid, $format));
+                if (is_string($cached)) {
+                    $chapters[$i] = $cached;
+
+                    continue;
+                }
+            }
+            array_push($paras, ...range($from, $to));
+        }
+        $rendered = $paras === [] ? [] : $this->readParagraphs($book, $paras, $channelUid, $format);
+
+        $ttl = (int) config('mint.cache.read_paragraph_ttl');
+        $separator = $format === 'html' ? '' : "\n";
+        $display = [];
+        foreach ($pieces as $i => [$from, $to, $whole]) {
+            if (! isset($chapters[$i])) {
+                $parts = [];
+                foreach (range($from, $to) as $para) {
+                    if (($rendered[$para]['display'] ?? '') !== '') {
+                        $parts[] = $rendered[$para]['display'];
+                    }
+                }
+                $chapters[$i] = implode($separator, $parts);
+                if ($whole) {
+                    RedisCache::put(self::chapterCacheKey($book, $from, $channelUid, $format), $chapters[$i], $ttl);
+                }
+            }
+            if ($chapters[$i] !== '') {
+                $display[] = $chapters[$i];
+            }
+        }
+
+        return implode($separator, $display);
     }
     }
 
 
     /**
     /**
@@ -707,12 +780,7 @@ class PaliContentService
      */
      */
     public function paragraphLevel(int $book, int $para): int
     public function paragraphLevel(int $book, int $para): int
     {
     {
-        $level = PaliText::where('book', $book)
-            ->where('paragraph', $para)
-            ->where('level', '<', 8)
-            ->value('level');
-
-        return $level ? (int) $level : 0;
+        return app(PaliTextService::class)->headingLevel($book, $para);
     }
     }
 
 
     /**
     /**
@@ -741,24 +809,46 @@ class PaliContentService
     private const MAX_COMMENTARY_SENTENCES = 3;
     private const MAX_COMMENTARY_SENTENCES = 3;
 
 
     /**
     /**
-     * 段落阅读模式缓存的 key
+     * 段落阅读模式缓存的 key(段落成品:含外壳与脚注列表)。
      */
      */
     public static function paragraphCacheKey(int $book, int $para, string $channelUid, string $format): string
     public static function paragraphCacheKey(int $book, int $para, string $channelUid, string $format): string
     {
     {
-        // markup:App\Services\Markup 渲染的缓存,与 MdRender 时代的旧缓存分开(旧 key 自然过期)
-        // markdown 2026-11-21 起句末附脚注正文,换 key 让旧缓存(不带脚注正文)自然过期
-        $suffix = $format === 'markdown' ? '/fn' : '';
+        // v4:2026-11-22 起缓存整段成品(原来只缓存句子、外壳每次现查),换前缀让旧缓存自然过期
+        return "/read-para/v4/{$book}-{$para}/{$channelUid}/{$format}";
+    }
 
 
-        return "/read-para/markup/{$book}-{$para}/{$channelUid}/{$format}{$suffix}";
+    /**
+     * 平铺章节的阅读正文缓存 key({@see self::readChapters()})。
+     */
+    public static function chapterCacheKey(int $book, int $chapter, string $channelUid, string $format): string
+    {
+        return "/read-chapter/v1/{$book}-{$chapter}/{$channelUid}/{$format}";
     }
     }
 
 
     /**
     /**
-     * 删除某个段落的阅读模式缓存。句子有增改删时调用,下次 readParagraph 自动重建。
+     * 删除某个段落的阅读模式缓存(段落成品,及它所在平铺章节的章节缓存),下次读时自动重建。
      */
      */
     public static function forgetParagraph(int $book, int $para, string $channelUid): void
     public static function forgetParagraph(int $book, int $para, string $channelUid): void
     {
     {
+        $chapter = app(PaliTextService::class)->flatChapterOf($book, $para);
         foreach (self::FORMATS as $format) {
         foreach (self::FORMATS as $format) {
             RedisCache::forget(self::paragraphCacheKey($book, $para, $channelUid, $format));
             RedisCache::forget(self::paragraphCacheKey($book, $para, $channelUid, $format));
+            if ($chapter !== null) {
+                RedisCache::forget(self::chapterCacheKey($book, $chapter, $channelUid, $format));
+            }
+        }
+    }
+
+    /**
+     * 某段的句子变了(Sentence 的模型事件调用):删段落成品与所在章节的缓存;「有译文的段」可能变了
+     * ($indexChanged:新建 / 删除句子、strlen 在 0 与非 0 之间变化、句子搬了家)时再删内容索引。
+     * 书号索引的两个参数见 {@see ReadingIndexService::forget()}。
+     */
+    public static function paragraphChanged(int $book, int $para, string $channelUid, bool $indexChanged = false, bool $mayAddBook = false, bool $mayRemoveBook = false): void
+    {
+        self::forgetParagraph($book, $para, $channelUid);
+        if ($indexChanged) {
+            app(ReadingIndexService::class)->forget($channelUid, $book, $mayAddBook, $mayRemoveBook);
         }
         }
     }
     }
 
 
@@ -774,7 +864,7 @@ class PaliContentService
      *   没有位置的合成一个三角叹号图标放在句尾。纯文本 / markdown 里不显示。
      *   没有位置的合成一个三角叹号图标放在句尾。纯文本 / markdown 里不显示。
      * - `assessment`(译文评估):句尾一个对勾图标,颜色按分数分档,带 discussion id,
      * - `assessment`(译文评估):句尾一个对勾图标,颜色按分数分档,带 discussion id,
      *   阅读器点击看分数与理由。一句只有一条(有并发残留时取最近更新的)。纯文本 / markdown 里不显示。
      *   阅读器点击看分数与理由。一句只有一条(有并发残留时取最近更新的)。纯文本 / markdown 里不显示。
-     *   同段里其它没有评估的句子由 {@see self::renderReadSentences()} 补灰色对勾。
+     *   同段里其它没有评估的句子由 {@see self::renderReadParagraphs()} 补灰色对勾。
      * issue / glossary 只注入未关闭的;批注与评估没有开关状态。
      * issue / glossary 只注入未关闭的;批注与评估没有开关状态。
      *
      *
      * 位置按 pos_* 定位,与 quote_exact 对不上(正文改过)时按摘录重新定位。
      * 位置按 pos_* 定位,与 quote_exact 对不上(正文改过)时按摘录重新定位。
@@ -782,23 +872,19 @@ class PaliContentService
      * 插入点写的是结构化标记({@see AnnotationSet})而不是 HTML:content 里留下占位符,渲染时变成
      * 插入点写的是结构化标记({@see AnnotationSet})而不是 HTML:content 里留下占位符,渲染时变成
      * anno-issue / anno-issue-mark / anno-assessment / note 模板节点,任意格式都能输出。
      * anno-issue / anno-issue-mark / anno-assessment / note 模板节点,任意格式都能输出。
      *
      *
-     * @return array{content: string, notes: list<array{fnId: string, noteHtml: string, citeHtml: string}>, assessed: bool, annotations: AnnotationSet}
+     * 批注由调用方一次查好传进来({@see self::readingAnnotations()})。段后脚注列表的正文(纯文本)
+     * 这里不渲染,只给出待渲染的源码(`text`),由调用方整块一次渲染后填进 `noteHtml`。
+     *
+     * @param  list<Discussion>  $records  挂在这句上、要注入阅读页的批注,按创建时间升序
+     * @return array{content: string, notes: list<array{fnId: string, noteHtml: string, citeHtml: string, text: array{source: string, channels: list<string>, contentType: string}, truncated: bool}>, assessed: bool, annotations: AnnotationSet}
      */
      */
-    protected function injectAnnotationNotes(Sentence $row, string $channelType, string $format = 'html'): array
+    protected function injectAnnotationNotes(Sentence $row, string $channelType, array $records): array
     {
     {
         $content = (string) $row->content;
         $content = (string) $row->content;
         $annotations = new AnnotationSet;
         $annotations = new AnnotationSet;
         $result = ['content' => $content, 'notes' => [], 'assessed' => false, 'annotations' => $annotations];
         $result = ['content' => $content, 'notes' => [], 'assessed' => false, 'annotations' => $annotations];
-        $records = Discussion::where('res_type', 'sentence')
-            ->where('res_id', $row->uid)
-            ->whereIn('type', Discussion::READING_TYPES)
-            // 只注入话题本身;回复(类型跟随话题)不进阅读页
-            ->whereNull('parent')
-            ->where(fn ($q) => $q->whereIn('type', Discussion::STATELESS_TYPES)->orWhere('status', 'active'))
-            ->orderBy('created_at')
-            ->get();
 
 
-        if ($records->isEmpty()) {
+        if ($records === []) {
             return $result;
             return $result;
         }
         }
 
 
@@ -833,7 +919,7 @@ class PaliContentService
 
 
                 continue;
                 continue;
             }
             }
-            $note = $this->renderAnnotationNote($record, $row, $channelType);
+            $note = $this->renderAnnotationNote($record, $row);
             if ($note === null) {
             if ($note === null) {
                 continue;
                 continue;
             }
             }
@@ -851,8 +937,10 @@ class PaliContentService
             ];
             ];
             $footnotes[$record->id] = [
             $footnotes[$record->id] = [
                 'fnId' => 'fn-'.$record->id,
                 'fnId' => 'fn-'.$record->id,
-                'noteHtml' => $note['noteHtml'],
+                'noteHtml' => '',
                 'citeHtml' => $note['citeHtml'],
                 'citeHtml' => $note['citeHtml'],
+                'text' => $note['text'],
+                'truncated' => $note['truncated'],
             ];
             ];
         }
         }
 
 
@@ -877,9 +965,12 @@ class PaliContentService
      * 把一条批注(commentary / note)整理成要插入正文的 note 模板(正文 + 参数)与段后脚注条目。
      * 把一条批注(commentary / note)整理成要插入正文的 note 模板(正文 + 参数)与段后脚注条目。
      * 不合格的(正文为空、commentary 不是句子模板)返回 null,不插角标也不进脚注列表。
      * 不合格的(正文为空、commentary 不是句子模板)返回 null,不插角标也不进脚注列表。
      *
      *
-     * @return array{body: string, params: array<string, string>, noteHtml: string, citeHtml: string, order: array<int, int>}|null
+     * 脚注条目的正文(纯文本)不在这里渲染:`text` 是待渲染的源码,`truncated` 表示义注被截断、
+     * 渲染后要补省略号。整块一起渲染见 {@see self::renderFootnoteTexts()}。
+     *
+     * @return array{body: string, params: array<string, string>, text: array{source: string, channels: list<string>, contentType: string}, truncated: bool, citeHtml: string, order: array<int, int>}|null
      */
      */
-    protected function renderAnnotationNote(Discussion $note, Sentence $row, string $channelType): ?array
+    protected function renderAnnotationNote(Discussion $note, Sentence $row): ?array
     {
     {
         $noteContent = trim((string) $note->content);
         $noteContent = trim((string) $note->content);
         if ($noteContent === '') {
         if ($noteContent === '') {
@@ -906,15 +997,14 @@ class PaliContentService
             $source = $noteContent;
             $source = $noteContent;
         }
         }
         // 段后脚注列表用的纯文本(边注本身是结构化的 note 节点,正文照 markdown 渲染)
         // 段后脚注列表用的纯文本(边注本身是结构化的 note 节点,正文照 markdown 渲染)
-        $noteHtml = (string) app(MarkupService::class)->render($source, new RenderOptions(
-            format: Format::Text,
-            channels: [(string) $row->channel_uid],
-            channelType: $channelType,
-            contentType: $note->effectiveContentType(),
-        ));
+        $text = [
+            'source' => $source,
+            'channels' => [(string) $row->channel_uid],
+            'contentType' => $note->effectiveContentType(),
+        ];
         // 义注被截断时补省略号,提示后面还有;想看全文点 <cite> 跳过去。
         // 义注被截断时补省略号,提示后面还有;想看全文点 <cite> 跳过去。
-        if (count($sents) > self::MAX_COMMENTARY_SENTENCES) {
-            $noteHtml = rtrim($noteHtml).'...';
+        $truncated = count($sents) > self::MAX_COMMENTARY_SENTENCES;
+        if ($truncated) {
             $source .= '...';
             $source .= '...';
         }
         }
         // 出处只有 commentary 有。跳转目标(义注书-段-起-止)同时挂在 <cite> 和角标
         // 出处只有 commentary 有。跳转目标(义注书-段-起-止)同时挂在 <cite> 和角标
@@ -933,7 +1023,8 @@ class PaliContentService
             // note 模板的正文(markdown)与参数:渲染成 tufte sidenote(label + input + span.sidenote)
             // note 模板的正文(markdown)与参数:渲染成 tufte sidenote(label + input + span.sidenote)
             'body' => $source,
             'body' => $source,
             'params' => $params,
             'params' => $params,
-            'noteHtml' => $noteHtml,
+            'text' => $text,
+            'truncated' => $truncated,
             'citeHtml' => $citeHtml,
             'citeHtml' => $citeHtml,
             // 同一插入点上的先后:按义注原文的先后;普通 note 没有坐标,取 0,排在义注对应之前
             // 同一插入点上的先后:按义注原文的先后;普通 note 没有坐标,取 0,排在义注对应之前
             'order' => $sents ? [(int) $sents[0][1], (int) $sents[0][2], (int) $sents[0][3]] : [0, 0, 0],
             'order' => $sents ? [(int) $sents[0][1], (int) $sents[0][2], (int) $sents[0][3]] : [0, 0, 0],
@@ -942,6 +1033,8 @@ class PaliContentService
 
 
     /**
     /**
      * 段落脚注列表:把本段的注释条目逐条列在段后,每条默认收起为可配置行数(见阅读器 CSS)。
      * 段落脚注列表:把本段的注释条目逐条列在段后,每条默认收起为可配置行数(见阅读器 CSS)。
+     *
+     * @param  list<array{fnId: string, noteHtml: string, citeHtml: string}>  $notes
      */
      */
     protected function renderFootnoteList(array $notes): string
     protected function renderFootnoteList(array $notes): string
     {
     {
@@ -964,42 +1057,114 @@ class PaliContentService
     }
     }
 
 
     /**
     /**
-     * 渲染段落里的句子。不含段落外壳,可直接缓存。
+     * 一次查回这些句子上要注入阅读页的批注,按句子 uid 分组、组内按创建时间升序。
+     *
+     * @param  Collection<int, Sentence>  $records
+     * @return array<string, list<Discussion>>
+     */
+    protected function readingAnnotations(Collection $records): array
+    {
+        $grouped = [];
+        foreach ($records->pluck('uid')->unique()->chunk(1000) as $uids) {
+            Discussion::where('res_type', 'sentence')
+                ->whereIn('res_id', $uids->values()->all())
+                ->whereIn('type', Discussion::READING_TYPES)
+                // 只注入话题本身;回复(类型跟随话题)不进阅读页
+                ->whereNull('parent')
+                ->where(fn ($q) => $q->whereIn('type', Discussion::STATELESS_TYPES)->orWhere('status', 'active'))
+                ->orderBy('created_at')
+                ->get()
+                ->each(function (Discussion $discussion) use (&$grouped) {
+                    $grouped[(string) $discussion->res_id][] = $discussion;
+                });
+        }
+
+        return $grouped;
+    }
+
+    /**
+     * 整块的段后脚注正文(纯文本)一次渲染:批注里的术语、义注句子合在一起查。
      *
      *
-     * @return array{area: string, display: array<int, string>, sentences: array<int, array{sid: string, html: string}>}
+     * @param  array<int, array{notes: list<array<string, mixed>>}>  $injections
+     * @return array<string, string> "句序号:脚注序号" => 纯文本
      */
      */
-    protected function renderReadSentences(int $book, int $para, string $channelUid, string $format): array
+    protected function renderFootnoteTexts(array $injections, string $channelType): array
     {
     {
-        $result = ['area' => 'translation', 'display' => [], 'sentences' => []];
+        $items = [];
+        foreach ($injections as $i => $injected) {
+            foreach ($injected['notes'] as $n => $note) {
+                $items["{$i}:{$n}"] = $note['text'];
+            }
+        }
+        if ($items === []) {
+            return [];
+        }
+        $texts = app(MarkupService::class)->renderMany($items, new RenderOptions(format: Format::Text, channelType: $channelType));
+        foreach ($injections as $i => $injected) {
+            foreach ($injected['notes'] as $n => $note) {
+                $text = (string) ($texts["{$i}:{$n}"] ?? '');
+                $texts["{$i}:{$n}"] = $note['truncated'] ? rtrim($text).'...' : $text;
+            }
+        }
+
+        return $texts;
+    }
+
+    /**
+     * 渲染同一本书的若干段落(没命中缓存的那些),结果含段落外壳,可直接缓存。
+     *
+     * 整块只查三次库:channel、句子(按段、word_start 排序)、批注;全部句子一次交给 Markup 渲染,
+     * 脚注正文再一次。标题级别与段落 class 取自 {@see PaliTextService}(缓存的经文静态数据)。
+     *
+     * @param  list<int>  $paras
+     * @return array<int, array{para: int, display: string, sentences: list<array{sid: string, html: string}>}>
+     */
+    protected function renderReadParagraphs(int $book, array $paras, string $channelUid, string $format): array
+    {
+        $results = [];
+        foreach ($paras as $para) {
+            $results[$para] = ['para' => $para, 'display' => '', 'sentences' => []];
+        }
         $channel = Channel::where('uid', $channelUid)
         $channel = Channel::where('uid', $channelUid)
             ->select(['uid', 'type', 'lang', 'name'])->first();
             ->select(['uid', 'type', 'lang', 'name'])->first();
         if (! $channel) {
         if (! $channel) {
-            return $result;
+            return $results;
         }
         }
         $isOrigin = $channel->type === 'original' || $channel->type === 'wbw';
         $isOrigin = $channel->type === 'original' || $channel->type === 'wbw';
         $channelType = $channel->type === 'nissaya' ? 'nissaya' : 'translation';
         $channelType = $channel->type === 'nissaya' ? 'nissaya' : 'translation';
-        $result['area'] = $isOrigin ? 'original' : 'translation';
+        $area = $isOrigin ? 'original' : 'translation';
 
 
         $records = Sentence::select($this->selectCol)
         $records = Sentence::select($this->selectCol)
             ->where('book_id', $book)
             ->where('book_id', $book)
-            ->where('paragraph', $para)
             ->where('channel_uid', $channelUid)
             ->where('channel_uid', $channelUid)
+            ->whereIn('paragraph', $paras)
+            ->orderBy('paragraph')
             ->orderBy('word_start')
             ->orderBy('word_start')
-            ->get();
+            ->get()
+            ->values();
+        if ($records->isEmpty()) {
+            return $results;
+        }
+
+        $annotations = $this->readingAnnotations($records);
+        $injections = [];
+        $assessedParas = [];
+        foreach ($records as $i => $row) {
+            $injections[$i] = $this->injectAnnotationNotes($row, $channelType, $annotations[(string) $row->uid] ?? []);
+            if ($injections[$i]['assessed']) {
+                $assessedParas[(int) $row->paragraph] = true;
+            }
+        }
 
 
-        $allNotes = [];
-        $injections = $records->map(fn (Sentence $row) => $this->injectAnnotationNotes($row, $channelType, $format));
-        // 段里有句子评估过,其余没评估的句子在句尾补灰色对勾:不然读者会把它与下一句的
-        // 对勾连起来,误以为是一句。整段都没评估就都不补(段落本身有分隔)。
-        $markUnassessed = $injections->contains('assessed', true);
         $sources = [];
         $sources = [];
         foreach ($records as $i => $row) {
         foreach ($records as $i => $row) {
             $injected = $injections[$i];
             $injected = $injections[$i];
             $content = $injected['content'];
             $content = $injected['content'];
-            if ($markUnassessed && ! $injected['assessed'] && trim($content) !== '') {
+            // 段里有句子评估过,其余没评估的句子在句尾补灰色对勾:不然读者会把它与下一句的
+            // 对勾连起来,误以为是一句。整段都没评估就都不补(段落本身有分隔)。按段算,不是按整块
+            if (isset($assessedParas[(int) $row->paragraph]) && ! $injected['assessed'] && trim($content) !== '') {
                 $content .= $injected['annotations']->unassessedMark();
                 $content .= $injected['annotations']->unassessedMark();
             }
             }
-            $allNotes = array_merge($allNotes, $injected['notes']);
             $sources[$i] = [
             $sources[$i] = [
                 'source' => $content,
                 'source' => $content,
                 'channels' => [(string) $row->channel_uid],
                 'channels' => [(string) $row->channel_uid],
@@ -1009,29 +1174,58 @@ class PaliContentService
                 'idPrefix' => "{$row->book_id}-{$row->paragraph}-{$row->word_start}-{$row->word_end}",
                 'idPrefix' => "{$row->book_id}-{$row->paragraph}-{$row->word_start}-{$row->word_end}",
             ];
             ];
         }
         }
-        // 整段一起渲染:各句里的术语、句子模板(含义注对应)合在一起批量查
-        $rendered = $sources === [] ? [] : app(MarkupService::class)->renderMany(
+        // 整块一起渲染:各句里的术语、句子模板(含义注对应)合在一起批量查
+        $rendered = app(MarkupService::class)->renderMany(
             $sources,
             $sources,
             // markdown 每句末尾附自己的脚注正文(`[^n]: …`)。编号每句从 1 起,跨句会重号,
             // markdown 每句末尾附自己的脚注正文(`[^n]: …`)。编号每句从 1 起,跨句会重号,
             // 整章导出时由 V3\TipitakaExportBuilder 逐句重新编号;不附正文的话 `[^n]` 无处可指
             // 整章导出时由 V3\TipitakaExportBuilder 逐句重新编号;不附正文的话 `[^n]` 无处可指
             new RenderOptions(format: self::markupFormat($format), channelType: $channelType, footnote: $format === 'markdown'),
             new RenderOptions(format: self::markupFormat($format), channelType: $channelType, footnote: $format === 'markdown'),
         );
         );
+        // 段后脚注列表只有 html 有
+        $noteTexts = $format === 'html' ? $this->renderFootnoteTexts($injections, $channelType) : [];
+
+        $display = [];
+        $notes = [];
         foreach ($records as $i => $row) {
         foreach ($records as $i => $row) {
+            $para = (int) $row->paragraph;
+            foreach ($injections[$i]['notes'] as $n => $note) {
+                $notes[$para][] = [
+                    'fnId' => $note['fnId'],
+                    'noteHtml' => $noteTexts["{$i}:{$n}"] ?? '',
+                    'citeHtml' => $note['citeHtml'],
+                ];
+            }
             $html = $rendered[$i] ?? '';
             $html = $rendered[$i] ?? '';
             if (empty($html)) {
             if (empty($html)) {
                 continue;
                 continue;
             }
             }
             $sid = "{$row->book_id}-{$row->paragraph}-{$row->word_start}-{$row->word_end}";
             $sid = "{$row->book_id}-{$row->paragraph}-{$row->word_start}-{$row->word_end}";
-            $result['sentences'][] = ['sid' => $sid, 'html' => $html];
+            $results[$para]['sentences'][] = ['sid' => $sid, 'html' => $html];
             if ($format === 'html') {
             if ($format === 'html') {
                 $class = $isOrigin ? 'sentence origin' : 'sentence';
                 $class = $isOrigin ? 'sentence origin' : 'sentence';
-                $result['display'][] = "<div class='{$class}' lang='{$channel->lang}' data-sid='{$sid}'>{$html}</div>";
+                $display[$para][] = "<div class='{$class}' lang='{$channel->lang}' data-sid='{$sid}'>{$html}</div>";
             } else {
             } else {
-                $result['display'][] = $html;
+                $display[$para][] = $html;
             }
             }
         }
         }
-        $result['notes'] = $allNotes;
 
 
-        return $result;
+        $paliTexts = app(PaliTextService::class);
+        foreach ($display as $para => $lines) {
+            if ($format !== 'html') {
+                // 其他格式一行一句
+                $results[$para]['display'] = implode("\n", $lines);
+
+                continue;
+            }
+            // html 格式加段落外壳;段后追加段落脚注列表(本段义注/复注条目)
+            $content = implode('', $lines);
+            $level = $paliTexts->headingLevel($book, $para);
+            $pClass = $paliTexts->paragraph($book, $para)['class'] ?? '';
+            $inner = $level > 0 ? "<h{$level}>{$content}</h{$level}>" : "<div class='para-block'>{$content}</div>";
+            $footnoteList = $this->renderFootnoteList($notes[$para] ?? []);
+            $results[$para]['display'] = "<div id='para-{$para}' class='{$area} {$pClass}' data-para='{$para}'>{$inner}{$footnoteList}</div>";
+        }
+
+        return $results;
     }
     }
 }
 }

+ 129 - 0
api-v13/app/Services/ReadingIndexService.php

@@ -0,0 +1,129 @@
+<?php
+
+namespace App\Services;
+
+use App\Facades\RedisCache;
+use App\Models\Sentence;
+
+/**
+ * 阅读的内容索引(纯能力,v3 阅读与三藏下载共用):某 channel 哪些书、哪些段有译文(句子 strlen > 0)。
+ *
+ * - **段号索引** `/read-index/{channel}/{book}`:这本书里有译文的段,存成连续区间;
+ * - **书号索引** `/read-index/{channel}/books`:有译文的书。整 channel 重建要几百毫秒,只在
+ *   「新出现一本书」或「可能少了一本书」时删。
+ *
+ * 只随句子失效({@see PaliContentService::paragraphChanged()},Sentence 的模型事件调用):
+ * 只有「有译文的段」可能变了才删,改一句译文的内容不动索引。批注不影响索引。
+ * **绕过模型事件的批量写入(`Sentence::where()->update()/delete()`、`DB::table('sentences')`)要自己调
+ * paragraphChanged()**,否则会读到旧索引直到过期。
+ */
+class ReadingIndexService
+{
+    /** @var array<string, list<int>> */
+    private array $paragraphs = [];
+
+    /**
+     * 有译文的书号,升序。
+     *
+     * @return list<int>
+     */
+    public function books(string $channel): array
+    {
+        return RedisCache::remember(
+            self::booksKey($channel),
+            (int) config('mint.cache.read_index_ttl'),
+            fn () => Sentence::where('channel_uid', $channel)
+                ->where('strlen', '>', 0)
+                ->distinct()
+                ->orderBy('book_id')
+                ->pluck('book_id')
+                ->map(fn ($book) => (int) $book)
+                ->all()
+        );
+    }
+
+    /**
+     * 这本书里有译文的段落号,升序。
+     *
+     * @return list<int>
+     */
+    public function paragraphs(string $channel, int $book): array
+    {
+        $key = self::paragraphsKey($channel, $book);
+        if (isset($this->paragraphs[$key])) {
+            return $this->paragraphs[$key];
+        }
+        // 存成连续区间 [[起, 止], …]:整本译完的书只有一个区间,展开成段号列表要八十多 KB
+        $ranges = RedisCache::remember(
+            $key,
+            (int) config('mint.cache.read_index_ttl'),
+            fn () => self::toRanges(Sentence::where('channel_uid', $channel)
+                ->where('book_id', $book)
+                ->where('strlen', '>', 0)
+                ->distinct()
+                ->orderBy('paragraph')
+                ->pluck('paragraph')
+                ->map(fn ($para) => (int) $para)
+                ->all())
+        );
+        $paras = [];
+        foreach ($ranges as [$from, $to]) {
+            array_push($paras, ...range($from, $to));
+        }
+
+        return $this->paragraphs[$key] = $paras;
+    }
+
+    /**
+     * 这本书「有译文的段」可能变了:删段号索引;书号索引按两个参数决定删不删。
+     *
+     * $mayAddBook(这本书现在有了译文)时,只有它不在已缓存的书号里才删;
+     * $mayRemoveBook(删了句子、strlen 变成 0、句子搬去了别的书或 channel)时一律删,下次重建。
+     */
+    public function forget(string $channel, int $book, bool $mayAddBook = false, bool $mayRemoveBook = false): void
+    {
+        $key = self::paragraphsKey($channel, $book);
+        RedisCache::forget($key);
+        unset($this->paragraphs[$key]);
+
+        if ($mayRemoveBook) {
+            RedisCache::forget(self::booksKey($channel));
+        } elseif ($mayAddBook) {
+            $books = RedisCache::get(self::booksKey($channel));
+            if (is_array($books) && ! in_array($book, $books, true)) {
+                RedisCache::forget(self::booksKey($channel));
+            }
+        }
+    }
+
+    /**
+     * 升序段号 → 连续区间。
+     *
+     * @param  list<int>  $paras
+     * @return list<array{int, int}>
+     */
+    public static function toRanges(array $paras): array
+    {
+        $ranges = [];
+        foreach ($paras as $para) {
+            $last = count($ranges) - 1;
+            if ($last >= 0 && $ranges[$last][1] === $para - 1) {
+                $ranges[$last][1] = $para;
+            } else {
+                $ranges[] = [$para, $para];
+            }
+        }
+
+        return $ranges;
+    }
+
+    private static function booksKey(string $channel): string
+    {
+        return "/read-index/{$channel}/books";
+    }
+
+    private static function paragraphsKey(string $channel, int $book): string
+    {
+        return "/read-index/{$channel}/{$book}";
+    }
+}

+ 260 - 0
api-v13/app/Services/V3/PaliTextService.php

@@ -0,0 +1,260 @@
+<?php
+
+namespace App\Services\V3;
+
+use App\Facades\RedisCache;
+use App\Models\PaliText;
+use App\Services\PaliContentService;
+
+/**
+ * 巴利原文段落表 `pali_texts` 的业务逻辑(2026-11-22 起,新代码里 pali_texts 的读取都放这里)。
+ *
+ * 这张表是经文静态数据,只有重新导入(`install:palitext` / `upgrade:palitext`)才会变,
+ * 所以按书缓存一个月,进程内再记一份:
+ *
+ * - 标题行(level < 8):一本书一个 key,阅读器算章节区间、导出排标题、章节范围都从这里取;
+ * - 全部段落的 level / class / 字节数:按 {@see self::CHUNK} 段一块,一本书最多一万六千段,
+ *   整本放一个 key 有四百多 KB,读一章只要其中一两块。
+ *
+ * 重新导入后调 {@see self::forgetBook()};改了缓存的结构就把 {@see self::VERSION} 加一(旧 key 自然过期)。
+ *
+ * 旧的 `App\Services\PaliTextService`(v2 在用)原样保留,不往那边加东西。
+ */
+class PaliTextService
+{
+    /** 缓存结构版本,改了缓存里存的字段就加一。 */
+    public const VERSION = 1;
+
+    /** 一个月。 */
+    public const TTL = 30 * 24 * 3600;
+
+    /** 段落按多少段一块缓存。 */
+    public const CHUNK = 1000;
+
+    /** 标题段的 level 上限(不含):1–7 是书 / 章 / 节等可导航节点,100 是正文。 */
+    public const HEADING_MAX_LEVEL = 8;
+
+    /** @var array<int, array<int, array{level: int, chapter_len: int, chapter_strlen: int, parent: int, toc: string}>> */
+    private array $headings = [];
+
+    /** @var array<string, array<int, array{int, string, int}>> */
+    private array $chunks = [];
+
+    /** @var array<int, array<int, int>> */
+    private array $flatChapters = [];
+
+    /**
+     * 一本书的全部标题段(level < 8),按段落号升序:段落号 => 标题信息。
+     *
+     * @return array<int, array{level: int, chapter_len: int, chapter_strlen: int, parent: int, toc: string}>
+     */
+    public function headings(int $book): array
+    {
+        if (isset($this->headings[$book])) {
+            return $this->headings[$book];
+        }
+        // 存成列表(段落号放在行里):键值对的 JSON 在键恰好是 0、1、2… 时会变成数组、读回来丢键
+        $rows = RedisCache::remember(
+            self::headingsKey($book),
+            self::TTL,
+            fn () => PaliText::where('book', $book)
+                ->where('level', '<', self::HEADING_MAX_LEVEL)
+                ->orderBy('paragraph')
+                ->get(['paragraph', 'level', 'chapter_len', 'chapter_strlen', 'parent', 'toc'])
+                ->map(fn (PaliText $row) => [
+                    (int) $row->paragraph, (int) $row->level, (int) $row->chapter_len,
+                    (int) $row->chapter_strlen, (int) $row->parent, (string) $row->toc,
+                ])
+                ->all()
+        );
+        $headings = [];
+        foreach ($rows as [$para, $level, $chapterLen, $chapterStrlen, $parent, $toc]) {
+            $headings[$para] = [
+                'level' => $level,
+                'chapter_len' => $chapterLen,
+                'chapter_strlen' => $chapterStrlen,
+                'parent' => $parent,
+                'toc' => $toc,
+            ];
+        }
+
+        return $this->headings[$book] = $headings;
+    }
+
+    /**
+     * 某段是标题段时返回它的标题信息,否则 null。
+     *
+     * @return array{level: int, chapter_len: int, chapter_strlen: int, parent: int, toc: string}|null
+     */
+    public function heading(int $book, int $para): ?array
+    {
+        return $this->headings($book)[$para] ?? null;
+    }
+
+    /**
+     * 段落是章节标题时返回标题级别(1–7),否则 0。
+     */
+    public function headingLevel(int $book, int $para): int
+    {
+        return $this->heading($book, $para)['level'] ?? 0;
+    }
+
+    /**
+     * 某段所在的书(level = 1 且段落号不大于它的最后一个标题段),没有返回 null。
+     *
+     * @return array{para: int, level: int, chapter_len: int, chapter_strlen: int, parent: int, toc: string}|null
+     */
+    public function bookStart(int $book, int $para): ?array
+    {
+        $found = null;
+        foreach ($this->headings($book) as $paragraph => $heading) {
+            if ($paragraph > $para) {
+                break;
+            }
+            if ($heading['level'] === 1) {
+                $found = ['para' => $paragraph] + $heading;
+            }
+        }
+
+        return $found;
+    }
+
+    /**
+     * 章节起始段落号 → 段落闭区间 [起, 止],长度取 chapter_len。
+     * 正文段(不是标题)没有 chapter_len,区间只有它自己;pali_texts 里没有这段返回 null。
+     *
+     * @return array{int, int}|null
+     */
+    public function chapterRange(int $book, int $chapter): ?array
+    {
+        $heading = $this->heading($book, $chapter);
+        if ($heading === null) {
+            return $this->paragraph($book, $chapter) === null ? null : [$chapter, $chapter];
+        }
+
+        return [$chapter, $chapter + max(1, $heading['chapter_len']) - 1];
+    }
+
+    /**
+     * 平铺的章节:每个标题段(level < 8)是一章的开头,到下一个标题段之前为止;章节按顺序排、不嵌套,
+     * 一段只属于一章。最后一章到它自己的 chapter_len 为止。章节起点 => 终点(含)。
+     *
+     * 与 chapter_len 的「父章包含子章」不同,这是阅读缓存用的切法({@see PaliContentService::readChapters()})。
+     *
+     * @return array<int, int>
+     */
+    public function flatChapters(int $book): array
+    {
+        if (isset($this->flatChapters[$book])) {
+            return $this->flatChapters[$book];
+        }
+        $chapters = [];
+        $starts = array_keys($this->headings($book));
+        foreach ($starts as $i => $start) {
+            $chapters[$start] = isset($starts[$i + 1])
+                ? $starts[$i + 1] - 1
+                : $start + max(1, $this->headings($book)[$start]['chapter_len']) - 1;
+        }
+
+        return $this->flatChapters[$book] = $chapters;
+    }
+
+    /**
+     * 某段所在平铺章节的起点({@see self::flatChapters()});排在第一个标题段之前、或超出最后一章的返回 null。
+     */
+    public function flatChapterOf(int $book, int $para): ?int
+    {
+        $found = null;
+        foreach ($this->flatChapters($book) as $start => $end) {
+            if ($start > $para) {
+                break;
+            }
+            $found = $para <= $end ? $start : null;
+        }
+
+        return $found;
+    }
+
+    /**
+     * 区间内各段的 level / class / 字节数:段落号 => 信息。pali_texts 里没有的段不出现。
+     *
+     * @return array<int, array{level: int, class: string, length: int}>
+     */
+    public function paragraphs(int $book, int $from, int $to): array
+    {
+        $result = [];
+        for ($chunk = intdiv(max(0, $from), self::CHUNK); $chunk <= intdiv(max(0, $to), self::CHUNK); $chunk++) {
+            foreach ($this->chunk($book, $chunk) as $para => [$level, $class, $length]) {
+                if ($para >= $from && $para <= $to) {
+                    $result[$para] = ['level' => $level, 'class' => $class, 'length' => $length];
+                }
+            }
+        }
+
+        return $result;
+    }
+
+    /**
+     * 单段的 level / class / 字节数,pali_texts 里没有返回 null。
+     *
+     * @return array{level: int, class: string, length: int}|null
+     */
+    public function paragraph(int $book, int $para): ?array
+    {
+        return $this->paragraphs($book, $para, $para)[$para] ?? null;
+    }
+
+    /**
+     * 重新导入某本书后调用,删掉它的全部缓存。
+     */
+    public function forgetBook(int $book): void
+    {
+        RedisCache::forget(self::headingsKey($book));
+        $max = (int) PaliText::where('book', $book)->max('paragraph');
+        // 段数可能变少,多删一块兜底
+        for ($chunk = 0; $chunk <= intdiv($max, self::CHUNK) + 1; $chunk++) {
+            RedisCache::forget(self::chunkKey($book, $chunk));
+        }
+        unset($this->headings[$book], $this->flatChapters[$book]);
+        $this->chunks = array_filter($this->chunks, fn ($key) => ! str_starts_with($key, "{$book}-"), ARRAY_FILTER_USE_KEY);
+    }
+
+    /**
+     * 一块段落:段落号 => [level, class, 字节数]。缓存里存成 [段落号, level, class, 字节数] 的列表。
+     *
+     * @return array<int, array{int, string, int}>
+     */
+    private function chunk(int $book, int $chunk): array
+    {
+        $memo = "{$book}-{$chunk}";
+        if (isset($this->chunks[$memo])) {
+            return $this->chunks[$memo];
+        }
+        $rows = RedisCache::remember(
+            self::chunkKey($book, $chunk),
+            self::TTL,
+            fn () => PaliText::where('book', $book)
+                ->whereBetween('paragraph', [$chunk * self::CHUNK, ($chunk + 1) * self::CHUNK - 1])
+                ->orderBy('paragraph')
+                ->get(['paragraph', 'level', 'class', 'lenght'])
+                ->map(fn (PaliText $row) => [(int) $row->paragraph, (int) $row->level, (string) $row->class, (int) $row->lenght])
+                ->all()
+        );
+        $paragraphs = [];
+        foreach ($rows as [$para, $level, $class, $length]) {
+            $paragraphs[$para] = [$level, $class, $length];
+        }
+
+        return $this->chunks[$memo] = $paragraphs;
+    }
+
+    private static function headingsKey(int $book): string
+    {
+        return '/pali-text/v'.self::VERSION."/{$book}/headings";
+    }
+
+    private static function chunkKey(int $book, int $chunk): string
+    {
+        return '/pali-text/v'.self::VERSION."/{$book}/paragraphs/{$chunk}";
+    }
+}

+ 18 - 14
api-v13/app/Services/V3/TipitakaExportBuilder.php

@@ -3,7 +3,6 @@
 namespace App\Services\V3;
 namespace App\Services\V3;
 
 
 use App\Models\Channel;
 use App\Models\Channel;
-use App\Models\PaliText;
 use App\Services\TipitakaCatalogService;
 use App\Services\TipitakaCatalogService;
 use DOMDocument;
 use DOMDocument;
 use DOMXPath;
 use DOMXPath;
@@ -30,6 +29,7 @@ class TipitakaExportBuilder
     public function __construct(
     public function __construct(
         private readonly TipitakaReadingService $reading,
         private readonly TipitakaReadingService $reading,
         private readonly TipitakaCatalogService $catalog,
         private readonly TipitakaCatalogService $catalog,
+        private readonly PaliTextService $paliTexts,
     ) {}
     ) {}
 
 
     /**
     /**
@@ -160,12 +160,7 @@ class TipitakaExportBuilder
      */
      */
     private function headingLevels(array $work): array
     private function headingLevels(array $work): array
     {
     {
-        return PaliText::where('book', $work['book'])
-            ->whereBetween('paragraph', [$work['para'], $work['end']])
-            ->where('level', '<', 8)
-            ->pluck('level', 'paragraph')
-            ->map(fn ($level) => (int) $level)
-            ->all();
+        return array_map(fn (array $heading) => $heading['level'], $this->headingsIn($work));
     }
     }
 
 
     /**
     /**
@@ -176,13 +171,22 @@ class TipitakaExportBuilder
      */
      */
     private function headings(array $work): array
     private function headings(array $work): array
     {
     {
-        return PaliText::where('book', $work['book'])
-            ->whereBetween('paragraph', [$work['para'], $work['end']])
-            ->where('level', '<', 8)
-            ->orderBy('paragraph')
-            ->get(['paragraph', 'level', 'toc'])
-            ->mapWithKeys(fn ($row) => [(int) $row->paragraph => [(int) $row->level, (string) $row->toc]])
-            ->all();
+        return array_map(fn (array $heading) => [$heading['level'], $heading['toc']], $this->headingsIn($work));
+    }
+
+    /**
+     * 作品区间里的标题段(缓存的经文静态数据),按段落号升序。
+     *
+     * @param  array<string, mixed>  $work
+     * @return array<int, array{level: int, chapter_len: int, chapter_strlen: int, parent: int, toc: string}>
+     */
+    private function headingsIn(array $work): array
+    {
+        return array_filter(
+            $this->paliTexts->headings((int) $work['book']),
+            fn (int $para) => $para >= $work['para'] && $para <= $work['end'],
+            ARRAY_FILTER_USE_KEY,
+        );
     }
     }
 
 
     /**
     /**

+ 105 - 68
api-v13/app/Services/V3/TipitakaReadingService.php

@@ -2,10 +2,8 @@
 
 
 namespace App\Services\V3;
 namespace App\Services\V3;
 
 
-use App\Models\PaliText;
-use App\Models\Sentence;
 use App\Services\PaliContentService;
 use App\Services\PaliContentService;
-use Illuminate\Database\Eloquent\Builder;
+use App\Services\ReadingIndexService;
 use Illuminate\Validation\ValidationException;
 use Illuminate\Validation\ValidationException;
 
 
 /**
 /**
@@ -33,11 +31,18 @@ class TipitakaReadingService
      */
      */
     public const MAX_PARAGRAPHS_PER_PAGE = 200;
     public const MAX_PARAGRAPHS_PER_PAGE = 200;
 
 
-    public function __construct(private readonly PaliContentService $paliService) {}
+    public function __construct(
+        private readonly PaliContentService $paliService,
+        private readonly PaliTextService $paliTexts,
+        private readonly ReadingIndexService $index,
+    ) {}
 
 
     /**
     /**
      * 取一块译文。
      * 取一块译文。
      *
      *
+     * 候选段、游标、进度都在「有译文的段号」索引上算({@see ReadingIndexService},命中时不查库),
+     * 正文按书一次交给 {@see PaliContentService::readParagraphs()}。
+     *
      * @param  array<string, mixed>  $filters  已经过 FormRequest 校验的查询参数
      * @param  array<string, mixed>  $filters  已经过 FormRequest 校验的查询参数
      * @return array{items: array<int, array<string, mixed>>, meta: array<string, mixed>}
      * @return array{items: array<int, array<string, mixed>>, meta: array<string, mixed>}
      */
      */
@@ -49,24 +54,15 @@ class TipitakaReadingService
             $unit === 'byte' ? self::MAX_BYTES_PER_PAGE : self::MAX_PARAGRAPHS_PER_PAGE
             $unit === 'byte' ? self::MAX_BYTES_PER_PAGE : self::MAX_PARAGRAPHS_PER_PAGE
         );
         );
 
 
-        $scope = $this->scopedQuery($channel, $filters);
+        $range = $this->scopeRange($filters);
+        $after = isset($filters['after']) ? $this->parseCursor((string) $filters['after']) : null;
 
 
-        // 多取一行用来判断后面还有没有,不必再查一次
+        // 多取一段用来判断后面还有没有
         $want = $unit === 'byte'
         $want = $unit === 'byte'
             ? self::MAX_PARAGRAPHS_PER_PAGE
             ? self::MAX_PARAGRAPHS_PER_PAGE
             : min($pageSize, self::MAX_PARAGRAPHS_PER_PAGE);
             : min($pageSize, self::MAX_PARAGRAPHS_PER_PAGE);
 
 
-        $candidates = (clone $scope)
-            ->when($filters['after'] ?? null, fn (Builder $q, string $after) => $this->applyCursor($q, $after))
-            ->distinct()
-            ->select(['book_id', 'paragraph'])
-            ->orderBy('book_id')
-            ->orderBy('paragraph')
-            ->limit($want + 1)
-            ->get()
-            ->map(fn ($row) => ['book' => (int) $row->book_id, 'para' => (int) $row->paragraph])
-            ->all();
-
+        $candidates = $this->candidates($channel, $range, $after, $want + 1);
         $hasMoreBeyondWant = count($candidates) > $want;
         $hasMoreBeyondWant = count($candidates) > $want;
         $candidates = array_slice($candidates, 0, $want);
         $candidates = array_slice($candidates, 0, $want);
 
 
@@ -78,9 +74,19 @@ class TipitakaReadingService
         $format = $filters['format'] ?? 'html';
         $format = $filters['format'] ?? 'html';
         $include = $filters['include'] ?? 'display';
         $include = $filters['include'] ?? 'display';
 
 
+        // 结果可以跨书:按书分组,一本书一次批量取
+        $byBook = [];
+        foreach ($slice as $coord) {
+            $byBook[$coord['book']][] = $coord['para'];
+        }
+        $rendered = [];
+        foreach ($byBook as $book => $paras) {
+            $rendered[$book] = $this->paliService->readParagraphs($book, $paras, $channel, $format);
+        }
+
         $items = [];
         $items = [];
         foreach ($slice as $coord) {
         foreach ($slice as $coord) {
-            $paragraph = $this->paliService->readParagraph($coord['book'], $coord['para'], $channel, $format);
+            $paragraph = $rendered[$coord['book']][$coord['para']];
             if (empty($paragraph['display'])) {
             if (empty($paragraph['display'])) {
                 continue;
                 continue;
             }
             }
@@ -98,36 +104,27 @@ class TipitakaReadingService
                 // 本块覆盖的最后一段。渲染为空的段落会被剔出 data 但仍算在块内,
                 // 本块覆盖的最后一段。渲染为空的段落会被剔出 data 但仍算在块内,
                 // 所以游标按 slice 推进而不是按 data 推进,否则会卡在那一段上打转
                 // 所以游标按 slice 推进而不是按 data 推进,否则会卡在那一段上打转
                 'next_cursor' => $hasMore && $last ? "{$last['book']}-{$last['para']}" : null,
                 'next_cursor' => $hasMore && $last ? "{$last['book']}-{$last['para']}" : null,
-            ] + $this->progressMeta($scope, $filters, $last),
+            ] + $this->progressMeta($channel, $range, $last),
         ];
         ];
     }
     }
 
 
     /**
     /**
-     * 按 filter 收窄的**基础查询**:只有 where,不带 select / distinct / order。
-     *
-     * 分页取数和 count 两边对它的要求不一样(一个要去重的两列,一个要聚合),
-     * 混在一起会拼出 `select distinct book_id, paragraph, count(...)` 这种非法 SQL。
-     * 所以基础查询保持干净,各自 clone 之后再加自己那套。
+     * 按 filter 收窄的范围:不带 book 是整个 channel(null),带 book 是这本书里的段落闭区间。
      *
      *
      * @param  array<string, mixed>  $filters
      * @param  array<string, mixed>  $filters
-     * @return Builder<Sentence>
+     * @return array{book: int, from: int, to: int}|null
      */
      */
-    private function scopedQuery(string $channel, array $filters): Builder
+    private function scopeRange(array $filters): ?array
     {
     {
-        $query = Sentence::query()
-            ->where('channel_uid', $channel)
-            ->where('strlen', '>', 0);
-
         if (! isset($filters['book'])) {
         if (! isset($filters['book'])) {
-            return $query;
+            return null;
         }
         }
         $book = (int) $filters['book'];
         $book = (int) $filters['book'];
-        $query->where('book_id', $book);
 
 
         if (isset($filters['chapter'])) {
         if (isset($filters['chapter'])) {
             [$from, $to] = $this->chapterRange($book, (int) $filters['chapter']);
             [$from, $to] = $this->chapterRange($book, (int) $filters['chapter']);
 
 
-            return $query->whereBetween('paragraph', [$from, $to]);
+            return ['book' => $book, 'from' => $from, 'to' => $to];
         }
         }
         if (isset($filters['para'])) {
         if (isset($filters['para'])) {
             $from = (int) $filters['para'];
             $from = (int) $filters['para'];
@@ -136,10 +133,55 @@ class TipitakaReadingService
                 throw ValidationException::withMessages(['to' => __('site.invalid_parameter')]);
                 throw ValidationException::withMessages(['to' => __('site.invalid_parameter')]);
             }
             }
 
 
-            return $query->whereBetween('paragraph', [$from, $to]);
+            return ['book' => $book, 'from' => $from, 'to' => $to];
+        }
+
+        return ['book' => $book, 'from' => PHP_INT_MIN, 'to' => PHP_INT_MAX];
+    }
+
+    /**
+     * 范围内有译文的段(句子 strlen > 0),按 (book, para) 升序,排在游标之后,最多 $limit 段。
+     *
+     * @param  array{book: int, from: int, to: int}|null  $range
+     * @param  array{int, int}|null  $after
+     * @return list<array{book: int, para: int}>
+     */
+    private function candidates(string $channel, ?array $range, ?array $after, int $limit): array
+    {
+        $books = $range === null ? $this->index->books($channel) : [$range['book']];
+        $result = [];
+        foreach ($books as $book) {
+            if ($after !== null && $book < $after[0]) {
+                continue;
+            }
+            foreach ($this->paragraphsIn($channel, $book, $range) as $para) {
+                if ($after !== null && $book === $after[0] && $para <= $after[1]) {
+                    continue;
+                }
+                $result[] = ['book' => $book, 'para' => $para];
+                if (count($result) >= $limit) {
+                    return $result;
+                }
+            }
+        }
+
+        return $result;
+    }
+
+    /**
+     * 这本书里有译文、且在范围内的段号,升序。
+     *
+     * @param  array{book: int, from: int, to: int}|null  $range
+     * @return list<int>
+     */
+    private function paragraphsIn(string $channel, int $book, ?array $range): array
+    {
+        $paras = $this->index->paragraphs($channel, $book);
+        if ($range === null) {
+            return $paras;
         }
         }
 
 
-        return $query;
+        return array_values(array_filter($paras, fn (int $para) => $para >= $range['from'] && $para <= $range['to']));
     }
     }
 
 
     /**
     /**
@@ -151,28 +193,24 @@ class TipitakaReadingService
      */
      */
     public function chapterRange(int $book, int $chapter): array
     public function chapterRange(int $book, int $chapter): array
     {
     {
-        $head = PaliText::where('book', $book)->where('paragraph', $chapter)->first();
-        if (! $head) {
+        $range = $this->paliTexts->chapterRange($book, $chapter);
+        if ($range === null) {
             abort(404, __('site.not_found'));
             abort(404, __('site.not_found'));
         }
         }
 
 
-        return [$chapter, $chapter + max(1, (int) $head->chapter_len) - 1];
+        return $range;
     }
     }
 
 
     /**
     /**
-     * 游标 `{book}-{para}`:取排在它之后的行。
-     *
-     * 用行值比较 `(book_id, paragraph) > (?, ?)` 而不是 `book > ? or (book = ? and para > ?)`,
-     * 一是短,二是 Postgres 能直接走 (book_id, paragraph, …) 那条复合索引。
+     * 游标 `{book}-{para}` → [book, para]。
      *
      *
-     * @param  Builder<Sentence>  $query
-     * @return Builder<Sentence>
+     * @return array{int, int}
      */
      */
-    private function applyCursor(Builder $query, string $after): Builder
+    private function parseCursor(string $after): array
     {
     {
-        [$book, $para] = array_map('intval', explode('-', $after, 2));
+        [$book, $para] = array_map('intval', explode('-', $after, 2)) + [0, 0];
 
 
-        return $query->whereRaw('(book_id, paragraph) > (?, ?)', [$book, $para]);
+        return [$book, $para];
     }
     }
 
 
     /**
     /**
@@ -201,8 +239,7 @@ class TipitakaReadingService
     }
     }
 
 
     /**
     /**
-     * 取这些段落的原文字节数。按书分组、每本用首尾段落号一次查回整段区间,
-     * 避免几百个值的 IN 列表;区间里多查回来几行比拼 IN 便宜。
+     * 取这些段落的原文字节数({@see PaliTextService},缓存的经文静态数据)。
      *
      *
      * @param  array<int, array{book: int, para: int}>  $candidates
      * @param  array<int, array{book: int, para: int}>  $candidates
      * @return array<int, array<int, int>> book => (para => 字节数)
      * @return array<int, array<int, int>> book => (para => 字节数)
@@ -216,10 +253,10 @@ class TipitakaReadingService
 
 
         $lengths = [];
         $lengths = [];
         foreach ($byBook as $book => $paras) {
         foreach ($byBook as $book => $paras) {
-            $lengths[$book] = PaliText::where('book', $book)
-                ->whereBetween('paragraph', [min($paras), max($paras)])
-                ->pluck('lenght', 'paragraph')
-                ->all();
+            $lengths[$book] = array_map(
+                fn (array $row) => $row['length'],
+                $this->paliTexts->paragraphs($book, min($paras), max($paras))
+            );
         }
         }
 
 
         return $lengths;
         return $lengths;
@@ -228,30 +265,30 @@ class TipitakaReadingService
     /**
     /**
      * 进度用的 total / remaining,**只在带了 book 过滤时给**。
      * 进度用的 total / remaining,**只在带了 book 过滤时给**。
      *
      *
-     * 不带过滤时结果集是整个 channel(实测最大的 52 万段),每页 count 一次要
-     * 八百毫秒、两百多 MB,不值得。那种场景用 next_cursor 判断结束。
+     * 不带过滤时结果集是整个 channel(实测最大的 52 万段),要把每本书的段号索引都读一遍,
+     * 不值得。那种场景用 next_cursor 判断结束。
      *
      *
-     * @param  Builder<Sentence>  $scope
-     * @param  array<string, mixed>  $filters
+     * @param  array{book: int, from: int, to: int}|null  $range
      * @param  array{book: int, para: int}|null  $last
      * @param  array{book: int, para: int}|null  $last
      * @return array<string, int>
      * @return array<string, int>
      */
      */
-    private function progressMeta(Builder $scope, array $filters, ?array $last): array
+    private function progressMeta(string $channel, ?array $range, ?array $last): array
     {
     {
-        if (! isset($filters['book'])) {
+        if ($range === null) {
             return [];
             return [];
         }
         }
 
 
-        $countIn = fn (Builder $q): int => (int) (
-            $q->selectRaw('count(distinct (book_id, paragraph)) as aggregate')->first()?->aggregate ?? 0
-        );
-
-        $total = $countIn(clone $scope);
-        $remaining = $last === null
-            ? 0
-            : $countIn($this->applyCursor(clone $scope, "{$last['book']}-{$last['para']}"));
+        $paras = $this->paragraphsIn($channel, $range['book'], $range);
+        $remaining = 0;
+        if ($last !== null) {
+            foreach ($paras as $para) {
+                if ($para > $last['para']) {
+                    $remaining++;
+                }
+            }
+        }
 
 
-        return ['total' => $total, 'remaining' => $remaining];
+        return ['total' => count($paras), 'remaining' => $remaining];
     }
     }
 
 
     /**
     /**

+ 5 - 0
api-v13/config/mint.php

@@ -122,6 +122,11 @@ return [
     'cache' => [
     'cache' => [
         // 这个值prod,staging无需设置
         // 这个值prod,staging无需设置
         'expire' => env('CACHE_EXPIRE', 36000),
         'expire' => env('CACHE_EXPIRE', 36000),
+        // 阅读段落成品(PaliContentService::readParagraph):句子、批注改动有精确失效,
+        // 术语释义、引用句子、channel 名称等没有,改了最多旧这么久
+        'read_paragraph_ttl' => env('CACHE_READ_PARAGRAPH_TTL', 86400),
+        // 有译文的书号 / 段号索引(ReadingIndexService):随句子改动失效,过期只为回收空间
+        'read_index_ttl' => env('CACHE_READ_INDEX_TTL', 7 * 86400),
     ],
     ],
 
 
     /**
     /**

+ 354 - 0
api-v13/documents/reading-cache-plan.html

@@ -0,0 +1,354 @@
+<!doctype html>
+<html lang="zh-Hans">
+<head>
+<meta charset="utf-8">
+<meta name="viewport" content="width=device-width, initial-scale=1">
+<title>段落缓存方案</title>
+<style>
+:root{
+  --bg:#f6f8fb; --surface:#fff; --surface-2:#f1f4f8; --border:#dfe5ec; --text:#1d2733; --muted:#5f6f83;
+  --primary:#066fd1; --primary-lt:#e7f1fc; --ok:#2f9e44; --ok-lt:#e8f6eb; --warn:#e67700; --warn-lt:#fff3e0;
+  --danger:#d63939; --danger-lt:#fdecec; --violet:#7048e8; --violet-lt:#f0ebff;
+  --mono:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;
+}
+@media (prefers-color-scheme: dark){:root:not([data-theme="light"]){
+  --bg:#11161d; --surface:#18202a; --surface-2:#1f2935; --border:#2c3746; --text:#e4e9f0; --muted:#97a6b8;
+  --primary:#4c9bf0; --primary-lt:#1a2f4d; --ok:#51cf66; --ok-lt:#16301d; --warn:#ffa94d; --warn-lt:#3a2a12;
+  --danger:#ff6b6b; --danger-lt:#3a1a1a; --violet:#9775fa; --violet-lt:#271f45;
+}}
+:root[data-theme="dark"]{
+  --bg:#11161d; --surface:#18202a; --surface-2:#1f2935; --border:#2c3746; --text:#e4e9f0; --muted:#97a6b8;
+  --primary:#4c9bf0; --primary-lt:#1a2f4d; --ok:#51cf66; --ok-lt:#16301d; --warn:#ffa94d; --warn-lt:#3a2a12;
+  --danger:#ff6b6b; --danger-lt:#3a1a1a; --violet:#9775fa; --violet-lt:#271f45;
+}
+*{box-sizing:border-box}
+body{margin:0;background:var(--bg);color:var(--text);font:15px/1.7 -apple-system,BlinkMacSystemFont,"Segoe UI","PingFang SC","Microsoft YaHei",sans-serif}
+.wrap{max-width:1100px;margin:0 auto;padding:28px 16px 80px}
+h1{font-size:26px;margin:0 0 4px}
+.sub{color:var(--muted);margin:0 0 24px}
+h2{font-size:19px;margin:40px 0 12px;padding-bottom:6px;border-bottom:2px solid var(--border)}
+h3{font-size:16px;margin:22px 0 8px}
+p{margin:0 0 12px}
+code{font:13px var(--mono);background:var(--surface-2);padding:1px 5px;border-radius:4px}
+.card{background:var(--surface);border:1px solid var(--border);border-radius:10px;padding:16px 18px;margin:12px 0}
+table{border-collapse:collapse;width:100%;font-size:14px;background:var(--surface)}
+th,td{border:1px solid var(--border);padding:7px 10px;text-align:left;vertical-align:top}
+th{background:var(--surface-2);font-weight:600}
+td.num{text-align:right;font-variant-numeric:tabular-nums;white-space:nowrap}
+.tbl{overflow-x:auto;margin:10px 0}
+.pill{display:inline-block;font-size:12px;padding:0 8px;border-radius:10px;font-weight:600}
+.l0{background:var(--violet-lt);color:var(--violet)}
+.l1{background:var(--ok-lt);color:var(--ok)}
+.l2{background:var(--primary-lt);color:var(--primary)}
+.l3{background:var(--ok-lt);color:var(--ok)}
+.l4{background:var(--violet-lt);color:var(--violet)}
+.gen{background:var(--warn-lt);color:var(--warn)}
+.cold{background:var(--danger-lt);color:var(--danger)}
+.bad{color:var(--danger);font-weight:600}
+.good{color:var(--ok);font-weight:600}
+.kpis{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:10px;margin:14px 0}
+.kpi{background:var(--surface);border:1px solid var(--border);border-radius:10px;padding:12px 14px}
+.kpi b{display:block;font-size:24px;line-height:1.2}
+.kpi span{color:var(--muted);font-size:13px}
+@media(max-width:720px){.kpis{grid-template-columns:repeat(2,minmax(0,1fr))}}
+.diagram{background:var(--surface);border:1px solid var(--border);border-radius:10px;padding:10px;overflow-x:auto}
+.diagram svg{display:block;min-width:900px;width:100%;height:auto}
+.legend{display:flex;flex-wrap:wrap;gap:8px 18px;font-size:13px;color:var(--muted);margin:10px 4px 0}
+.legend i{display:inline-block;width:26px;height:0;border-top:3px solid;vertical-align:middle;margin-right:6px}
+ol li,ul li{margin:4px 0}
+.note{border-left:4px solid var(--warn);background:var(--warn-lt);padding:10px 14px;border-radius:6px;margin:12px 0}
+.decide{border-left:4px solid var(--primary);background:var(--primary-lt);padding:10px 14px;border-radius:6px;margin:12px 0}
+</style>
+</head>
+<body>
+<div class="wrap">
+
+<h1>阅读段落:冷启动与缓存</h1>
+<p class="sub">范围:<code>/v3/tipitaka-reading</code>、Laravel library 阅读器、三藏下载打包(含 mobile 离线包)。两大块:<b>A. 冷启动</b>(没命中时一块只查几次库)与 <b>B. 缓存</b>(命中时不查库)。2026-11-22,方案稿,未动代码。</p>
+
+<h2>现状(实测)</h2>
+<p>同一块 200 段(book 213),<code>TipitakaReadingService::page()</code>:</p>
+<div class="kpis">
+  <div class="kpi"><b class="bad">1954</b><span>cs6 冷启动查询 · 1215 ms</span></div>
+  <div class="kpi"><b class="bad">2009</b><span>元亨寺·CBETA 冷启动查询 · 1384 ms(库 617 ms)</span></div>
+  <div class="kpi"><b class="bad">403</b><span>cs6 缓存全部命中仍要查 · 164 ms</span></div>
+  <div class="kpi"><b class="good">≈4 / 0</b><span>目标:冷启动 / 命中时查询次数</span></div>
+</div>
+
+<h3>冷启动(没命中)在查什么</h3>
+<div class="tbl"><table>
+<tr><th>查询</th><th>cs6</th><th>CBETA</th><th>为什么这么多</th></tr>
+<tr><td><code>discussions</code>(挂在句子上的批注)</td><td class="num">1151</td><td class="num">1207(343 ms)</td><td><code>injectAnnotationNotes()</code> <b>逐句</b>查一次</td></tr>
+<tr><td><code>sentences</code>(该段句子)</td><td class="num">200</td><td class="num">200</td><td><code>renderReadSentences()</code> 逐段查</td></tr>
+<tr><td><code>channels</code>(同一个 channel)</td><td class="num">200</td><td class="num">200</td><td>逐段把同一行查 200 遍</td></tr>
+<tr><td><code>pali_texts.level</code> / <code>.class</code></td><td class="num">400</td><td class="num">399</td><td>逐段两次,经文静态数据</td></tr>
+<tr><td><code>page()</code> 候选段 + 两次 count</td><td class="num">3</td><td class="num">3</td><td>每块</td></tr>
+</table></div>
+<p>CBETA 那块 1384 ms 里数据库占 617 ms,其余约 770 ms 是 PHP 渲染与写缓存。另外两处这两个样本没触发、但模板多的 channel 会放大:</p>
+<ul>
+<li><b>Markup 的取数是「一次 <code>renderMany</code> 一批」</b>(术语 <code>TermLoader</code>、引用句子 <code>SentenceLoader</code>、channel 名 <code>ChannelDirectory</code>、<code>QaLoader</code>、<code>TplLoader</code> 都是 <code>whereIn</code>),但现在一段调用一次 <code>renderMany</code>,所以是<b>每段一批</b>:200 段带术语就是 200 次术语查询。</li>
+<li><b>批注正文逐条渲染</b>:<code>renderAnnotationNote()</code> 每条批注单独调一次 <code>MarkupService::render()</code>,批注里有术语就每条各查一次。</li>
+</ul>
+
+<h3>命中时还在查什么</h3>
+<div class="tbl"><table>
+<tr><th>查询</th><th>次数 / 200 段</th><th>出处</th><th>性质</th></tr>
+<tr><td><code>pali_texts.level</code>(是不是标题段)</td><td class="num">200</td><td><code>readParagraph()</code> 进缓存前的 <code>paragraphLevel()</code></td><td>经文静态数据</td></tr>
+<tr><td><code>pali_texts.class</code>(段落外壳的 class)</td><td class="num">200</td><td><code>readParagraph()</code> 命中后拼外壳</td><td>经文静态数据</td></tr>
+<tr><td><code>distinct (book_id, paragraph)</code> 候选段</td><td class="num">1</td><td><code>page()</code></td><td>随译文变化</td></tr>
+<tr><td><code>count(distinct …)</code> 进度 total / remaining</td><td class="num">2</td><td><code>page()</code> 的 <code>progressMeta()</code></td><td>随译文变化</td></tr>
+<tr><td>(字节模式)<code>pali_texts.lenght</code></td><td class="num">每书 1</td><td><code>page()</code> 的 <code>paragraphLengths()</code></td><td>经文静态数据</td></tr>
+</table></div>
+<ul>
+<li><b>Laravel 阅读器</b>按章读:<code>resolveDisplayRange()</code> 算区间,<code>fetchRangeContent()</code> 对 <code>range($start, $end)</code> 逐段调 <code>readParagraph()</code>,整章一次,不切块。实测 213-34(下钻后 27 段):第一次 384 次查询(批注 247 次),第二次 83 次(正文 51 次 + 页面外围约 32 次)。</li>
+<li><b>TTL</b> 用的是通用的 <code>mint.cache.expire</code>:本地 10 秒、默认 10 小时,过期就整段重渲。</li>
+<li>一块 200 段就是 200 次 Redis 往返(本机看不出,生产上乘以网络延迟)。</li>
+</ul>
+
+<h2>A. 冷启动:按块渲染,一块只查几次库</h2>
+
+<div class="card">
+<p><span class="pill cold">A1 批量渲染</span> &nbsp;<code>PaliContentService</code> 新增 <code>readParagraphs(int $book, array $paras, string $channel, string $format)</code>,单段的 <code>readParagraph()</code> 改为调它(传一段)——<b>只有一份渲染逻辑</b>。没命中的那些段一起渲染:</p>
+<ol>
+<li><b>channel 查一次</b>(现在每段一次)。</li>
+<li><b>句子查一次</b>:<code>where book, channel, paragraph in (未命中的段) order by paragraph, word_start</code>。</li>
+<li><b>批注查一次</b>:所有句子的 uid 一次 <code>whereIn('res_id', …)</code>,在 PHP 里按句分组;<code>injectAnnotationNotes()</code> 改为接收已取好的批注,不再自己查。</li>
+<li><b>标题级别与 class 查 L0</b>(见 B 部分),不落库。</li>
+<li><b>一次 <code>renderManyAs()</code> 渲染全部句子</b>:Resolver 收集整块的术语 / 引用 / 模板,各类只查一次。</li>
+<li><b>批注正文也合并成一次 <code>renderMany()</code></b>(现在每条批注一次 <code>render()</code>)。</li>
+</ol>
+<p>结果:200 段从约 2000 次查询降到<b>约 4 次</b>(channel、句子、批注、<code>page()</code> 的候选),外加每类模板数据各一次。CBETA 那块的 617 ms 库时间预计降到几十 ms;剩下的是渲染本身的 CPU,改完再量。</p>
+</div>
+
+<div class="card">
+<p><span class="pill cold">A2 谁受益</span></p>
+<ul>
+<li><code>page()</code>:一块里没命中的段交给 <code>readParagraphs()</code> 一次渲染(与 B 的批量读同一个入口)。</li>
+<li>阅读器:L3 章节缓存没命中时,整章的段一次交给 <code>readParagraphs()</code>。</li>
+<li>下载打包:经 <code>page()</code> 自动受益。cs6 整 channel html 打包 2286 s,大部分花在逐句批注与逐段查询上,这一步对它影响最大。</li>
+</ul>
+<p>注意:批量取句子时要保持现有口径——<code>strlen &gt; 0</code>、句子按 <code>word_start</code> 排、段内「有评估的句子之外补灰色对勾」的规则按段计算,不能变成按块计算。</p>
+</div>
+
+<h2>B. 缓存</h2>
+<h3>B 的方案:五块缓存,只给 readParagraph 改内部、不套外层</h3>
+
+<p>两个调用形状不同,缓存也分开:</p>
+<ul>
+<li><b>阅读器</b>按章读:<code>resolveDisplayRange()</code> 算出整章区间,<code>fetchRangeContent()</code> 一次拼完,<b>不切块</b>。区间只由经文静态数据决定,同一章每次都一样 → 缓存整章成品,一次 GET。</li>
+<li><b><code>/v3/tipitaka-reading</code> 与下载打包</b>按块读:块的边界取决于调用方的 <code>page_size</code> / <code>unit</code> / 游标,各不相同 → 缓存段落与索引,按块现拼。</li>
+</ul>
+
+<div class="card">
+<p><span class="pill l0">L0 书目元数据</span> &nbsp;<code>pali_texts</code> 的静态列按书缓存:<code>para → [level, class, lenght, chapter_len, chapter_strlen, toc]</code>。</p>
+<ul>
+<li>key:<code>/pali-meta/{book}/v{N}</code>,<b>30 天</b>;经文重新导入时把代码里的 <code>N</code> 加一(与 <code>TipitakaCatalogService::CACHE_KEY</code> 同一做法)。同一进程内再用数组记住。</li>
+<li>使用方:<code>readParagraph()</code> 未命中时取标题级别与 class;<code>page()</code> 的字节模式;阅读器的 <code>resolveDisplayRange()</code>(现在每次查本书全部章节行);导出的 <code>headingLevels()</code>。</li>
+</ul>
+</div>
+
+<div class="card">
+<p><span class="pill l1">L1 段落成品</span> &nbsp;<code>readParagraph()</code> 直接缓存<b>完整结果</b>(含外壳 <code>&lt;div id='para-N'&gt;</code> / <code>&lt;hN&gt;</code> 与段后脚注列表)。</p>
+<ul>
+<li>外壳只依赖 L0 的 level / class(经文静态数据),放进缓存不会过时,所以<b>不需要外层</b>:把那两次查询挪进缓存闭包、改查 L0,签名与返回形状不变。</li>
+<li>key:<code>/read-para/v4/{book}-{para}/{channel}/{format}</code>(换版本号,旧 key 自然过期)。没有译文的段也缓存(空 display)。</li>
+<li>失效:沿用 <code>forgetParagraph()</code>(句子、批注的模型事件已接好),改成删新 key。TTL 改用专门配置 <code>mint.cache.read_paragraph_ttl</code>(见「需要你定的」)。</li>
+</ul>
+</div>
+
+<div class="card">
+<p><span class="pill gen">版本号</span> &nbsp;每个 (channel, book) 一个递增计数 <code>/read-gen/{channel}/{book}</code>(<code>RedisCache::increment</code>,不过期)。</p>
+<ul>
+<li>句子、批注的模型事件里,在 <code>forgetParagraph()</code> 旁边加一次 <code>increment</code>:这本书的译文变了。</li>
+<li>L2、L3 的 key 都带上它。版本一变,旧 key 不再被读到、自然过期,<b>不用去找「哪些章包含这一段」再逐个删</b>(父章、子章、下钻后的区间互相重叠,精确删除很难)。</li>
+<li>代价:一次多读一个小 key;编辑某本书时只有这本书的索引和章节缓存失效,别的书不受影响。</li>
+</ul>
+</div>
+
+<div class="card">
+<p><span class="pill l2">L2 内容索引</span> &nbsp;「某 channel 哪些段有译文」,给 <code>page()</code> 用:</p>
+<ul>
+<li><code>/read-index/{channel}/books/g…</code>:有译文的书号;<code>/read-index/{channel}/{book}/g{gen}</code>:该书有译文的段号(升序)。书号列表用 channel 级版本号(同样在句子事件里加一)。</li>
+<li><code>page()</code> 的候选段、游标、<code>total</code> / <code>remaining</code> 全在 PHP 里对这个数组算,<b>命中时 0 查询</b>;游标格式 <code>{book}-{para}</code> 与响应不变。</li>
+<li>重建只需一条 <code>select distinct paragraph</code>;cs6 最大的一本书一万多段,几十 KB;TTL 7 天。</li>
+</ul>
+</div>
+
+<div class="card">
+<p><span class="pill l3">L3 章节成品</span> &nbsp;给阅读器:整章拼好的 HTML 一次存、一次取。</p>
+<ul>
+<li>key:<code>/read-chapter/{channel}/{book}-{start}-{end}/g{gen}</code>,值 <code>{display, title}</code>。<code>start</code> / <code>end</code> 由 <code>resolveDisplayRange()</code> 算(查 L0,不落库)。</li>
+<li>命中:读版本号 1 次 + 读章节 1 次,<b>正文部分 0 查询</b>。未命中才逐段 <code>readParagraph()</code>(各段多半已在 L1)拼好回写。</li>
+<li>只动 <code>BookController::fetchRangeContent()</code> 这一个方法:先查 L3,没有再走原来的拼接。</li>
+<li><code>?comm=</code> 注释注入(<code>injectNoteMarkers</code>)在取出后做,不进缓存,不影响命中。</li>
+</ul>
+</div>
+
+<div class="card">
+<p><span class="pill l4">L4 批量读</span> &nbsp;只给 <code>page()</code>:一块最多 200 段,逐段 GET 是 200 次往返。</p>
+<ul>
+<li><code>RedisCache</code> 加 <code>many()</code>(phpredis 的 <code>RedisCluster::mget</code>,按 slot 拆到各节点);<code>readParagraph</code> 加批量版 <code>readParagraphs()</code>:先 <code>many()</code> 拿命中的,没命中的逐段渲染回写。</li>
+<li>已在开发集群验证:200 个 key 落在 200 个 slot,<code>mget</code> 全部取对。本机往返近乎为零,看不出差别;收益与生产上 PHP 到 Redis 的往返延迟成正比(1 ms 往返时一块省约 200 ms)。</li>
+<li><b>阅读器不需要它</b>:整章已有 L3。可以放到最后做,或先测生产延迟再决定。</li>
+</ul>
+</div>
+
+<h2>数据流(冷启动 + 缓存)</h2>
+<div class="diagram">
+<svg viewBox="0 0 1060 600" role="img" aria-labelledby="t d">
+<title id="t">段落数据流</title>
+<desc id="d">mobile 与下载打包经 TipitakaReadingService 读内容索引 L2 与段落成品 L1;阅读器经 BookController 读章节成品 L3,未命中才落到 L2 与 L1;L1 未命中才渲染、查 L0 与数据库;写入事件删 L1 并给本书版本号加一,L2、L3 的 key 带版本号。</desc>
+<defs>
+<marker id="ah" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" fill="var(--muted)"/></marker>
+<marker id="ahg" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" fill="var(--ok)"/></marker>
+<marker id="ahr" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" fill="var(--danger)"/></marker>
+<marker id="ahw" viewBox="0 0 10 10" refX="9" refY="5" markerWidth="7" markerHeight="7" orient="auto-start-reverse"><path d="M0,0 L10,5 L0,10 z" fill="var(--warn)"/></marker>
+</defs>
+<style>
+.bx{fill:var(--surface);stroke:var(--border);stroke-width:1.5}
+.tx{fill:var(--text);font:600 14px -apple-system,"PingFang SC","Microsoft YaHei",sans-serif}
+.sm{fill:var(--muted);font:12px -apple-system,"PingFang SC","Microsoft YaHei",sans-serif}
+.mono{fill:var(--muted);font:11px ui-monospace,Menlo,monospace}
+.ln{stroke:var(--muted);stroke-width:1.6;fill:none}
+.hit{stroke:var(--ok);stroke-width:2.4;fill:none}
+.miss{stroke:var(--danger);stroke-width:1.8;fill:none;stroke-dasharray:6 4}
+.inv{stroke:var(--warn);stroke-width:1.6;fill:none;stroke-dasharray:3 4}
+</style>
+
+<text x="20" y="26" class="sm">调用方</text>
+<rect class="bx" x="20" y="40" width="200" height="54" rx="8"/><text class="tx" x="34" y="63">mobile / v6</text><text class="mono" x="34" y="82">GET /v3/tipitaka-reading</text>
+<rect class="bx" x="20" y="106" width="200" height="54" rx="8"/><text class="tx" x="34" y="129">下载打包 worker</text><text class="mono" x="34" y="148">TipitakaExportBuilder</text>
+<rect class="bx" x="20" y="200" width="200" height="54" rx="8"/><text class="tx" x="34" y="223">Laravel 阅读器</text><text class="mono" x="34" y="242">按章,整章一次</text>
+
+<!-- B 列 -->
+<rect class="bx" x="270" y="50" width="220" height="80" rx="8"/>
+<text class="tx" x="284" y="76">TipitakaReadingService</text><text class="mono" x="284" y="96">::page() 按块</text><text class="sm" x="284" y="116">候选 / 游标 / 进度 → L2</text>
+<line class="ln" x1="220" y1="67" x2="268" y2="80" marker-end="url(#ah)"/>
+<line class="ln" x1="220" y1="133" x2="268" y2="108" marker-end="url(#ah)"/>
+
+<rect class="bx" x="270" y="190" width="220" height="74" rx="8"/>
+<text class="tx" x="284" y="216">BookController</text><text class="mono" x="284" y="236">fetchRangeContent()</text><text class="sm" x="284" y="254">区间由 L0 算</text>
+<line class="ln" x1="220" y1="227" x2="268" y2="227" marker-end="url(#ah)"/>
+
+<rect x="270" y="300" width="220" height="86" rx="8" fill="var(--ok-lt)" stroke="var(--ok)" stroke-width="1.5"/>
+<text class="tx" x="284" y="324">L3 章节成品</text><text class="mono" x="284" y="344">/read-chapter/{ch}/</text><text class="mono" x="284" y="360">{book}-{start}-{end}/g{gen}</text><text class="sm" x="284" y="378">命中:整章 1 次 GET</text>
+<line class="hit" x1="380" y1="264" x2="380" y2="298" marker-end="url(#ahg)"/>
+
+<rect x="270" y="450" width="220" height="80" rx="8" fill="var(--warn-lt)" stroke="var(--warn)" stroke-width="1.5"/>
+<text class="tx" x="284" y="474">本书版本号</text><text class="mono" x="284" y="494">/read-gen/{ch}/{book}</text><text class="sm" x="284" y="514">INCR,不过期</text>
+
+<!-- C 列 -->
+<rect x="540" y="40" width="220" height="78" rx="8" fill="var(--primary-lt)" stroke="var(--primary)" stroke-width="1.5"/>
+<text class="tx" x="554" y="64">L2 内容索引</text><text class="mono" x="554" y="84">/read-index/{ch}/books</text><text class="mono" x="554" y="102">/read-index/{ch}/{book}/g{gen}</text>
+<line class="hit" x1="490" y1="80" x2="538" y2="78" marker-end="url(#ahg)"/>
+
+<rect x="540" y="170" width="220" height="96" rx="8" fill="var(--ok-lt)" stroke="var(--ok)" stroke-width="1.5"/>
+<text class="tx" x="554" y="194">L1 段落成品</text><text class="mono" x="554" y="214">/read-para/v4/{b}-{p}/</text><text class="mono" x="554" y="230">{ch}/{fmt}</text><text class="sm" x="554" y="252">含外壳与脚注,空段也存</text>
+<path class="hit" d="M490,112 C516,112 516,200 538,204" marker-end="url(#ahg)"/>
+<path class="miss" d="M490,340 C516,340 516,250 538,248" marker-end="url(#ahr)"/>
+<text class="sm" x="284" y="406" style="fill:var(--danger)">L3 未命中 → 逐段取 L1,拼好回写</text>
+
+<rect class="bx" x="540" y="320" width="220" height="86" rx="8"/>
+<text class="tx" x="554" y="344">A1 批量渲染</text><text class="sm" x="554" y="364">未命中的段一起:句子 1 次、</text><text class="sm" x="554" y="382">批注 1 次、renderMany 1 次</text><text class="sm" x="554" y="400">回写 L1</text>
+<line class="miss" x1="650" y1="266" x2="650" y2="318" marker-end="url(#ahr)"/>
+<text class="sm" x="658" y="312" style="fill:var(--danger)">L1 未命中</text>
+
+<!-- D 列 -->
+<rect x="820" y="170" width="220" height="96" rx="8" fill="var(--violet-lt)" stroke="var(--violet)" stroke-width="1.5"/>
+<text class="tx" x="834" y="194">L4 批量读(仅 page)</text><text class="mono" x="834" y="214">RedisCache::many()</text><text class="sm" x="834" y="234">一块 200 段 = 1 次 MGET</text><text class="sm" x="834" y="252">(按节点拆)</text>
+<line class="hit" x1="760" y1="218" x2="818" y2="218" marker-end="url(#ahg)"/>
+
+<rect x="820" y="320" width="220" height="86" rx="8" fill="var(--violet-lt)" stroke="var(--violet)" stroke-width="1.5"/>
+<text class="tx" x="834" y="344">L0 书目元数据</text><text class="mono" x="834" y="364">/pali-meta/{book}/v{N}</text><text class="sm" x="834" y="384">level · class · chapter_len…</text>
+<line class="miss" x1="760" y1="363" x2="818" y2="363" marker-end="url(#ahr)"/>
+<path class="ln" d="M490,240 H504 V292 H880 V318" marker-end="url(#ah)" style="stroke-dasharray:2 3"/>
+<text class="sm" x="780" y="286">章节区间</text>
+
+<rect x="540" y="470" width="500" height="66" rx="8" fill="var(--danger-lt)" stroke="var(--danger)" stroke-width="1.5"/>
+<text class="tx" x="554" y="495">PostgreSQL</text><text class="mono" x="554" y="516">sentences · discussions · channels · terms · pali_texts</text>
+<line class="miss" x1="650" y1="406" x2="650" y2="468" marker-end="url(#ahr)"/>
+<line class="miss" x1="930" y1="406" x2="930" y2="468" marker-end="url(#ahr)"/>
+<path class="miss" d="M760,58 H1048 V503 H1044" marker-end="url(#ahr)"/>
+<text class="sm" x="800" y="52" style="fill:var(--danger)">L2 未命中:select distinct</text>
+
+<!-- 写入 -->
+<rect class="bx" x="20" y="450" width="200" height="80" rx="8"/>
+<text class="tx" x="34" y="474">写入事件</text><text class="mono" x="34" y="494">Sentence saved/deleted…</text><text class="mono" x="34" y="512">Discussion saved/deleted</text>
+<line class="inv" x1="220" y1="480" x2="268" y2="480" marker-end="url(#ahw)"/>
+<text class="sm" x="226" y="470" style="fill:var(--warn)">+1</text>
+<line class="inv" x1="380" y1="450" x2="380" y2="388" marker-end="url(#ahw)"/>
+<path class="inv" d="M490,470 H516 V100 H538" marker-end="url(#ahw)"/>
+<path class="inv" d="M220,520 H528 V260 H538" marker-end="url(#ahw)"/>
+<text class="sm" x="226" y="548" style="fill:var(--warn)">删 L1(forgetParagraph);版本号 +1 → L2、L3 换 key</text>
+</svg>
+</div>
+<div class="legend">
+<span><i style="border-color:var(--ok)"></i>命中路径(0 次查询)</span>
+<span><i style="border-color:var(--danger);border-top-style:dashed"></i>未命中才走</span>
+<span><i style="border-color:var(--warn);border-top-style:dotted"></i>失效</span>
+<span><i style="border-color:var(--muted)"></i>调用</span>
+</div>
+
+<h2>改完后的效果</h2>
+<div class="tbl"><table>
+<tr><th></th><th>现在</th><th>改后</th></tr>
+<tr><td><code>page()</code> 一块 200 段:<b>冷启动</b>数据库</td><td class="num bad">≈2000 次(CBETA 库 617 ms)</td><td class="num good">≈4 次 + 每类模板数据 1 次</td></tr>
+<tr><td>阅读器打开一章(27 段):<b>冷启动</b>正文</td><td class="num bad">约 330 次</td><td class="num good">≈3 次</td></tr>
+<tr><td><code>page()</code> 一块 200 段:<b>命中</b>数据库</td><td class="num bad">403 次</td><td class="num good">0</td></tr>
+<tr><td><code>page()</code> 一块 200 段:Redis</td><td class="num">200 次 GET</td><td class="num">版本号 + 索引 2~3 次,段落 1 次 MGET(做了 L4)或 200 次 GET(没做)</td></tr>
+<tr><td>阅读器打开一章(213-34,27 段):正文部分</td><td class="num bad">51 次查询 + 27 次 GET</td><td class="num good">0 查询 + 2 次 GET</td></tr>
+<tr><td>阅读器打开一章:整页</td><td class="num">83 次查询(实测)</td><td class="num">约 32 次:目录、翻页、版本列表、标题等外围,不在本方案内</td></tr>
+</table></div>
+
+<h2>改动清单</h2>
+<div class="tbl"><table>
+<tr><th>文件</th><th>改什么</th><th>规模</th></tr>
+<tr><td><code>Services/PaliContentService.php</code>(冷启动)</td><td><span class="pill cold">A1</span> 新 <code>readParagraphs()</code>:channel / 句子 / 批注各查一次,整块一次 <code>renderManyAs()</code>;<code>injectAnnotationNotes()</code> 接收预取的批注;批注正文合并渲染;<code>readParagraph()</code> 改为调它</td><td>中~大</td></tr>
+<tr><td>新 <code>Services/PaliTextMetaService.php</code>(根命名空间,纯能力)</td><td><span class="pill l0">L0</span> 按书取静态列,进程内记住</td><td>小</td></tr>
+<tr><td><code>Services/PaliContentService.php</code></td><td><span class="pill l1">L1</span> <code>readParagraph()</code> 缓存完整结果、level / class 改查 L0、key 换 v4、TTL 用新配置;<code>forgetParagraph()</code> 删新 key;<code>paragraphLevel()</code> 改查 L0</td><td>中</td></tr>
+<tr><td><code>Models/Sentence.php</code>、<code>Models/Discussion.php</code></td><td><span class="pill gen">版本号</span> 事件里在 <code>forgetParagraph()</code> 旁边加 <code>increment</code>(句子改 book 时新旧两本都加)</td><td>小</td></tr>
+<tr><td>新 <code>Services/ParagraphIndexService.php</code>(根命名空间,纯能力)</td><td><span class="pill l2">L2</span> 书号列表、段号列表(带版本号)、按游标切片、total / remaining</td><td>中</td></tr>
+<tr><td><code>Services/V3/TipitakaReadingService.php</code></td><td><code>page()</code> 的 candidates / applyCursor / progressMeta / paragraphLengths 改用 L2 + L0;对外响应不变</td><td>中</td></tr>
+<tr><td><code>Http/Controllers/Library/BookController.php</code></td><td><span class="pill l3">L3</span> <code>fetchRangeContent()</code> 先查章节缓存;<code>resolveDisplayRange()</code> 改查 L0(只动这两个方法)</td><td>小</td></tr>
+<tr><td><code>Services/RedisCache.php</code> + Fake + 门面</td><td><span class="pill l4">L4</span> <code>many()</code>;<code>PaliContentService::readParagraphs()</code> 批量版</td><td>小</td></tr>
+<tr><td><code>Services/V3/TipitakaExportBuilder.php</code></td><td><code>headingLevels()</code> / <code>headings()</code> 改查 L0;取段经 <code>page()</code> 自动受益</td><td>小</td></tr>
+<tr><td><code>Console/Commands/InitCommentary.php</code></td><td>批量 <code>delete()</code> 绕过模型事件,删完后给涉及的 (channel, book) 版本号加一</td><td>小</td></tr>
+<tr><td><code>config/mint.php</code></td><td><code>cache.read_paragraph_ttl</code>、<code>cache.read_index_ttl</code>、<code>cache.read_chapter_ttl</code></td><td>小</td></tr>
+<tr><td>测试</td><td>命中时 0 查询(<code>DB::enableQueryLog</code> 断言);句子 / 批注增删改后 L1 删除、版本号加一、L2 / L3 读到新内容;游标、total / remaining 与改前一致;阅读器同一章第二次打开正文 0 查询</td><td>中</td></tr>
+</table></div>
+<p>不改的:v2 的 <code>chapter-content</code> / <code>paragraph-content</code>(走 <code>makeContentObj()</code>,v4 下线前不动);<code>tipitaka-reading</code> 的响应形状与游标格式;阅读器页面外围的查询。</p>
+
+<h2>风险与需要你定的</h2>
+<div class="decide">
+<p><b>待定 1:L1、L3 的 TTL。</b>段落与章节成品除了句子与批注(有精确失效),还依赖<b>没有失效信号的数据</b>:术语释义(<code>{{term}}</code>)、引用的其他句子(<code>{{sent}}</code>、义注对应)、channel 名称等。它们改了,缓存会旧到过期为止。</p>
+<ul>
+<li>A(推荐):<b>24 小时</b>。现在默认是 10 小时,旧内容最多多留半天;命中率大幅提高。</li>
+<li>B:7 天,另加一个全局「渲染代号」,术语保存时加一,所有段落与章节按需重渲。术语编辑很频繁时会反复整库失效。</li>
+<li>C:维持现状(跟 <code>mint.cache.expire</code>)。</li>
+</ul>
+</div>
+<div class="decide">
+<p><b>待定 2:L4 做不做。</b>阅读器不需要;只对 <code>page()</code> 有用,收益取决于生产上 PHP 到 Redis 的往返延迟。可以先上 L0–L3,量一下生产延迟再定。</p>
+</div>
+<div class="note">
+<ul>
+<li><b>绕过模型事件的写入</b>:全仓库只找到 <code>InitCommentary</code> 一处对 sentences 批量 <code>delete()</code>;以后新增批量写入要手动加版本号,在 <code>ParagraphIndexService</code> 类注释里写明。</li>
+<li><b>Redis 占用</b>:L1 key 数与现在相同,只是活得更久;L3 每个被打开过的 (channel, 章) 一个 key,正文几十 KB;版本号每个 (channel, book) 一个小 key、不过期;L0 共 217 个。</li>
+<li><b>v4</b>:v2 不读这些缓存,不受影响。</li>
+</ul>
+</div>
+
+<h2>分步实施</h2>
+<ol>
+<li><span class="pill l0">L0</span> 书目元数据(A、B 都要用)。</li>
+<li><span class="pill cold">A1</span> 批量渲染 <code>readParagraphs()</code>:冷启动从约 2000 次降到约 4 次;同时它就是 B 的批量入口。</li>
+<li><span class="pill l1">L1</span> 段落成品(含外壳):命中时 <code>page()</code> 403 → 3,阅读器正文 51 → 0。</li>
+<li><span class="pill gen">版本号</span> + <span class="pill l3">L3</span> 章节成品:阅读器整章一次 GET。</li>
+<li><span class="pill l2">L2</span> 内容索引:<code>page()</code> 命中 3 → 0。</li>
+<li>(视生产延迟)<span class="pill l4">L4</span> 批量读。</li>
+</ol>
+<p>每步单独可测、可回退。</p>
+
+</div>
+</body>
+</html>

+ 246 - 0
api-v13/tests/Feature/ReadingCacheTest.php

@@ -0,0 +1,246 @@
+<?php
+
+use App\Facades\RedisCache;
+use App\Models\Discussion;
+use App\Models\PaliText;
+use App\Services\PaliContentService;
+use App\Services\ReadingIndexService;
+use App\Services\V3\PaliTextService;
+use Illuminate\Foundation\Testing\RefreshDatabase;
+use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Str;
+
+uses(RefreshDatabase::class);
+
+/**
+ * 阅读缓存(api-v13/documents/reading-cache-plan.html):
+ * L0 pali_texts 按书缓存、A1 整块批量渲染、L1 段落成品、L2 段号 / 书号索引。
+ */
+function makePaliRow(int $book, int $para, int $level, int $chapterLen = 0, string $class = 'bodytext', string $toc = ''): void
+{
+    (new PaliText)->forceFill([
+        'book' => $book,
+        'paragraph' => $para,
+        'level' => $level,
+        'class' => $class,
+        'toc' => $toc,
+        'text' => '',
+        'html' => '',
+        'lenght' => 10 * $para,
+        'chapter_len' => $chapterLen,
+        'chapter_strlen' => 100,
+        'parent' => 0,
+        'pcd_book_id' => 0,
+        'uid' => (string) Str::uuid(),
+    ])->save();
+}
+
+function makeReadingNote(string $sentenceUid, string $type, string $content, ?int $score = null): Discussion
+{
+    $discussion = new Discussion;
+    $discussion->forceFill([
+        'res_id' => $sentenceUid,
+        'res_type' => 'sentence',
+        'type' => $type,
+        'title' => $content,
+        'content' => $content,
+        'content_type' => 'markdown',
+        'editor_uid' => makeStudio('note-'.Str::random(6)),
+        'score' => $score,
+        'pos_start' => 0,
+        'pos_end' => 1,
+    ])->save();
+
+    return $discussion;
+}
+
+/**
+ * 计数这段代码查了几次库。
+ */
+function countQueries(Closure $callback): int
+{
+    DB::flushQueryLog();
+    DB::enableQueryLog();
+    $callback();
+    $count = count(DB::getQueryLog());
+    DB::disableQueryLog();
+
+    return $count;
+}
+
+it('caches pali_texts per book and serves headings, levels and classes without queries', function () {
+    makePaliRow(9301, 1, 1, 5, 'book', 'Book');
+    makePaliRow(9301, 2, 2, 4, 'chapter', 'Chapter');
+    makePaliRow(9301, 3, 100, 0, 'gatha1');
+
+    app(PaliTextService::class)->headings(9301);
+    app(PaliTextService::class)->paragraphs(9301, 1, 3);
+
+    // 新实例(没有进程内记忆)也只读缓存
+    $service = new PaliTextService;
+    expect(countQueries(function () use ($service) {
+        expect($service->headingLevel(9301, 2))->toBe(2)
+            ->and($service->headingLevel(9301, 3))->toBe(0)
+            ->and($service->paragraph(9301, 3))->toBe(['level' => 100, 'class' => 'gatha1', 'length' => 30])
+            ->and($service->chapterRange(9301, 2))->toBe([2, 5])
+            ->and($service->chapterRange(9301, 3))->toBe([3, 3])
+            ->and($service->bookStart(9301, 3))->toMatchArray(['para' => 1, 'toc' => 'Book']);
+    }))->toBe(0);
+
+    expect($service->chapterRange(9301, 99))->toBeNull();
+});
+
+it('renders a block exactly like rendering each paragraph alone', function () {
+    $channel = makeChannel(makeStudio('cache-owner'), 'cache channel');
+    makePaliRow(9302, 1, 2, 3, 'chapter');
+    foreach ([1, 2, 3] as $para) {
+        $sentence = makeSentence($channel, 9302, $para, 1, "first of {$para}");
+        makeSentence($channel, 9302, $para, 2, "second of {$para}");
+        makeReadingNote($sentence->uid, 'note', "note of {$para}");
+    }
+    // 只有第 2 段有评估:第 2 段的另一句补灰色对勾,别的段不补(按段算,不是按整块)
+    $assessed = makeSentence($channel, 9302, 2, 3, 'assessed');
+    makeReadingNote($assessed->uid, 'assessment', 'ok', 90);
+
+    $service = app(PaliContentService::class);
+    $block = $service->readParagraphs(9302, [1, 2, 3], $channel);
+
+    foreach ([1, 2, 3] as $para) {
+        PaliContentService::forgetParagraph(9302, $para, $channel);
+    }
+    foreach ([1, 2, 3] as $para) {
+        expect($service->readParagraph(9302, $para, $channel))->toBe($block[$para]);
+    }
+    expect($block[1]['display'])->toContain('<h2>')->toContain('note of 1')->toContain('anno-footnotes')
+        ->and($block[2]['display'])->toContain('anno-assessment')
+        ->and($block[1]['display'])->not->toContain('anno-assessment')
+        ->and($block[3]['display'])->not->toContain('anno-assessment');
+});
+
+it('renders a block with a fixed number of queries however many paragraphs it has', function () {
+    $channel = makeChannel(makeStudio('cache-owner'), 'cache channel');
+    $render = function (int $book, int $count) use ($channel) {
+        foreach (range(1, $count) as $para) {
+            $sentence = makeSentence($channel, $book, $para, 1, "text {$para}");
+            makeReadingNote($sentence->uid, 'note', "note {$para}");
+        }
+        app(PaliTextService::class)->headings($book);
+        app(PaliTextService::class)->paragraphs($book, 1, $count);
+
+        return countQueries(fn () => app(PaliContentService::class)->readParagraphs($book, range(1, $count), $channel));
+    };
+
+    expect($render(9303, 20))->toBe($render(9304, 2));
+});
+
+it('serves cached paragraphs without touching the database', function () {
+    $channel = makeChannel(makeStudio('cache-owner'), 'cache channel');
+    makeSentence($channel, 9305, 1, 1, 'cached');
+    $url = "/api/v3/tipitaka-reading/{$channel}?book=9305";
+    $first = $this->getJson($url)->assertOk()->json();
+
+    // 鉴权中间件等外围查询之外,正文、候选、进度都不查库
+    $queries = countQueries(fn () => expect($this->getJson($url)->assertOk()->json())->toBe($first));
+    $baseline = countQueries(fn () => $this->getJson("/api/v3/tipitaka-reading/{$channel}?book=9305&para=999")->assertOk());
+    expect($queries)->toBe($baseline);
+});
+
+it('refreshes the paragraph index only when the set of translated paragraphs changes', function () {
+    $channel = makeChannel(makeStudio('cache-owner'), 'cache channel');
+    $first = makeSentence($channel, 9306, 1, 1, 'one');
+    $index = fn () => new ReadingIndexService;
+    expect($index()->paragraphs($channel, 9306))->toBe([1]);
+
+    $sentence = makeSentence($channel, 9306, 3, 1, 'three');
+    expect($index()->paragraphs($channel, 9306))->toBe([1, 3]);
+
+    // 只改内容:段落成品删掉,索引不动(不重建)
+    app(PaliContentService::class)->readParagraph(9306, 1, $channel);
+    $first->forceFill(['content' => 'one again', 'strlen' => 9])->save();
+    expect(RedisCache::has(PaliContentService::paragraphCacheKey(9306, 1, $channel, 'html')))->toBeFalse()
+        ->and(countQueries(fn () => expect($index()->paragraphs($channel, 9306))->toBe([1, 3])))->toBe(0);
+
+    // strlen 变成 0 就不算有译文
+    $sentence->forceFill(['content' => '', 'strlen' => 0])->save();
+    expect($index()->paragraphs($channel, 9306))->toBe([1]);
+
+    // 批注不碰索引
+    makeReadingNote($first->uid, 'note', 'n');
+    expect(countQueries(fn () => $index()->paragraphs($channel, 9306)))->toBe(0);
+});
+
+it('keeps the book index in step with books gaining or losing translations', function () {
+    $channel = makeChannel(makeStudio('cache-owner'), 'cache channel');
+    makeSentence($channel, 9307, 1, 1, 'a');
+    expect((new ReadingIndexService)->books($channel))->toBe([9307]);
+
+    $other = makeSentence($channel, 9308, 1, 1, 'b');
+    expect((new ReadingIndexService)->books($channel))->toBe([9307, 9308]);
+
+    // 搬去别的书:旧书少了、新书多了
+    $other->forceFill(['book_id' => 9309])->save();
+    expect((new ReadingIndexService)->books($channel))->toBe([9307, 9309]);
+
+    $other->delete();
+    expect((new ReadingIndexService)->books($channel))->toBe([9307]);
+});
+
+it('walks a whole channel across books with the cursor', function () {
+    $channel = makeChannel(makeStudio('cache-owner'), 'cache channel');
+    makeSentence($channel, 9310, 1, 1, 'a');
+    makeSentence($channel, 9310, 2, 1, 'b');
+    makeSentence($channel, 9311, 5, 1, 'c');
+
+    $page = $this->getJson("/api/v3/tipitaka-reading/{$channel}?page_size=2")->assertOk();
+    expect(array_column($page->json('data'), 'para'))->toBe([1, 2])
+        ->and($page->json('meta.next_cursor'))->toBe('9310-2');
+
+    $page = $this->getJson("/api/v3/tipitaka-reading/{$channel}?page_size=2&after=9310-2")->assertOk();
+    expect($page->json('data.0'))->toMatchArray(['book' => 9311, 'para' => 5])
+        ->and($page->json('meta.next_cursor'))->toBeNull();
+});
+
+it('clears the paragraph cache only after the transaction commits', function () {
+    $channel = makeChannel(makeStudio('cache-owner'), 'cache channel');
+    $sentence = makeSentence($channel, 9313, 1, 1, 'before');
+    app(PaliContentService::class)->readParagraph(9313, 1, $channel);
+    $key = PaliContentService::paragraphCacheKey(9313, 1, $channel, 'html');
+
+    DB::transaction(function () use ($sentence, $key) {
+        $sentence->forceFill(['content' => 'after'])->save();
+        expect(RedisCache::has($key))->toBeTrue();
+    });
+    expect(RedisCache::has($key))->toBeFalse();
+});
+
+it('splits a book into flat chapters, each running up to the next heading', function () {
+    makePaliRow(9320, 1, 1, 10);
+    makePaliRow(9320, 2, 2, 5);
+    makePaliRow(9320, 4, 3, 3);
+    makePaliRow(9320, 7, 2, 4);
+
+    $service = app(PaliTextService::class);
+    expect($service->flatChapters(9320))->toBe([1 => 1, 2 => 3, 4 => 6, 7 => 10])
+        ->and($service->flatChapterOf(9320, 5))->toBe(4)
+        ->and($service->flatChapterOf(9320, 10))->toBe(7)
+        ->and($service->flatChapterOf(9320, 11))->toBeNull();
+});
+
+it('caches the reader chapters and drops only the chapter whose sentence changed', function () {
+    $channel = makeChannel(makeStudio('cache-owner'), 'cache channel');
+    makePaliRow(9321, 1, 2, 2);
+    makePaliRow(9321, 3, 2, 2);
+    makeSentence($channel, 9321, 1, 1, 'chapter one');
+    $changed = makeSentence($channel, 9321, 4, 1, 'chapter two');
+
+    $service = app(PaliContentService::class);
+    $display = $service->readChapters(9321, 1, 4, $channel);
+    expect($display)->toContain('chapter one')->toContain('chapter two')
+        ->and($display)->toBe(implode('', array_column($service->readParagraphs(9321, [1, 2, 3, 4], $channel), 'display')))
+        ->and(countQueries(fn () => $service->readChapters(9321, 1, 4, $channel)))->toBe(0);
+
+    $changed->forceFill(['content' => 'chapter two edited'])->save();
+    expect(RedisCache::has(PaliContentService::chapterCacheKey(9321, 1, $channel, 'html')))->toBeTrue()
+        ->and(RedisCache::has(PaliContentService::chapterCacheKey(9321, 3, $channel, 'html')))->toBeFalse()
+        ->and($service->readChapters(9321, 1, 4, $channel))->toContain('chapter two edited');
+});

+ 3 - 0
api-v13/tests/Feature/TipitakaReadingRenderTest.php

@@ -4,6 +4,7 @@ use App\Facades\RedisCache;
 use App\Models\PaliText;
 use App\Models\PaliText;
 use App\Models\Sentence;
 use App\Models\Sentence;
 use App\Services\PaliContentService;
 use App\Services\PaliContentService;
+use App\Services\V3\PaliTextService;
 use Illuminate\Foundation\Testing\RefreshDatabase;
 use Illuminate\Foundation\Testing\RefreshDatabase;
 use Illuminate\Support\Str;
 use Illuminate\Support\Str;
 
 
@@ -52,6 +53,8 @@ it('wraps a chapter title paragraph in a heading', function () {
         'pcd_book_id' => 0,
         'pcd_book_id' => 0,
         'uid' => (string) Str::uuid(),
         'uid' => (string) Str::uuid(),
     ])->save();
     ])->save();
+    // pali_texts 按书缓存;生产上只有导入命令改它,导入后同样要 forgetBook()
+    app(PaliTextService::class)->forgetBook(9001);
 
 
     $display = $this->getJson("/api/v3/tipitaka-reading/{$channel}?book=9001&para=1")
     $display = $this->getJson("/api/v3/tipitaka-reading/{$channel}?book=9001&para=1")
         ->assertOk()
         ->assertOk()