This commit is contained in:
gr
2026-11-16 09:28:25 +08:00
parent 6a2b387edc
commit 44f26dc038
152 changed files with 15331 additions and 1538 deletions
+64 -10
View File
@@ -17,6 +17,7 @@ from knowledge_processing import classify, feed, finish
from knowledge_model_output import ModelDiscard, ModelOutputError, normalize_output, original_draft, split_batch
from knowledge_models import ModelCallError
from knowledge_store import AUTO_RUN, KnowledgeStore, job_scope, load_config
from knowledge_access import KnowledgeProcessingDenied, processing_access, processing_principal_access
# 每页读多少条消息。规则整理一步一页;模型整理一步最多读 MAX_SCAN_PAGES 页,攒够一轮并发要用的问答
# (线上 100 条消息只能切出一两段问答,只读一页的话并发和合并都用不上)。
@@ -29,6 +30,19 @@ DEFAULT_BATCH = 8
MAX_TRANSIENT = 6
def _processing_client_options(database, tenant_id, task_id):
if not task_id:
return {} # Standalone/system model probes retain their existing contract.
async def authorize_request(_request):
# The extractor can retry provider parameter errors inside one call. Check
# each actual HTTP send as well as the worker's pool and commit boundaries.
with database.connect() as db:
processing_access(db, task_id, tenant_id)
return {'event_hooks': {'request': [authorize_request]}}
def batch_size(options) -> int:
value = options.get('model_batch')
if value is None:
@@ -55,7 +69,7 @@ def enhance(candidate, database, options=None, *, tenant_id="default", task_id="
async def run():
async with UsageRecorder(database, tenant_id=tenant_id, task_id=task_id,
purpose="knowledge") as recorder:
async with httpx.AsyncClient() as client:
async with httpx.AsyncClient(**_processing_client_options(database, tenant_id, task_id)) as client:
return await extract(client, outlet, candidate, deadline=deadline,
allow_discard=allow_discard, usage_recorder=recorder)
try:
@@ -90,7 +104,7 @@ def enhance_batch(candidates, database, options=None, *, tenant_id="default", ta
async def run():
async with UsageRecorder(database, tenant_id=tenant_id, task_id=task_id,
purpose="knowledge") as recorder:
async with httpx.AsyncClient() as client:
async with httpx.AsyncClient(**_processing_client_options(database, tenant_id, task_id)) as client:
return await extract_batch(client, outlet, candidates, deadline=deadline,
allow_discard=allow_discard, usage_recorder=recorder)
try:
@@ -179,14 +193,28 @@ class KnowledgeWorker:
config = load_config(self.store.database)
with self.store.database.connect() as db:
db.execute("BEGIN IMMEDIATE")
dirty = db.execute("""SELECT d.*,w.created_by FROM knowledge_dirty d JOIN knowledge_watch w
dirty, had_dirty = None, False
candidates = db.execute("""SELECT d.*,w.created_by FROM knowledge_dirty d JOIN knowledge_watch w
ON w.tenant_id=d.tenant_id AND w.source_account_id=d.source_account_id
WHERE w.enabled=1 AND d.changed_at<? ORDER BY d.changed_at LIMIT 1""", (cutoff,)).fetchone()
WHERE w.enabled=1 AND d.changed_at<? ORDER BY d.changed_at""", (cutoff,))
for candidate in candidates:
had_dirty = True
try:
processing_principal_access(db, candidate['created_by'], candidate['tenant_id'], automatic=True)
except KnowledgeProcessingDenied:
# Keep denied work for permission restoration without letting
# it block later authorized sources, even beyond 100 entries.
continue
dirty = candidate
break
if dirty is None:
if had_dirty:
return False
# 持续整理每个会话一个小任务,留一个月够排查,再久就清掉
old = (datetime.now(timezone.utc) - timedelta(days=30)).isoformat(timespec="milliseconds")
db.execute("DELETE FROM knowledge_job WHERE id IN (SELECT id FROM knowledge_job WHERE status='completed' "
"AND (run_id=? OR json_extract(options_json,'$.incremental') IS 1) AND updated_at<? LIMIT 200)",
db.execute("DELETE FROM knowledge_job WHERE id IN (SELECT j.id FROM knowledge_job j WHERE j.status='completed' "
"AND (j.run_id=? OR json_extract(j.options_json,'$.incremental') IS 1) AND j.updated_at<? "
"AND NOT EXISTS(SELECT 1 FROM knowledge_item k WHERE k.job_id=j.id AND k.tenant_id=j.tenant_id) LIMIT 200)",
(AUTO_RUN, old))
return False
options = {"source_account_id": dirty["source_account_id"], "conversation_id": dirty["conversation_id"],
@@ -209,11 +237,17 @@ class KnowledgeWorker:
return True
def _owned(self, db, job):
return db.execute("SELECT * FROM knowledge_job WHERE id=? AND status='running' AND lease_owner=?",
(job['id'], self.owner)).fetchone()
row = db.execute("SELECT * FROM knowledge_job WHERE id=? AND status='running' AND lease_owner=?",
(job['id'], self.owner)).fetchone()
if row is not None:
processing_access(db, row['id'], row['tenant_id'])
return row
def scan(self, job, options, state, pending):
"""读一批消息,切成问答候选,连同游标一起落库(付费调用之前先保存进度)。"""
with self.store.database.connect() as db:
if not self._owned(db, job):
return None
limit = options.get('max_messages') or 0
remaining = limit - job['processed'] if limit else None
size = SCAN_BATCH if remaining is None else min(SCAN_BATCH, remaining)
@@ -244,6 +278,9 @@ class KnowledgeWorker:
# Persist the scan and redacted candidates before any paid request.
# Pending candidates survive failure, pause and process restarts.
with self.store.database.connect() as db:
db.execute('BEGIN IMMEDIATE')
if not self._owned(db, job):
return None
updated = db.execute("""UPDATE knowledge_job SET cursor_json=?,state_json=?,
processed=processed+?,skipped=skipped+?,options_json=?,lease_until=?,updated_at=?
WHERE id=? AND status='running' AND lease_owner=?""", (
@@ -287,6 +324,12 @@ class KnowledgeWorker:
def _call(self, job, options, group):
try:
# Pool submission is not authorization: queued threads may start after
# a permission change. Recheck immediately before the paid operation.
with self.store.database.connect() as db:
db.execute('BEGIN IMMEDIATE')
if not self._owned(db, job):
return 'error', ModelCallError('整理任务已暂停、取消或由其他进程接管')
return 'done', enhance_batch(group, self.store.database, options, tenant_id=job["tenant_id"], task_id=job["id"])
except ModelCallError as exc:
return 'error', exc
@@ -399,6 +442,10 @@ class KnowledgeWorker:
if job is None:
return self.enqueue_incremental()
try:
with self.store.database.connect() as db:
db.execute('BEGIN IMMEDIATE')
if not self._owned(db, job):
return True
options = json.loads(job['options_json'])
if options['engine'] == 'model' and not options.get('model_provider_id'):
from knowledge_models import resolve_model
@@ -423,13 +470,20 @@ class KnowledgeWorker:
if not saved:
return True
with self.store.database.connect() as db:
db.execute('BEGIN IMMEDIATE')
if not self._owned(db, job):
return True
db.execute("""UPDATE knowledge_job SET status=?,state_json=?,lease_owner='',lease_until=0,error='',
options_json=?,updated_at=? WHERE id=? AND status='running' AND lease_owner=?""",
('completed' if done else 'queued', json_text({} if done else state),
json_text(options), utc_now(), job['id'], self.owner))
except Exception as exc:
if isinstance(exc, ModelCallError) and exc.transient and self._retry_later(job, exc):
return True
if isinstance(exc, ModelCallError) and exc.transient:
try:
if self._retry_later(job, exc):
return True
except KnowledgeProcessingDenied as denied:
exc = denied
# Only local validation messages may be persisted; provider bodies stay private.
error = str(exc)[:240] if isinstance(exc, ValueError) and not isinstance(exc, json.JSONDecodeError) else type(exc).__name__
if isinstance(exc, ModelCallError) and exc.transient: