fusion-artifacts-engine 0.7.18__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- fusion_artifacts_engine/__init__.py +0 -0
- fusion_artifacts_engine/__main__.py +263 -0
- fusion_artifacts_engine/ai_client.py +54 -0
- fusion_artifacts_engine/auto_identifier.py +148 -0
- fusion_artifacts_engine/compactor.py +164 -0
- fusion_artifacts_engine/config.py +462 -0
- fusion_artifacts_engine/default_config.yaml +144 -0
- fusion_artifacts_engine/dsl_parser.py +231 -0
- fusion_artifacts_engine/engine.py +1372 -0
- fusion_artifacts_engine/gateway_client.py +396 -0
- fusion_artifacts_engine/ipc_consumer.py +321 -0
- fusion_artifacts_engine/long_context.py +392 -0
- fusion_artifacts_engine/metrics.py +144 -0
- fusion_artifacts_engine/models.py +168 -0
- fusion_artifacts_engine/office_ingest.py +365 -0
- fusion_artifacts_engine/rate_limiter.py +82 -0
- fusion_artifacts_engine/ref_parser.py +77 -0
- fusion_artifacts_engine/render.py +184 -0
- fusion_artifacts_engine/rpc/__init__.py +0 -0
- fusion_artifacts_engine/rpc/errors.py +61 -0
- fusion_artifacts_engine/rpc/event_bus.py +95 -0
- fusion_artifacts_engine/rpc/methods.py +1365 -0
- fusion_artifacts_engine/rpc/server.py +1279 -0
- fusion_artifacts_engine/section_index.py +189 -0
- fusion_artifacts_engine/share.py +326 -0
- fusion_artifacts_engine/storage/__init__.py +0 -0
- fusion_artifacts_engine/storage/base.py +270 -0
- fusion_artifacts_engine/storage/sqlite_storage.py +2813 -0
- fusion_artifacts_engine/token_budget.py +119 -0
- fusion_artifacts_engine/token_counter.py +80 -0
- fusion_artifacts_engine/tracing.py +132 -0
- fusion_artifacts_engine/utils.py +170 -0
- fusion_artifacts_engine/visual_dispatcher.py +135 -0
- fusion_artifacts_engine/visual_error_boundary.py +52 -0
- fusion_artifacts_engine/visual_primitives/__init__.py +34 -0
- fusion_artifacts_engine/visual_primitives/array_grid.py +66 -0
- fusion_artifacts_engine/visual_primitives/base.py +79 -0
- fusion_artifacts_engine/visual_primitives/bucket_divider.py +66 -0
- fusion_artifacts_engine/visual_primitives/data_chart.py +65 -0
- fusion_artifacts_engine/visual_primitives/flow_card.py +101 -0
- fusion_artifacts_engine/visual_primitives/geometry_2d.py +80 -0
- fusion_artifacts_engine/visual_primitives/isometric_3d.py +82 -0
- fusion_artifacts_engine/visual_primitives/tape_diagram.py +58 -0
- fusion_artifacts_engine/visual_primitives/track_timeline.py +58 -0
- fusion_artifacts_engine/webui_dist/assets/abnfDiagram-WEYOIA3C-2ebtMp5N.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/architectureDiagram-ZHVYKT53-COvSzFYy.js +36 -0
- fusion_artifacts_engine/webui_dist/assets/blockDiagram-RJAE7QA3-CsO2Iy8b.js +140 -0
- fusion_artifacts_engine/webui_dist/assets/c4Diagram-XDPPPE54-dFggQosH.js +38 -0
- fusion_artifacts_engine/webui_dist/assets/channel-BXYZthxM.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/chunk-2E7WHVMD-B93QdjG6.js +88 -0
- fusion_artifacts_engine/webui_dist/assets/chunk-2Q5K7J3B-DHEJLJup.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/chunk-4EMNKR2T-OGUUH-PY.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/chunk-55XCU76K-CKbux1-g.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/chunk-5VM5RSS4-CPHhHyIF.js +15 -0
- fusion_artifacts_engine/webui_dist/assets/chunk-JWPE2WC7-CJSxuarC.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/chunk-VQ5W62QI-LHItmtfv.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/chunk-XXDRQBXY-BRYBW56M.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/chunk-ZCHMQSOR-cGbkforM.js +2 -0
- fusion_artifacts_engine/webui_dist/assets/classDiagram-v2-4MYWR3UA-RVdXT7ne.js +217 -0
- fusion_artifacts_engine/webui_dist/assets/cose-bilkent-JH36ORCC-C1hy4K0b.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/cynefin-EF2NZ3EQ-D8ytFvIy.js +141 -0
- fusion_artifacts_engine/webui_dist/assets/cynefinDiagram-WF24UDRP-9iOV04Va.js +62 -0
- fusion_artifacts_engine/webui_dist/assets/cytoscape.esm-BLAcgzS2.js +331 -0
- fusion_artifacts_engine/webui_dist/assets/dagre-NK4GIZVX-zE4dzUJh.js +4 -0
- fusion_artifacts_engine/webui_dist/assets/defaultLocale-5voVPcsN.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/diagram-CBK3MWTC-BrXmQtKM.js +24 -0
- fusion_artifacts_engine/webui_dist/assets/diagram-I5XIIV2D-Bctxj8zx.js +24 -0
- fusion_artifacts_engine/webui_dist/assets/diagram-ODIL2UCW-DfDzzeod.js +30 -0
- fusion_artifacts_engine/webui_dist/assets/diagram-PFBEJUXE-BGZKfFXu.js +3 -0
- fusion_artifacts_engine/webui_dist/assets/diagram-RJA3I4VV-CXB6A2jx.js +41 -0
- fusion_artifacts_engine/webui_dist/assets/diagram-TYUNFSNR-gfqyjmIj.js +200 -0
- fusion_artifacts_engine/webui_dist/assets/ebnfDiagram-V4P3TTPT-CZ1BZkcl.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/elk-QONTBCTQ-C5YzS41r.js +27 -0
- fusion_artifacts_engine/webui_dist/assets/erDiagram-KYQIGQAA-B-DYTd4O.js +99 -0
- fusion_artifacts_engine/webui_dist/assets/flowDiagram-IUGLLWBU-IRAKfxcJ.js +213 -0
- fusion_artifacts_engine/webui_dist/assets/ganttDiagram-R7GPNTJY-DRdmsg6i.js +292 -0
- fusion_artifacts_engine/webui_dist/assets/gitGraphDiagram-PDYL7XHY-B0QL_KrV.js +106 -0
- fusion_artifacts_engine/webui_dist/assets/graph-Bn3Yngep.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/index-CCsQ6nhB.js +374 -0
- fusion_artifacts_engine/webui_dist/assets/index-Cw23dyL1.css +1 -0
- fusion_artifacts_engine/webui_dist/assets/infoDiagram-MVDRKAX5-DMlVkZRb.js +2 -0
- fusion_artifacts_engine/webui_dist/assets/init-DDsq4BXF.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/ishikawaDiagram-HPEHV2GE-yZW7Bvw7.js +70 -0
- fusion_artifacts_engine/webui_dist/assets/journeyDiagram-BOSHW7O7-C0UaOGz2.js +139 -0
- fusion_artifacts_engine/webui_dist/assets/kanban-definition-FNSA4HC5-D2VjWSCv.js +89 -0
- fusion_artifacts_engine/webui_dist/assets/katex-Be3d8Y4U.js +257 -0
- fusion_artifacts_engine/webui_dist/assets/linear-B0L4ZWGd.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/mermaid.core-C0Fw4Tzk.js +314 -0
- fusion_artifacts_engine/webui_dist/assets/mindmap-definition-6OY57UG3-Dy3WTB5p.js +98 -0
- fusion_artifacts_engine/webui_dist/assets/ordinal-_ShbN0yz.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/pegDiagram-ECIUJNBX-Cdm0XnAV.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/pieDiagram-GNMPY74T-TrdpBRYl.js +39 -0
- fusion_artifacts_engine/webui_dist/assets/quadrantDiagram-D57K4MC3-N1OmHTjQ.js +7 -0
- fusion_artifacts_engine/webui_dist/assets/railroadDiagram-Y72NRBL7-DhZcDSX6.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/requirementDiagram-EQYSW5RA-CGmfo0LK.js +84 -0
- fusion_artifacts_engine/webui_dist/assets/sankeyDiagram-SY24JHO5-CnAXR6RI.js +40 -0
- fusion_artifacts_engine/webui_dist/assets/sequenceDiagram-BLEHNHQU-Divp82Qv.js +169 -0
- fusion_artifacts_engine/webui_dist/assets/sizeCapture-INFHLROL-BxUSO2gs.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/stateDiagram-v2-A6IESKWZ-Ch2o3gee.js +291 -0
- fusion_artifacts_engine/webui_dist/assets/swimlanes-B3ENRKFQ-CBnYOtut.js +1 -0
- fusion_artifacts_engine/webui_dist/assets/swimlanesDiagram-AYQRV4AK-Bdp49byx.js +8 -0
- fusion_artifacts_engine/webui_dist/assets/timeline-definition-JXYKGLGB-Cp8DPlck.js +120 -0
- fusion_artifacts_engine/webui_dist/assets/usecaseDiagram-WPOLBNNX-CcF_Y4cE.js +370 -0
- fusion_artifacts_engine/webui_dist/assets/vennDiagram-Q3Y3IDCW-Dplzp3gZ.js +34 -0
- fusion_artifacts_engine/webui_dist/assets/wardleyDiagram-IVAIDKWA-fKoKxoZw.js +78 -0
- fusion_artifacts_engine/webui_dist/assets/xychartDiagram-4URNHDU4-DRVZF7Gc.js +7 -0
- fusion_artifacts_engine/webui_dist/favicon.svg +1 -0
- fusion_artifacts_engine/webui_dist/index.html +14 -0
- fusion_artifacts_engine-0.7.18.dist-info/METADATA +1115 -0
- fusion_artifacts_engine-0.7.18.dist-info/RECORD +114 -0
- fusion_artifacts_engine-0.7.18.dist-info/WHEEL +5 -0
- fusion_artifacts_engine-0.7.18.dist-info/entry_points.txt +2 -0
- fusion_artifacts_engine-0.7.18.dist-info/licenses/LICENSE +201 -0
- fusion_artifacts_engine-0.7.18.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,392 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import os
|
|
3
|
+
import time
|
|
4
|
+
|
|
5
|
+
import httpx
|
|
6
|
+
|
|
7
|
+
logger = logging.getLogger(__name__)
|
|
8
|
+
|
|
9
|
+
# v0.7.1 #91: layered context compaction. compactor remains the fallback; this module provides the two primary mechanisms:
|
|
10
|
+
# 1) Rolling summary — once the version count passes the threshold, fusion-mlx generates a changelog summary written back to
|
|
11
|
+
# artifact.summary (ref_text picks it up automatically via the existing pipeline) + metadata.summary_version for dedup.
|
|
12
|
+
# 2) RAG archival — when a version is superseded, push the old version into fusion-rag
|
|
13
|
+
# (POST /bases/{kb}/documents/ingest, doc_name=art_x_vN, metadata carrying
|
|
14
|
+
# artifact_id/version/type); metadata.archived_versions is the idempotent dedup guard.
|
|
15
|
+
# Both paths only log on failure and never block version creation/patch results.
|
|
16
|
+
# v0.7.17 #129: archive failures are no longer silent — they are recorded in
|
|
17
|
+
# metadata.rag_archive ({failed: [vnum...], last_error, status, updated_at}) and
|
|
18
|
+
# retryable via artifact.retry_archive; first-class library search (artifact.search_library)
|
|
19
|
+
# queries fusion-rag synchronously and merges with local metadata-filter results.
|
|
20
|
+
|
|
21
|
+
_ARCHIVE_TAG = "archived_versions"
|
|
22
|
+
_ARCHIVE_STATUS_TAG = "rag_archive"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _mlx_config(engine) -> tuple[str, str, str]:
|
|
26
|
+
cfg = engine.config
|
|
27
|
+
api_key = cfg.long_context_mlx_api_key or os.environ.get("FUSION_MLX_API_KEY", "")
|
|
28
|
+
return cfg.long_context_mlx_url, api_key, cfg.long_context_summary_model
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _build_changelog_digest(engine, artifact_id: str, limit: int = 40) -> str:
|
|
32
|
+
versions = engine.storage.list_versions(
|
|
33
|
+
artifact_id, page=1, page_size=limit, include_content=False
|
|
34
|
+
)
|
|
35
|
+
lines = []
|
|
36
|
+
for v in reversed(versions):
|
|
37
|
+
change = (v.change_log or "(no change log)").strip().replace("\n", " ")
|
|
38
|
+
lines.append(f"v{v.version_num}: {change}")
|
|
39
|
+
return "\n".join(lines)
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
async def maybe_generate_summary(engine, artifact, version_num: int) -> str | None:
|
|
43
|
+
# When the version count reaches the threshold and no summary exists yet for this version, call fusion-mlx to generate the rolling changelog.
|
|
44
|
+
cfg = engine.config
|
|
45
|
+
threshold = cfg.long_context_summary_threshold
|
|
46
|
+
if threshold <= 0:
|
|
47
|
+
return None
|
|
48
|
+
# Background tasks may run after other metadata writes — re-read the latest row, never trust the caller's snapshot
|
|
49
|
+
fresh = engine.storage.get_artifact(artifact.id)
|
|
50
|
+
if fresh is not None:
|
|
51
|
+
artifact = fresh
|
|
52
|
+
meta = artifact.metadata or {}
|
|
53
|
+
if meta.get("summary_version") == version_num:
|
|
54
|
+
return None
|
|
55
|
+
try:
|
|
56
|
+
count = len(
|
|
57
|
+
engine.storage.list_versions(artifact.id, page=1, page_size=500, include_content=False)
|
|
58
|
+
)
|
|
59
|
+
if count < threshold:
|
|
60
|
+
return None
|
|
61
|
+
digest = _build_changelog_digest(engine, artifact.id)
|
|
62
|
+
base_url, api_key, model = _mlx_config(engine)
|
|
63
|
+
headers = {"Authorization": f"Bearer {api_key}"} if api_key else {}
|
|
64
|
+
payload = {
|
|
65
|
+
"model": model or "default",
|
|
66
|
+
"messages": [
|
|
67
|
+
{
|
|
68
|
+
"role": "system",
|
|
69
|
+
"content": (
|
|
70
|
+
"Summarize the evolution of this artifact in <=120 words. "
|
|
71
|
+
"State what it is now and the key changes across versions. "
|
|
72
|
+
"Output the summary text only."
|
|
73
|
+
),
|
|
74
|
+
},
|
|
75
|
+
{"role": "user", "content": digest},
|
|
76
|
+
],
|
|
77
|
+
"max_tokens": 300,
|
|
78
|
+
"temperature": 0.2,
|
|
79
|
+
}
|
|
80
|
+
async with httpx.AsyncClient(timeout=60.0) as client:
|
|
81
|
+
resp = await client.post(
|
|
82
|
+
f"{base_url.rstrip('/')}/v1/chat/completions",
|
|
83
|
+
json=payload,
|
|
84
|
+
headers=headers,
|
|
85
|
+
)
|
|
86
|
+
resp.raise_for_status()
|
|
87
|
+
summary = (resp.json()["choices"][0]["message"]["content"] or "").strip()
|
|
88
|
+
if not summary:
|
|
89
|
+
logger.warning("long-context: empty summary from mlx for %s", artifact.id)
|
|
90
|
+
return None
|
|
91
|
+
engine.storage.update_artifact_summary(
|
|
92
|
+
artifact.id,
|
|
93
|
+
summary,
|
|
94
|
+
metadata_patch={"summary_version": version_num},
|
|
95
|
+
)
|
|
96
|
+
logger.info(
|
|
97
|
+
"long-context: rolling summary generated %s v%d (%d chars)",
|
|
98
|
+
artifact.id,
|
|
99
|
+
version_num,
|
|
100
|
+
len(summary),
|
|
101
|
+
)
|
|
102
|
+
return summary
|
|
103
|
+
except Exception as e: # noqa: BLE001
|
|
104
|
+
logger.warning(
|
|
105
|
+
"long-context: summary generation failed %s v%d (degrade, non-fatal): %s",
|
|
106
|
+
artifact.id,
|
|
107
|
+
version_num,
|
|
108
|
+
e,
|
|
109
|
+
)
|
|
110
|
+
return None
|
|
111
|
+
|
|
112
|
+
|
|
113
|
+
async def maybe_archive_superseded(engine, artifact, superseded_version_num: int) -> str | None:
|
|
114
|
+
# After a new version supersedes the old one, archive the old version's content into fusion-rag. Idempotent: each version is archived once.
|
|
115
|
+
cfg = engine.config
|
|
116
|
+
if not cfg.long_context_rag_enabled:
|
|
117
|
+
return None
|
|
118
|
+
# Background tasks may run after other metadata writes — re-read the latest row, never trust the caller's snapshot
|
|
119
|
+
fresh = engine.storage.get_artifact(artifact.id)
|
|
120
|
+
if fresh is not None:
|
|
121
|
+
artifact = fresh
|
|
122
|
+
meta = artifact.metadata or {}
|
|
123
|
+
archived = meta.get(_ARCHIVE_TAG) or []
|
|
124
|
+
if superseded_version_num in archived:
|
|
125
|
+
return None
|
|
126
|
+
if superseded_version_num < 1:
|
|
127
|
+
return None
|
|
128
|
+
ok, err = await _archive_version(engine, artifact, superseded_version_num)
|
|
129
|
+
_record_archive_result(engine, artifact.id, superseded_version_num, err if not ok else None)
|
|
130
|
+
if ok:
|
|
131
|
+
return f"{artifact.id}_v{superseded_version_num}"
|
|
132
|
+
return None
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
async def _archive_version(engine, artifact, version_num: int) -> tuple[bool, str | None]:
|
|
136
|
+
# Core archive push for one version. Returns (ok, error). Never raises.
|
|
137
|
+
cfg = engine.config
|
|
138
|
+
try:
|
|
139
|
+
version = engine.storage.get_version(artifact.id, version_num)
|
|
140
|
+
if version is None:
|
|
141
|
+
logger.warning(
|
|
142
|
+
"long-context: archive skip, version %s v%d not found",
|
|
143
|
+
artifact.id,
|
|
144
|
+
version_num,
|
|
145
|
+
)
|
|
146
|
+
return False, f"version {version_num} not found"
|
|
147
|
+
base_url = cfg.long_context_rag_url.rstrip("/")
|
|
148
|
+
api_key = cfg.long_context_rag_api_key or os.environ.get("FUSION_RAG_API_KEY", "")
|
|
149
|
+
headers = {"X-API-Key": api_key} if api_key else {}
|
|
150
|
+
body = {
|
|
151
|
+
"content": version.content,
|
|
152
|
+
"content_type": "text",
|
|
153
|
+
"doc_name": f"{artifact.id}_v{version_num}.txt",
|
|
154
|
+
"metadata": {
|
|
155
|
+
"artifact_id": artifact.id,
|
|
156
|
+
"artifact_version": version_num,
|
|
157
|
+
"artifact_type": artifact.type,
|
|
158
|
+
"name": artifact.name,
|
|
159
|
+
"archived_at": version.created_at,
|
|
160
|
+
},
|
|
161
|
+
}
|
|
162
|
+
async with httpx.AsyncClient(timeout=30.0) as client:
|
|
163
|
+
resp = await client.post(
|
|
164
|
+
f"{base_url}/bases/{cfg.long_context_rag_kb_id}/documents/ingest",
|
|
165
|
+
json=body,
|
|
166
|
+
headers=headers,
|
|
167
|
+
)
|
|
168
|
+
if resp.status_code >= 400:
|
|
169
|
+
detail = resp.text[:200]
|
|
170
|
+
logger.warning(
|
|
171
|
+
"long-context: rag archive rejected %s v%d: HTTP %d %s",
|
|
172
|
+
artifact.id,
|
|
173
|
+
version_num,
|
|
174
|
+
resp.status_code,
|
|
175
|
+
detail,
|
|
176
|
+
)
|
|
177
|
+
return False, f"HTTP {resp.status_code}: {detail}"
|
|
178
|
+
prev_archived = (artifact.metadata or {}).get(_ARCHIVE_TAG) or []
|
|
179
|
+
new_archived = sorted({*prev_archived, version_num})
|
|
180
|
+
engine.storage.update_artifact_summary(
|
|
181
|
+
artifact.id,
|
|
182
|
+
artifact.summary or "",
|
|
183
|
+
metadata_patch={_ARCHIVE_TAG: new_archived},
|
|
184
|
+
)
|
|
185
|
+
logger.info(
|
|
186
|
+
"long-context: archived %s v%d into rag kb=%s",
|
|
187
|
+
artifact.id,
|
|
188
|
+
version_num,
|
|
189
|
+
cfg.long_context_rag_kb_id,
|
|
190
|
+
)
|
|
191
|
+
return True, None
|
|
192
|
+
except Exception as e: # noqa: BLE001
|
|
193
|
+
logger.warning(
|
|
194
|
+
"long-context: rag archive failed %s v%d (degrade, non-fatal): %s",
|
|
195
|
+
artifact.id,
|
|
196
|
+
version_num,
|
|
197
|
+
e,
|
|
198
|
+
)
|
|
199
|
+
return False, str(e)
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
def _record_archive_result(engine, artifact_id: str, version_num: int, error: str | None) -> None:
|
|
203
|
+
# Issue #129: surface archive state in metadata.rag_archive — failures are
|
|
204
|
+
# visible and retryable via artifact.retry_archive instead of log-only.
|
|
205
|
+
try:
|
|
206
|
+
fresh = engine.storage.get_artifact(artifact_id)
|
|
207
|
+
if fresh is None:
|
|
208
|
+
return
|
|
209
|
+
meta = fresh.metadata or {}
|
|
210
|
+
status = dict(meta.get(_ARCHIVE_STATUS_TAG) or {})
|
|
211
|
+
failed = set(status.get("failed") or [])
|
|
212
|
+
if error is None:
|
|
213
|
+
failed.discard(version_num)
|
|
214
|
+
if failed:
|
|
215
|
+
status["status"] = "failed"
|
|
216
|
+
else:
|
|
217
|
+
status["status"] = "ok"
|
|
218
|
+
status.pop("last_error", None)
|
|
219
|
+
else:
|
|
220
|
+
failed.add(version_num)
|
|
221
|
+
status["status"] = "failed"
|
|
222
|
+
status["last_error"] = str(error)[:300]
|
|
223
|
+
status["failed"] = sorted(failed)
|
|
224
|
+
status["updated_at"] = time.time()
|
|
225
|
+
engine.storage.update_artifact_summary(
|
|
226
|
+
artifact_id,
|
|
227
|
+
fresh.summary or "",
|
|
228
|
+
metadata_patch={_ARCHIVE_STATUS_TAG: status},
|
|
229
|
+
)
|
|
230
|
+
except Exception: # noqa: BLE001
|
|
231
|
+
logger.exception("long-context: failed to record archive state for %s", artifact_id)
|
|
232
|
+
|
|
233
|
+
|
|
234
|
+
async def retry_failed_archives(engine, artifact_id: str) -> dict:
|
|
235
|
+
# Issue #129 acceptance: archive failure visible + retryable from the API.
|
|
236
|
+
cfg = engine.config
|
|
237
|
+
if not cfg.long_context_rag_enabled:
|
|
238
|
+
return {"retried": [], "failed": [], "status": "disabled"}
|
|
239
|
+
fresh = engine.storage.get_artifact(artifact_id)
|
|
240
|
+
if fresh is None:
|
|
241
|
+
raise ValueError(f"artifact {artifact_id} not found")
|
|
242
|
+
meta = fresh.metadata or {}
|
|
243
|
+
status = meta.get(_ARCHIVE_STATUS_TAG) or {}
|
|
244
|
+
failed = status.get("failed") or []
|
|
245
|
+
archived = meta.get(_ARCHIVE_TAG) or []
|
|
246
|
+
todo = [v for v in failed if v not in archived]
|
|
247
|
+
retried: list[int] = []
|
|
248
|
+
still_failed: list[int] = []
|
|
249
|
+
for vnum in todo:
|
|
250
|
+
ok, err = await _archive_version(engine, fresh, vnum)
|
|
251
|
+
_record_archive_result(engine, artifact_id, vnum, None if ok else err)
|
|
252
|
+
(retried if ok else still_failed).append(vnum)
|
|
253
|
+
final = engine.storage.get_artifact(artifact_id)
|
|
254
|
+
final_status = ((final.metadata or {}).get(_ARCHIVE_STATUS_TAG) or {}) if final else {}
|
|
255
|
+
logger.info(
|
|
256
|
+
"long-context: retry archive %s -> retried=%s failed=%s",
|
|
257
|
+
artifact_id,
|
|
258
|
+
retried,
|
|
259
|
+
still_failed,
|
|
260
|
+
)
|
|
261
|
+
return {
|
|
262
|
+
"retried": retried,
|
|
263
|
+
"failed": still_failed,
|
|
264
|
+
"status": final_status.get("status", "ok"),
|
|
265
|
+
"last_error": final_status.get("last_error"),
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
def _search_row(
|
|
270
|
+
artifact, version_num: int | None, source: str, score: float | None, snippet: str | None
|
|
271
|
+
) -> dict:
|
|
272
|
+
row = {
|
|
273
|
+
"artifact_id": artifact.id,
|
|
274
|
+
"name": artifact.name,
|
|
275
|
+
"type": artifact.type,
|
|
276
|
+
"kind": artifact.kind,
|
|
277
|
+
"version": version_num if version_num is not None else artifact.current_version,
|
|
278
|
+
"source": source,
|
|
279
|
+
"updated_at": artifact.updated_at,
|
|
280
|
+
}
|
|
281
|
+
if score is not None:
|
|
282
|
+
row["score"] = round(float(score), 6)
|
|
283
|
+
if snippet:
|
|
284
|
+
row["snippet"] = snippet[:200]
|
|
285
|
+
return row
|
|
286
|
+
|
|
287
|
+
|
|
288
|
+
async def search_library(
|
|
289
|
+
engine,
|
|
290
|
+
query: str,
|
|
291
|
+
top_k: int = 10,
|
|
292
|
+
threshold: float = 0.0,
|
|
293
|
+
hybrid: bool = False,
|
|
294
|
+
filters: dict | None = None,
|
|
295
|
+
) -> dict:
|
|
296
|
+
# Issue #129: first-class library search. Queries fusion-rag synchronously over
|
|
297
|
+
# archived artifact content (kb=long_context_rag_kb_id) and merges with local
|
|
298
|
+
# metadata-filter results. RAG unavailability degrades to metadata-only results
|
|
299
|
+
# with rag_status="unavailable" — never fails the whole search.
|
|
300
|
+
if not query or not str(query).strip():
|
|
301
|
+
raise ValueError("query is required")
|
|
302
|
+
cfg = engine.config
|
|
303
|
+
top_k = max(int(top_k), 1)
|
|
304
|
+
local_artifacts, _total = engine.list_all_artifacts(
|
|
305
|
+
filters=filters, sort="updated_at", page=1, page_size=top_k
|
|
306
|
+
)
|
|
307
|
+
results: dict[str, dict] = {}
|
|
308
|
+
for a in local_artifacts:
|
|
309
|
+
results[a.id] = _search_row(a, None, "metadata", None, None)
|
|
310
|
+
if not cfg.long_context_rag_enabled:
|
|
311
|
+
return {"results": list(results.values()), "rag_status": "disabled"}
|
|
312
|
+
base_url = cfg.long_context_rag_url.rstrip("/")
|
|
313
|
+
api_key = cfg.long_context_rag_api_key or os.environ.get("FUSION_RAG_API_KEY", "")
|
|
314
|
+
headers = {"X-API-Key": api_key} if api_key else {}
|
|
315
|
+
body = {
|
|
316
|
+
"query": str(query),
|
|
317
|
+
"top_k": top_k,
|
|
318
|
+
"threshold": float(threshold),
|
|
319
|
+
"hybrid": bool(hybrid),
|
|
320
|
+
}
|
|
321
|
+
rag_status = "ok"
|
|
322
|
+
try:
|
|
323
|
+
async with httpx.AsyncClient(timeout=15.0) as client:
|
|
324
|
+
resp = await client.post(
|
|
325
|
+
f"{base_url}/bases/{cfg.long_context_rag_kb_id}/search",
|
|
326
|
+
json=body,
|
|
327
|
+
headers=headers,
|
|
328
|
+
)
|
|
329
|
+
if resp.status_code >= 400:
|
|
330
|
+
logger.warning(
|
|
331
|
+
"long-context: library search rejected: HTTP %d %s",
|
|
332
|
+
resp.status_code,
|
|
333
|
+
resp.text[:200],
|
|
334
|
+
)
|
|
335
|
+
rag_status = "unavailable"
|
|
336
|
+
else:
|
|
337
|
+
hits = resp.json() or []
|
|
338
|
+
if rag_status == "ok":
|
|
339
|
+
for hit in hits:
|
|
340
|
+
if not isinstance(hit, dict):
|
|
341
|
+
continue
|
|
342
|
+
meta = hit.get("metadata") or {}
|
|
343
|
+
if isinstance(meta, str):
|
|
344
|
+
import json as _json
|
|
345
|
+
|
|
346
|
+
try:
|
|
347
|
+
meta = _json.loads(meta)
|
|
348
|
+
except Exception: # noqa: BLE001
|
|
349
|
+
meta = {}
|
|
350
|
+
aid = meta.get("artifact_id")
|
|
351
|
+
if not aid:
|
|
352
|
+
continue
|
|
353
|
+
vnum = meta.get("artifact_version")
|
|
354
|
+
snippet = hit.get("content") or hit.get("text") or ""
|
|
355
|
+
row = _search_row_of(hit, aid, vnum, snippet)
|
|
356
|
+
existing = results.get(aid)
|
|
357
|
+
if existing is None or "score" not in existing:
|
|
358
|
+
results[aid] = row
|
|
359
|
+
except Exception as e: # noqa: BLE001
|
|
360
|
+
logger.warning("long-context: library search rag unavailable (degrade): %s", e)
|
|
361
|
+
rag_status = "unavailable"
|
|
362
|
+
ranked = sorted(
|
|
363
|
+
results.values(),
|
|
364
|
+
key=lambda r: (-r.get("score", 0.0), -(r.get("updated_at") or 0)),
|
|
365
|
+
)
|
|
366
|
+
return {"results": ranked, "rag_status": rag_status}
|
|
367
|
+
|
|
368
|
+
|
|
369
|
+
def _search_row_of(hit: dict, artifact_id: str, version_num, snippet: str) -> dict:
|
|
370
|
+
meta = hit.get("metadata") or {}
|
|
371
|
+
return {
|
|
372
|
+
"artifact_id": artifact_id,
|
|
373
|
+
"name": meta.get("name") or artifact_id,
|
|
374
|
+
"type": meta.get("artifact_type"),
|
|
375
|
+
"kind": None,
|
|
376
|
+
"version": version_num,
|
|
377
|
+
"source": "rag",
|
|
378
|
+
"score": round(float(hit.get("score") or 0.0), 6),
|
|
379
|
+
"snippet": snippet[:200],
|
|
380
|
+
"updated_at": meta.get("archived_at"),
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
|
|
384
|
+
def history_query_hint(engine, artifact) -> dict:
|
|
385
|
+
# #91 acceptance: the RAG query pattern handed to consumers (no new RPC surface — documenting the usage is enough).
|
|
386
|
+
cfg = engine.config
|
|
387
|
+
return {
|
|
388
|
+
"rag_url": cfg.long_context_rag_url,
|
|
389
|
+
"kb_id": cfg.long_context_rag_kb_id,
|
|
390
|
+
"filter": {"artifact_id": artifact.id},
|
|
391
|
+
"note": "query fusion-rag /bases/{kb_id}/search with filter.artifact_id; doc_name=<artifact_id>_v<N>.txt",
|
|
392
|
+
}
|
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
import logging
|
|
2
|
+
import threading
|
|
3
|
+
|
|
4
|
+
logger = logging.getLogger(__name__)
|
|
5
|
+
|
|
6
|
+
# Ops-2: self-implemented Prometheus text format, no external dependencies.
|
|
7
|
+
# Metrics: requests_total / error_total (counters), active_conns (gauge),
|
|
8
|
+
# request_latency_seconds (histogram, fixed buckets).
|
|
9
|
+
|
|
10
|
+
_DEFAULT_BUCKETS = (
|
|
11
|
+
0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1.0, 2.5, 5.0, 10.0,
|
|
12
|
+
)
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class MetricsRegistry:
|
|
16
|
+
def __init__(self, buckets=_DEFAULT_BUCKETS):
|
|
17
|
+
self._lock = threading.Lock()
|
|
18
|
+
self._counters: dict[str, dict[str, float]] = {}
|
|
19
|
+
self._gauges: dict[str, float] = {}
|
|
20
|
+
self._hist_buckets: dict[str, tuple[float, ...]] = {}
|
|
21
|
+
self._hist_counts: dict[str, list[int]] = {}
|
|
22
|
+
self._hist_sum: dict[str, float] = {}
|
|
23
|
+
self._hist_total: dict[str, int] = {}
|
|
24
|
+
self._buckets = tuple(sorted(buckets))
|
|
25
|
+
# Pre-declare built-in metrics so exposition output order is stable
|
|
26
|
+
self._register_counter("rpc_requests_total")
|
|
27
|
+
self._register_counter("rpc_error_total")
|
|
28
|
+
self._register_gauge("rpc_active_conns")
|
|
29
|
+
self._register_histogram("rpc_request_latency_seconds")
|
|
30
|
+
|
|
31
|
+
def _register_counter(self, name: str) -> None:
|
|
32
|
+
self._counters[name] = {}
|
|
33
|
+
|
|
34
|
+
def _register_gauge(self, name: str) -> None:
|
|
35
|
+
self._gauges[name] = 0
|
|
36
|
+
|
|
37
|
+
def _register_histogram(self, name: str) -> None:
|
|
38
|
+
self._hist_buckets[name] = self._buckets
|
|
39
|
+
self._hist_counts[name] = [0] * (len(self._buckets) + 1)
|
|
40
|
+
self._hist_sum[name] = 0.0
|
|
41
|
+
self._hist_total[name] = 0
|
|
42
|
+
|
|
43
|
+
def inc_counter(self, name: str, labels: dict | None = None, amount: float = 1) -> None:
|
|
44
|
+
with self._lock:
|
|
45
|
+
counters = self._counters.setdefault(name, {})
|
|
46
|
+
key = self._label_key(labels)
|
|
47
|
+
counters[key] = counters.get(key, 0.0) + amount
|
|
48
|
+
|
|
49
|
+
def set_gauge(self, name: str, value: float) -> None:
|
|
50
|
+
with self._lock:
|
|
51
|
+
self._gauges[name] = value
|
|
52
|
+
|
|
53
|
+
def inc_gauge(self, name: str, delta: float = 1) -> None:
|
|
54
|
+
with self._lock:
|
|
55
|
+
self._gauges[name] = self._gauges.get(name, 0) + delta
|
|
56
|
+
|
|
57
|
+
def dec_gauge(self, name: str, delta: float = 1) -> None:
|
|
58
|
+
with self._lock:
|
|
59
|
+
self._gauges[name] = self._gauges.get(name, 0) - delta
|
|
60
|
+
|
|
61
|
+
def observe(self, name: str, value: float) -> None:
|
|
62
|
+
with self._lock:
|
|
63
|
+
if name not in self._hist_counts:
|
|
64
|
+
self._register_histogram(name)
|
|
65
|
+
buckets = self._hist_buckets[name]
|
|
66
|
+
counts = self._hist_counts[name]
|
|
67
|
+
placed = False
|
|
68
|
+
for i, b in enumerate(buckets):
|
|
69
|
+
if value <= b:
|
|
70
|
+
counts[i] += 1
|
|
71
|
+
placed = True
|
|
72
|
+
break
|
|
73
|
+
if not placed:
|
|
74
|
+
counts[-1] += 1
|
|
75
|
+
self._hist_sum[name] += value
|
|
76
|
+
self._hist_total[name] += 1
|
|
77
|
+
|
|
78
|
+
@staticmethod
|
|
79
|
+
def _label_key(labels: dict | None) -> str:
|
|
80
|
+
if not labels:
|
|
81
|
+
return ""
|
|
82
|
+
return ",".join(f"{k}={labels[k]}" for k in sorted(labels))
|
|
83
|
+
|
|
84
|
+
@staticmethod
|
|
85
|
+
def _label_str(labels: dict | None) -> str:
|
|
86
|
+
if not labels:
|
|
87
|
+
return ""
|
|
88
|
+
pairs = ",".join(f'{k}="{labels[k]}"' for k in sorted(labels))
|
|
89
|
+
return "{" + pairs + "}"
|
|
90
|
+
|
|
91
|
+
def expose(self) -> str:
|
|
92
|
+
# Prometheus text exposition format 0.0.4
|
|
93
|
+
lines: list[str] = []
|
|
94
|
+
with self._lock:
|
|
95
|
+
for name in sorted(self._counters):
|
|
96
|
+
lines.append(f"# HELP {name} Counter")
|
|
97
|
+
lines.append(f"# TYPE {name} counter")
|
|
98
|
+
for key, val in sorted(self._counters[name].items()):
|
|
99
|
+
if not key:
|
|
100
|
+
lines.append(f"{name} {val}")
|
|
101
|
+
else:
|
|
102
|
+
# keys look like method=xxx -> restore to {method="xxx"}
|
|
103
|
+
parts = key.split(",")
|
|
104
|
+
label_str = "{" + ",".join(
|
|
105
|
+
f'{p.split("=", 1)[0]}="{p.split("=", 1)[1]}"' for p in parts
|
|
106
|
+
) + "}"
|
|
107
|
+
lines.append(f"{name}{label_str} {val}")
|
|
108
|
+
for name in sorted(self._gauges):
|
|
109
|
+
lines.append(f"# HELP {name} Gauge")
|
|
110
|
+
lines.append(f"# TYPE {name} gauge")
|
|
111
|
+
lines.append(f"{name} {self._gauges[name]}")
|
|
112
|
+
for name in sorted(self._hist_counts):
|
|
113
|
+
lines.append(f"# HELP {name} Histogram")
|
|
114
|
+
lines.append(f"# TYPE {name} histogram")
|
|
115
|
+
buckets = self._hist_buckets[name]
|
|
116
|
+
counts = self._hist_counts[name]
|
|
117
|
+
cum = 0
|
|
118
|
+
for i, b in enumerate(buckets):
|
|
119
|
+
cum += counts[i]
|
|
120
|
+
lines.append(f'{name}_bucket{{le="{b}"}} {cum}')
|
|
121
|
+
cum += counts[-1]
|
|
122
|
+
lines.append(f'{name}_bucket{{le="+Inf"}} {cum}')
|
|
123
|
+
lines.append(f"{name}_sum {self._hist_sum[name]}")
|
|
124
|
+
lines.append(f"{name}_count {self._hist_total[name]}")
|
|
125
|
+
return "\n".join(lines) + "\n"
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
_metrics: MetricsRegistry | None = None
|
|
129
|
+
_metrics_lock = threading.Lock()
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def get_metrics() -> MetricsRegistry:
|
|
133
|
+
global _metrics
|
|
134
|
+
with _metrics_lock:
|
|
135
|
+
if _metrics is None:
|
|
136
|
+
_metrics = MetricsRegistry()
|
|
137
|
+
return _metrics
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def reset_metrics() -> None:
|
|
141
|
+
# Test helper: clear the global singleton
|
|
142
|
+
global _metrics
|
|
143
|
+
with _metrics_lock:
|
|
144
|
+
_metrics = None
|