Skip to content

fix(engine): prompt plaza edits not taking effect in generation (#146)#170

Open
liaoyl830 wants to merge 1 commit into
shenminglinyi:masterfrom
liaoyl830:fix/prompt-plaza-not-effective-in-generation
Open

fix(engine): prompt plaza edits not taking effect in generation (#146)#170
liaoyl830 wants to merge 1 commit into
shenminglinyi:masterfrom
liaoyl830:fix/prompt-plaza-not-effective-in-generation

Conversation

@liaoyl830
Copy link
Copy Markdown

@liaoyl830 liaoyl830 commented May 22, 2026

变更类型

  • fix Bug 修复

变更说明

修复提示词广场编辑后不生效的问题。用户在提示词广场修改提示词并保存后,章节生成仍使用旧版本提示词。

根因分析

PromptRegistry 对提示词节点有 300 秒(5 分钟)的内存缓存。用户编辑提示词后,API 层的 _plaza_cache 会被清除,但 PromptRegistry 的缓存未同步失效,导致生成管线在 5 分钟内仍读取旧版 DB 快照。

修复内容

  1. _invalidate_plaza_cache() 扩展 — 所有提示词写操作(编辑、回滚、新建、删除、导入)现在同时清除 PromptRegistry 缓存,确保生成管线立即读取到最新版本。

  2. PromptManager.update_node() 补充失效 — 数据库层更新节点后主动调用 _invalidate_registry_cache(),作为 API 层失效的兜底。

  3. 降级日志级别提升_get_workflow_system_template()_get_workflow_user_template() 的硬编码回退日志从 DEBUG 提升至 WARNING,便于排查管道是否意外降级到硬编码模板。


架构影响

  • 涉及层级:interfaces / infrastructure / application
  • 是否修改现有 API 契约:否
  • 是否新增数据库表/字段:否

测试

  • 修改不涉及数据库 schema 变更
  • 所有改动为缓存失效逻辑,不影响正常读取路径
  • _invalidate_registry_cache() 包含异常捕获,PromptRegistry 不可用时静默跳过

Summary by CodeRabbit

  • Bug Fixes

    • Strengthened cache invalidation to ensure prompt updates and edits are immediately visible throughout the system.
    • Enhanced logging visibility for fallback template scenarios by elevating alerts to warning level.
  • Chores

    • Refined internal cache management to improve system consistency and data freshness.

Review Change Stack

…minglinyi#146)

Root cause: PromptRegistry caches prompt templates with a 300s TTL.
After a user edits a prompt in the plaza, the API layer cache is cleared
but the PromptRegistry cache is not invalidated, so the generation
pipeline still serves stale templates for up to 5 minutes.

Changes:
1. interfaces/api/v1/workbench/llm_control.py
   - _invalidate_plaza_cache() now also calls PromptRegistry.invalidate_cache()
     so all editing endpoints (update_node, rollback_node, create_node,
     delete_node, import_prompts, create_template) trigger full cache
     invalidation

2. infrastructure/ai/prompt_manager.py
   - update_node() now calls _invalidate_registry_cache() after commit
   - New _invalidate_registry_cache() static helper method

3. application/workflows/auto_novel_generation_workflow.py
   - Upgrade fallback logging from DEBUG to WARNING for both
     _get_workflow_system_template and _get_workflow_user_template
   - Makes it easier to diagnose when the pipeline is falling back to
     hardcoded templates instead of reading from the DB
@liaoyl830 liaoyl830 requested a review from shenminglinyi as a code owner May 22, 2026 14:31
@coderabbitai
Copy link
Copy Markdown
Contributor

coderabbitai Bot commented May 22, 2026

📝 Walkthrough

Walkthrough

This PR adds PromptRegistry cache invalidation to keep node updates immediately visible across infrastructure and API layers. Logging for template fallbacks escalates to WARNING level with explicit fallback messages. A cache invalidation helper is introduced and integrated into node update and API cache operations.

Changes

Cache invalidation and logging improvements

Layer / File(s) Summary
Fallback logging improvements
application/workflows/auto_novel_generation_workflow.py
Fallback template warning visibility escalates from DEBUG to WARNING in both _get_workflow_system_template() and _get_workflow_user_template(), with explicit messages stating hardcoded fallback templates are in use and registry may be unavailable or improperly seeded.
Cache invalidation helper
infrastructure/ai/prompt_manager.py
New PromptManager._invalidate_registry_cache(node_key_or_id) static method fetches PromptRegistry, performs targeted cache invalidation when input appears to be a node key, otherwise clears entire cache, and silently ignores exceptions.
Integration into node updates and API
infrastructure/ai/prompt_manager.py, interfaces/api/v1/workbench/llm_control.py
PromptManager.update_node() calls the invalidation helper after node activation; API endpoint _invalidate_plaza_cache() additionally invalidates PromptRegistry cache to ensure prompt plaza edits don't persist across separate TTL windows.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~12 minutes

Poem

A cache, once stale, now springs anew,
The registry sings with templates true—
When nodes awake and plazas change,
Invalidation clears the strange. 🐰✨

🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically describes the main fix: prompt plaza edits not taking effect in generation, directly matching the core issue resolved in this changeset.
Description check ✅ Passed The description covers the required template sections: change type (fix), detailed explanation of the problem and root cause, architecture impact (layers and API/DB changes), and testing approach. All critical sections are complete.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

Copy link
Copy Markdown
Contributor

@coderabbitai coderabbitai Bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🧹 Nitpick comments (2)
infrastructure/ai/prompt_manager.py (1)

1091-1100: ⚡ Quick win

Make registry invalidation explicit instead of heuristic key-shape detection.

Line 1097 relies on string shape to infer key type. UUID-style IDs with hyphens can be treated as node keys, which risks missing the real cache entry. Prefer explicit invalidation by resolved node_key (or an explicit by_key flag) to avoid stale cache edge cases.

Suggested change
-    def _invalidate_registry_cache(node_key_or_id: str) -> None:
-        """使 PromptRegistry 缓存失效(node_key 或 node_id 均可)。"""
+    def _invalidate_registry_cache(node_key: Optional[str] = None) -> None:
+        """使 PromptRegistry 缓存失效。传 node_key 时做定向失效,否则全量失效。"""
         try:
             from infrastructure.ai.prompt_registry import get_prompt_registry
             registry = get_prompt_registry()
-            # 尝试按 node_key 失效;如果是 node_id 则清除全部缓存(更安全)
-            if '-' in node_key_or_id and len(node_key_or_id) < 50:
-                registry.invalidate_cache(node_key_or_id)
+            if node_key:
+                registry.invalidate_cache(node_key)
             else:
                 registry.invalidate_cache()
         except Exception:
             pass  # Registry 不可用时静默跳过
-        self._invalidate_registry_cache(node_id)
+        updated_node = self.get_node(node_id, by_key=False)
+        self._invalidate_registry_cache(updated_node.node_key if updated_node else None)
 
-        return self.get_node(node_id, by_key=False)
+        return updated_node
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@infrastructure/ai/prompt_manager.py` around lines 1091 - 1100, The
_invalidate_registry_cache function currently heuristically treats
node_key_or_id as a key when it contains a '-' and is short, which can
misclassify UUID-style IDs; change it to resolve the canonical node_key (or
accept an explicit by_key boolean) and call get_prompt_registry() and
registry.invalidate_cache with the resolved node_key only when you truly have a
key, otherwise call registry.invalidate_cache() to clear all; update the
function signature (e.g., _invalidate_registry_cache(node_key_or_id: str,
by_key: Optional[bool]=None)) or perform a lookup to convert a node_id to
node_key before calling registry.invalidate_cache to ensure deterministic
invalidation.
interfaces/api/v1/workbench/llm_control.py (1)

275-276: ⚡ Quick win

Keep non-blocking behavior, but emit a debug log on invalidation failure.

Line 275-276 fully suppresses failures, which makes stale-cache incidents harder to diagnose in production.

Suggested change
-    except Exception:
-        pass  # Registry 不可用时静默跳过,不影响 API 层功能
+    except Exception as exc:
+        logger.debug("PromptRegistry cache invalidation skipped: %s", exc, exc_info=True)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@interfaces/api/v1/workbench/llm_control.py` around lines 275 - 276, The
except Exception: pass in interfaces/api/v1/workbench/llm_control.py should
remain non-blocking but emit a debug-level log when registry invalidation fails;
replace the pass with a debug log call (e.g., logger.debug("Registry
invalidation failed, continuing without aborting", exc_info=True)) using the
existing logger variable (or process_logger) so the exception and stack trace
are recorded for diagnosis while keeping the API behavior unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@infrastructure/ai/prompt_manager.py`:
- Around line 1091-1100: The _invalidate_registry_cache function currently
heuristically treats node_key_or_id as a key when it contains a '-' and is
short, which can misclassify UUID-style IDs; change it to resolve the canonical
node_key (or accept an explicit by_key boolean) and call get_prompt_registry()
and registry.invalidate_cache with the resolved node_key only when you truly
have a key, otherwise call registry.invalidate_cache() to clear all; update the
function signature (e.g., _invalidate_registry_cache(node_key_or_id: str,
by_key: Optional[bool]=None)) or perform a lookup to convert a node_id to
node_key before calling registry.invalidate_cache to ensure deterministic
invalidation.

In `@interfaces/api/v1/workbench/llm_control.py`:
- Around line 275-276: The except Exception: pass in
interfaces/api/v1/workbench/llm_control.py should remain non-blocking but emit a
debug-level log when registry invalidation fails; replace the pass with a debug
log call (e.g., logger.debug("Registry invalidation failed, continuing without
aborting", exc_info=True)) using the existing logger variable (or
process_logger) so the exception and stack trace are recorded for diagnosis
while keeping the API behavior unchanged.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 098e8fd3-c16d-484b-8cf8-f091b94c2f15

📥 Commits

Reviewing files that changed from the base of the PR and between 1008f81 and 2accec2.

📒 Files selected for processing (3)
  • application/workflows/auto_novel_generation_workflow.py
  • infrastructure/ai/prompt_manager.py
  • interfaces/api/v1/workbench/llm_control.py

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant