dandelion-memory 1.0.0rc15__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.
- benchmarks/__init__.py +3 -0
- benchmarks/adapters/__init__.py +29 -0
- benchmarks/adapters/ablations.py +406 -0
- benchmarks/adapters/base.py +72 -0
- benchmarks/adapters/controlled/__init__.py +13 -0
- benchmarks/adapters/controlled/core_archival.py +115 -0
- benchmarks/adapters/controlled/extract_resolve.py +130 -0
- benchmarks/adapters/controlled/hybrid_rag.py +120 -0
- benchmarks/adapters/controlled/no_late_binding.py +113 -0
- benchmarks/adapters/dandelion.py +94 -0
- benchmarks/adapters/native/__init__.py +31 -0
- benchmarks/adapters/native/base.py +45 -0
- benchmarks/adapters/native/dandelion_native.py +164 -0
- benchmarks/adapters/native/dandelion_native_b0.py +165 -0
- benchmarks/adapters/native/dandelion_native_b1.py +170 -0
- benchmarks/adapters/native/dandelion_native_b2.py +169 -0
- benchmarks/adapters/native/dandelion_native_b3.py +171 -0
- benchmarks/adapters/native/dandelion_native_c4.py +261 -0
- benchmarks/adapters/native/dandelion_native_c4_1.py +281 -0
- benchmarks/adapters/native/dandelion_native_c4_2.py +435 -0
- benchmarks/adapters/native/event_evidence_b2.py +616 -0
- benchmarks/adapters/native/evidence_b2.py +609 -0
- benchmarks/adapters/native/letta_native.py +253 -0
- benchmarks/adapters/native/mem0_native.py +219 -0
- benchmarks/adapters/native/store_vector_b0.py +792 -0
- benchmarks/adapters/native/store_vector_b2.py +808 -0
- benchmarks/agent_adapter_stdio_acceptance.py +86 -0
- benchmarks/bootstrap_cross_stack.py +218 -0
- benchmarks/canonical_profile_instrumentation.py +167 -0
- benchmarks/canonical_public_baseline.py +288 -0
- benchmarks/cli.py +525 -0
- benchmarks/collector_public30_offline.py +1653 -0
- benchmarks/datasets/__init__.py +45 -0
- benchmarks/datasets/conversational_generator.py +238 -0
- benchmarks/datasets/generator.py +283 -0
- benchmarks/datasets/holdout_topology_generator.py +290 -0
- benchmarks/datasets/holdout_topology_generator_v2.py +294 -0
- benchmarks/datasets/multi_world.py +1643 -0
- benchmarks/datasets/scale_generator.py +289 -0
- benchmarks/datasets/schema.py +57 -0
- benchmarks/deep_collision_stress.py +199 -0
- benchmarks/evaluators/__init__.py +12 -0
- benchmarks/evaluators/manifest.py +142 -0
- benchmarks/evaluators/metrics.py +277 -0
- benchmarks/evaluators/runner.py +258 -0
- benchmarks/f1_step0/build_dev_measurement_manifest_v1.py +127 -0
- benchmarks/f1_step0/build_dev_measurement_manifest_v2.py +127 -0
- benchmarks/f1_step0/build_dev_measurement_manifest_v3.py +146 -0
- benchmarks/f1_step0/build_ledger.py +143 -0
- benchmarks/f1_step0/build_ledger_v2.py +296 -0
- benchmarks/f1_step0/compare_dev52_readiness_v1.py +106 -0
- benchmarks/f1_step0/locator_public_smoke.py +172 -0
- benchmarks/f1_step0/prepare_dev52_owner_v1.py +133 -0
- benchmarks/f1_step0/prepare_dev52_owner_v2.py +133 -0
- benchmarks/f1_step0/public_identity_probe.py +191 -0
- benchmarks/f1_step0/public_response_mapper.py +101 -0
- benchmarks/f1_step0/real_source_public_preflight.py +244 -0
- benchmarks/f1_step0/run_exact_fusion_dev_experiment_v1.py +83 -0
- benchmarks/f1_step0/scorer.py +110 -0
- benchmarks/f1_step0/source_aware_dev_measurement_v1.py +627 -0
- benchmarks/f1_step0/source_aware_dev_measurement_v2.py +659 -0
- benchmarks/f1_step0/source_aware_dev_measurement_v3.py +776 -0
- benchmarks/f1_step0/test_public_response_mapper.py +110 -0
- benchmarks/f1_step0/test_real_source_public_preflight.py +25 -0
- benchmarks/f1_step0/test_scorer.py +158 -0
- benchmarks/f1_step0/test_source_aware_dev_measurement.py +189 -0
- benchmarks/f1_step0/test_source_aware_dev_measurement_v2.py +263 -0
- benchmarks/f1_step0/test_source_aware_dev_measurement_v3.py +334 -0
- benchmarks/f1_step0/typed_readback_public_smoke.py +181 -0
- benchmarks/forensic_c4_1_dev.py +258 -0
- benchmarks/forensic_c4_dev.py +255 -0
- benchmarks/forensic_deep25_c4_1.py +478 -0
- benchmarks/legacy_migration_acceptance.py +29 -0
- benchmarks/longmemeval_actor.py +497 -0
- benchmarks/longmemeval_agent_judge.py +593 -0
- benchmarks/longmemeval_budget.py +139 -0
- benchmarks/longmemeval_full.py +410 -0
- benchmarks/longmemeval_judge.py +327 -0
- benchmarks/longmemeval_pilot.py +316 -0
- benchmarks/longmemeval_s.py +318 -0
- benchmarks/memory_bench.py +248 -0
- benchmarks/memory_formation/__init__.py +1 -0
- benchmarks/memory_formation/audit.py +801 -0
- benchmarks/memory_formation/real_audit.py +688 -0
- benchmarks/memory_session_acceptance.py +279 -0
- benchmarks/native_codex_host.py +513 -0
- benchmarks/owner_dense_acceptance.py +126 -0
- benchmarks/pilot_seeker_vault.py +266 -0
- benchmarks/prepare_public30_ripgrep_range_owner.py +115 -0
- benchmarks/profile_canonical.py +373 -0
- benchmarks/profile_canonical_lanes.py +405 -0
- benchmarks/profile_search_chunks.py +351 -0
- benchmarks/public_ranges_faq_proof.py +121 -0
- benchmarks/public_repos/build_history_scope_v3.py +330 -0
- benchmarks/public_repos/build_oracle.py +108 -0
- benchmarks/public_repos/build_oracle_v2.py +169 -0
- benchmarks/public_repos/build_oracle_v3.py +176 -0
- benchmarks/public_repos/map_public_v2.py +296 -0
- benchmarks/public_repos/project_prompts_v2.py +31 -0
- benchmarks/public_repos/project_prompts_v3.py +29 -0
- benchmarks/public_repos/ready_admin_v2.py +214 -0
- benchmarks/public_repos/score_public_v2.py +258 -0
- benchmarks/public_repos/test_map_public_v2.py +171 -0
- benchmarks/public_repos/test_public_repo_v2.py +44 -0
- benchmarks/public_repos/test_public_repo_v3.py +46 -0
- benchmarks/public_repos/test_ready_admin_v2.py +117 -0
- benchmarks/public_repos/test_score_public_v2.py +163 -0
- benchmarks/public_repos/test_wire_v2.py +292 -0
- benchmarks/public_repos/wire_v2.py +603 -0
- benchmarks/real_blocker_fix_acceptance.py +155 -0
- benchmarks/real_scan_rescan_acceptance.py +41 -0
- benchmarks/recall_v2_20k_smoke.py +112 -0
- benchmarks/recall_v2_e1_retrieve.py +70 -0
- benchmarks/recall_v2_e1_score.py +271 -0
- benchmarks/recall_v2_e2_prepare.py +69 -0
- benchmarks/recall_v2_e2_public_score.py +91 -0
- benchmarks/recall_v2_e2_score.py +108 -0
- benchmarks/recall_v2_navigation_mcp_replay.py +308 -0
- benchmarks/recall_v2_reader_capture.py +118 -0
- benchmarks/recall_v2_reader_replay.py +136 -0
- benchmarks/run_blind_h10_holdout.py +284 -0
- benchmarks/run_blind_h9_holdout.py +275 -0
- benchmarks/run_c4_2_nightly_scale.py +446 -0
- benchmarks/run_context_scale_simulation.py +189 -0
- benchmarks/run_conversational_bench.py +170 -0
- benchmarks/run_h11_evaluation.py +316 -0
- benchmarks/run_h11_v2_evaluation.py +431 -0
- benchmarks/run_native_fixed12.py +469 -0
- benchmarks/run_native_preflight.py +280 -0
- benchmarks/run_scale_stress.py +225 -0
- benchmarks/solanazation_brownfield_01/build_oracle.py +970 -0
- benchmarks/solanazation_brownfield_01/check_level_a.py +78 -0
- benchmarks/solanazation_brownfield_01/debug_scope.py +13 -0
- benchmarks/solanazation_brownfield_01/evaluate_bootstrap_02.py +570 -0
- benchmarks/solanazation_brownfield_01/evaluate_first_pass.py +306 -0
- benchmarks/solanazation_brownfield_01/generate_dryrun_report.py +222 -0
- benchmarks/solanazation_brownfield_01/generate_manifests.py +146 -0
- benchmarks/solanazation_brownfield_01/inspect_misses.py +29 -0
- benchmarks/solanazation_brownfield_01/run_miss_forensic.py +206 -0
- benchmarks/solanazation_brownfield_01/test_facts.py +15 -0
- benchmarks/statistics/__init__.py +15 -0
- benchmarks/statistics/significance.py +326 -0
- benchmarks/test_native_mcp_preflight.py +229 -0
- benchmarks/test_prepare_public30_range_owner.py +35 -0
- benchmarks/test_public30_source_reference.py +698 -0
- benchmarks/test_recall_v2_e1_reader_input.py +89 -0
- benchmarks/test_recall_v2_navigation_mcp_replay.py +155 -0
- benchmarks/test_recall_v2_reader_replay.py +41 -0
- dandelion/__init__.py +3 -0
- dandelion/__main__.py +11 -0
- dandelion/agent_adapter.py +2369 -0
- dandelion/bootstrap/__init__.py +872 -0
- dandelion/bootstrap/alias_policy.py +50 -0
- dandelion/bootstrap/authority.py +225 -0
- dandelion/bootstrap/canonical_history.py +412 -0
- dandelion/bootstrap/classifier.py +403 -0
- dandelion/bootstrap/component_graph.py +280 -0
- dandelion/bootstrap/discovery.py +279 -0
- dandelion/bootstrap/domain_induction.py +180 -0
- dandelion/bootstrap/domain_topology.py +673 -0
- dandelion/bootstrap/evidence_envelope.py +132 -0
- dandelion/bootstrap/extractors/base.py +171 -0
- dandelion/bootstrap/extractors/exact.py +1234 -0
- dandelion/bootstrap/extractors/generic.py +100 -0
- dandelion/bootstrap/extractors/git_temporal.py +111 -0
- dandelion/bootstrap/extractors/registry.py +345 -0
- dandelion/bootstrap/extractors/relations.py +89 -0
- dandelion/bootstrap/extractors/semantic.py +424 -0
- dandelion/bootstrap/extractors/status.py +218 -0
- dandelion/bootstrap/git_sweeper.py +135 -0
- dandelion/bootstrap/manifest.py +246 -0
- dandelion/bootstrap/quarantine.py +264 -0
- dandelion/bootstrap/report.py +259 -0
- dandelion/bootstrap/root_resolver.py +221 -0
- dandelion/bootstrap/tech_profiler.py +125 -0
- dandelion/bootstrap/topology.py +75 -0
- dandelion/bootstrap/topology_index.py +110 -0
- dandelion/bootstrap/transaction.py +315 -0
- dandelion/canonical_bootstrap.py +257 -0
- dandelion/canonical_memory.py +4130 -0
- dandelion/captured_input.py +295 -0
- dandelion/cli.py +767 -0
- dandelion/config.py +40 -0
- dandelion/derived_index.py +745 -0
- dandelion/domains.py +706 -0
- dandelion/embedder.py +229 -0
- dandelion/event_evidence.py +571 -0
- dandelion/evidence.py +812 -0
- dandelion/evidence_response.py +453 -0
- dandelion/evidence_workspace.py +2360 -0
- dandelion/exact_context.py +129 -0
- dandelion/hydrator.py +124 -0
- dandelion/inspector.py +442 -0
- dandelion/inspector_assets/dandelion-mark.svg +33 -0
- dandelion/inspector_assets/dandelion_graph.js +361 -0
- dandelion/inspector_assets/inspector.css +223 -0
- dandelion/inspector_assets/inspector.html +135 -0
- dandelion/inspector_assets/inspector.js +1059 -0
- dandelion/legacy_import.py +431 -0
- dandelion/live_source_grants.py +133 -0
- dandelion/local_owner.py +114 -0
- dandelion/memory_client.py +252 -0
- dandelion/memory_contract.py +107 -0
- dandelion/memory_owner.py +560 -0
- dandelion/reader_providers.py +118 -0
- dandelion/recall_v2.py +767 -0
- dandelion/reconciler.py +219 -0
- dandelion/request_budget.py +125 -0
- dandelion/retained_basis.py +223 -0
- dandelion/retrieval.py +485 -0
- dandelion/router.py +405 -0
- dandelion/search_terms.py +53 -0
- dandelion/security.py +124 -0
- dandelion/server.py +810 -0
- dandelion/source_content_fts.py +219 -0
- dandelion/source_delivery.py +89 -0
- dandelion/source_history.py +241 -0
- dandelion/source_identity.py +88 -0
- dandelion/source_navigator.py +5 -0
- dandelion/source_reader.py +444 -0
- dandelion/source_references.py +379 -0
- dandelion/source_sections.py +265 -0
- dandelion/store_kv.py +684 -0
- dandelion/store_vector.py +1289 -0
- dandelion/studio.py +325 -0
- dandelion/wal.py +227 -0
- dandelion_memory-1.0.0rc15.dist-info/METADATA +48 -0
- dandelion_memory-1.0.0rc15.dist-info/RECORD +232 -0
- dandelion_memory-1.0.0rc15.dist-info/WHEEL +5 -0
- dandelion_memory-1.0.0rc15.dist-info/entry_points.txt +5 -0
- dandelion_memory-1.0.0rc15.dist-info/licenses/LICENSE +21 -0
- dandelion_memory-1.0.0rc15.dist-info/top_level.txt +2 -0
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
"""Stage profiler for the production ``VectorStore.search_chunks`` pipeline.
|
|
2
|
+
|
|
3
|
+
This is benchmark tooling only: it wraps existing calls temporarily and never
|
|
4
|
+
changes candidate selection, evidence resolution, or ranking semantics.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import hashlib
|
|
11
|
+
import importlib.metadata
|
|
12
|
+
import inspect
|
|
13
|
+
import json
|
|
14
|
+
import os
|
|
15
|
+
import platform
|
|
16
|
+
import sys
|
|
17
|
+
import time
|
|
18
|
+
from collections import defaultdict
|
|
19
|
+
from contextlib import contextmanager
|
|
20
|
+
from dataclasses import dataclass, field
|
|
21
|
+
from pathlib import Path
|
|
22
|
+
from typing import Any, Callable, Iterator
|
|
23
|
+
|
|
24
|
+
import dandelion.store_kv as kv_module
|
|
25
|
+
import dandelion.store_vector as vector_module
|
|
26
|
+
from dandelion.config import COLLECTION_NAME
|
|
27
|
+
from dandelion.store_kv import KVStore
|
|
28
|
+
from dandelion.store_vector import VectorStore
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def _milliseconds(seconds: float) -> float:
|
|
32
|
+
return round(seconds * 1000, 3)
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def _mean(values: list[float]) -> float:
|
|
36
|
+
return sum(values) / len(values) if values else 0.0
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _median(values: list[float]) -> float:
|
|
40
|
+
ordered = sorted(values)
|
|
41
|
+
if not ordered:
|
|
42
|
+
return 0.0
|
|
43
|
+
middle = len(ordered) // 2
|
|
44
|
+
return ordered[middle] if len(ordered) % 2 else (ordered[middle - 1] + ordered[middle]) / 2
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def _find_line(source: list[str], start: int, marker: str) -> int:
|
|
48
|
+
for offset, line in enumerate(source):
|
|
49
|
+
if marker in line:
|
|
50
|
+
return start + offset
|
|
51
|
+
raise RuntimeError(f"Cannot locate search_chunks profiling marker: {marker!r}")
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _line_stage_map() -> tuple[Callable[[int], str], dict[str, tuple[int, int]]]:
|
|
55
|
+
"""Map stable source landmarks to broad in-process retrieval stages."""
|
|
56
|
+
source, start = inspect.getsourcelines(VectorStore.search_chunks)
|
|
57
|
+
markers = {
|
|
58
|
+
"scope": "# ── Tier 0",
|
|
59
|
+
"query_evidence": "query_ev = extract_query_evidence(",
|
|
60
|
+
"embedding": "vector = Embedder.get().embed_query(query)",
|
|
61
|
+
"query_points": "# Build filter: always require is_active=True",
|
|
62
|
+
"reverse": "# ── Reverse Fact-Value Lookup",
|
|
63
|
+
"lexical": "# Extract explicit code identifiers from query",
|
|
64
|
+
"evidence": "# ── Reciprocal Rank Fusion",
|
|
65
|
+
"ranking": "# Deterministic Ranking Tuple",
|
|
66
|
+
}
|
|
67
|
+
lines = {name: _find_line(source, start, marker) for name, marker in markers.items()}
|
|
68
|
+
end = start + len(source)
|
|
69
|
+
ordered = list(markers)
|
|
70
|
+
ranges = {
|
|
71
|
+
name: (lines[name], lines[ordered[index + 1]] if index + 1 < len(ordered) else end)
|
|
72
|
+
for index, name in enumerate(ordered)
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
def stage_for(line_number: int) -> str:
|
|
76
|
+
for name, (lower, upper) in ranges.items():
|
|
77
|
+
if lower <= line_number < upper:
|
|
78
|
+
return name
|
|
79
|
+
return "other"
|
|
80
|
+
|
|
81
|
+
return stage_for, ranges
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
class _LineTracer:
|
|
85
|
+
"""Attribute execution time inside one call to search_chunks by source range."""
|
|
86
|
+
|
|
87
|
+
def __init__(self, stage_for: Callable[[int], str]) -> None:
|
|
88
|
+
self._stage_for = stage_for
|
|
89
|
+
self._target = VectorStore.search_chunks.__code__
|
|
90
|
+
self._previous_trace = None
|
|
91
|
+
self._last_line: int | None = None
|
|
92
|
+
self._last_time = 0.0
|
|
93
|
+
self.durations: dict[str, float] = defaultdict(float)
|
|
94
|
+
|
|
95
|
+
def _trace(self, frame, event: str, arg): # noqa: ANN001, ANN201 - sys.settrace protocol
|
|
96
|
+
if frame.f_code is not self._target:
|
|
97
|
+
return self._trace
|
|
98
|
+
now = time.perf_counter()
|
|
99
|
+
if self._last_line is not None:
|
|
100
|
+
self.durations[self._stage_for(self._last_line)] += now - self._last_time
|
|
101
|
+
if event == "line":
|
|
102
|
+
self._last_line = frame.f_lineno
|
|
103
|
+
self._last_time = now
|
|
104
|
+
elif event in {"return", "exception"}:
|
|
105
|
+
self._last_line = None
|
|
106
|
+
return self._trace
|
|
107
|
+
|
|
108
|
+
def __enter__(self) -> "_LineTracer":
|
|
109
|
+
self._previous_trace = sys.gettrace()
|
|
110
|
+
sys.settrace(self._trace)
|
|
111
|
+
return self
|
|
112
|
+
|
|
113
|
+
def __exit__(self, exc_type, exc, traceback) -> None: # noqa: ANN001
|
|
114
|
+
sys.settrace(self._previous_trace)
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
@dataclass
|
|
118
|
+
class CallMetrics:
|
|
119
|
+
external_seconds: dict[str, float] = field(default_factory=lambda: defaultdict(float))
|
|
120
|
+
external_calls: dict[str, int] = field(default_factory=lambda: defaultdict(int))
|
|
121
|
+
|
|
122
|
+
def timed(self, name: str, original: Callable[..., Any]) -> Callable[..., Any]:
|
|
123
|
+
def wrapped(*args: Any, **kwargs: Any) -> Any:
|
|
124
|
+
started = time.perf_counter()
|
|
125
|
+
try:
|
|
126
|
+
return original(*args, **kwargs)
|
|
127
|
+
finally:
|
|
128
|
+
self.external_seconds[name] += time.perf_counter() - started
|
|
129
|
+
self.external_calls[name] += 1
|
|
130
|
+
|
|
131
|
+
return wrapped
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def _is_typed_query(query_filter: Any) -> bool:
|
|
135
|
+
for condition in getattr(query_filter, "must", []) or []:
|
|
136
|
+
if getattr(condition, "key", None) == "memory_kind":
|
|
137
|
+
return True
|
|
138
|
+
return False
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
@contextmanager
|
|
142
|
+
def _external_stage_wrappers(store: VectorStore, metrics: CallMetrics, stage_for: Callable[[int], str]) -> Iterator[None]:
|
|
143
|
+
"""Time external calls while forwarding every argument and return unchanged."""
|
|
144
|
+
client = store._client
|
|
145
|
+
originals = {
|
|
146
|
+
"scope": vector_module.ScopeResolver.resolve,
|
|
147
|
+
"query_evidence": vector_module.extract_query_evidence,
|
|
148
|
+
"evidence": vector_module.resolve_evidence,
|
|
149
|
+
"query_points": client.query_points,
|
|
150
|
+
"retrieve": client.retrieve,
|
|
151
|
+
}
|
|
152
|
+
embedder = vector_module.Embedder.get()
|
|
153
|
+
original_embed = embedder.embed_query
|
|
154
|
+
|
|
155
|
+
def query_points(*args: Any, **kwargs: Any) -> Any:
|
|
156
|
+
name = "query_points_typed" if _is_typed_query(kwargs.get("query_filter")) else "query_points_dense"
|
|
157
|
+
return metrics.timed(name, originals["query_points"])(*args, **kwargs)
|
|
158
|
+
|
|
159
|
+
def retrieve(*args: Any, **kwargs: Any) -> Any:
|
|
160
|
+
caller = inspect.currentframe().f_back
|
|
161
|
+
name = "retrieve_reverse" if caller and stage_for(caller.f_lineno) == "reverse" else "retrieve_lexical"
|
|
162
|
+
return metrics.timed(name, originals["retrieve"])(*args, **kwargs)
|
|
163
|
+
|
|
164
|
+
vector_module.ScopeResolver.resolve = metrics.timed("scope", originals["scope"])
|
|
165
|
+
vector_module.extract_query_evidence = metrics.timed("query_evidence", originals["query_evidence"])
|
|
166
|
+
vector_module.resolve_evidence = metrics.timed("evidence", originals["evidence"])
|
|
167
|
+
client.query_points = query_points
|
|
168
|
+
client.retrieve = retrieve
|
|
169
|
+
embedder.embed_query = metrics.timed("embedding", original_embed)
|
|
170
|
+
try:
|
|
171
|
+
yield
|
|
172
|
+
finally:
|
|
173
|
+
vector_module.ScopeResolver.resolve = originals["scope"]
|
|
174
|
+
vector_module.extract_query_evidence = originals["query_evidence"]
|
|
175
|
+
vector_module.resolve_evidence = originals["evidence"]
|
|
176
|
+
client.query_points = originals["query_points"]
|
|
177
|
+
client.retrieve = originals["retrieve"]
|
|
178
|
+
embedder.embed_query = original_embed
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
def _load_queries(path: Path) -> list[dict[str, Any]]:
|
|
182
|
+
payload = json.loads(path.read_text(encoding="utf-8"))
|
|
183
|
+
rows = payload.get("queries", payload) if isinstance(payload, dict) else payload
|
|
184
|
+
if not isinstance(rows, list):
|
|
185
|
+
raise ValueError("Query fixture must be a list or an object with a 'queries' list")
|
|
186
|
+
normalized: list[dict[str, Any]] = []
|
|
187
|
+
for index, row in enumerate(rows):
|
|
188
|
+
if isinstance(row, str):
|
|
189
|
+
row = {"id": f"query-{index + 1}", "query": row}
|
|
190
|
+
if not isinstance(row, dict) or not isinstance(row.get("query"), str):
|
|
191
|
+
raise ValueError(f"Invalid query fixture entry at index {index}")
|
|
192
|
+
normalized.append({
|
|
193
|
+
"id": str(row.get("id", f"query-{index + 1}")),
|
|
194
|
+
"query": row["query"],
|
|
195
|
+
"domains": row.get("domains"),
|
|
196
|
+
"limit": int(row.get("limit", 3)),
|
|
197
|
+
"partition_ids": row.get("partition_ids"),
|
|
198
|
+
"topology_version": row.get("topology_version"),
|
|
199
|
+
})
|
|
200
|
+
return normalized
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _file_marker(path: Path) -> dict[str, Any]:
|
|
204
|
+
if not path.exists():
|
|
205
|
+
return {"exists": False}
|
|
206
|
+
stat = path.stat()
|
|
207
|
+
return {
|
|
208
|
+
"exists": True,
|
|
209
|
+
"size_bytes": stat.st_size,
|
|
210
|
+
"mtime_ns": stat.st_mtime_ns,
|
|
211
|
+
"sha256": hashlib.sha256(path.read_bytes()).hexdigest(),
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _environment_fingerprint(dandelion_dir: Path) -> dict[str, Any]:
|
|
216
|
+
qdrant_dir = dandelion_dir / "qdrant"
|
|
217
|
+
return {
|
|
218
|
+
"python": sys.version,
|
|
219
|
+
"platform": platform.platform(),
|
|
220
|
+
"packages": {
|
|
221
|
+
name: importlib.metadata.version(name)
|
|
222
|
+
for name in ("qdrant-client", "fastembed", "portalocker")
|
|
223
|
+
},
|
|
224
|
+
"embedding_model": os.getenv("DANDELION_EMBEDDING_MODEL", "default"),
|
|
225
|
+
"collection": COLLECTION_NAME,
|
|
226
|
+
"store": {
|
|
227
|
+
"dandelion_dir": str(dandelion_dir.resolve()),
|
|
228
|
+
"qdrant_mtime_ns": qdrant_dir.stat().st_mtime_ns if qdrant_dir.exists() else None,
|
|
229
|
+
"facts": _file_marker(dandelion_dir / "facts.json"),
|
|
230
|
+
"topology": _file_marker(dandelion_dir / "domain_topology.current.json"),
|
|
231
|
+
},
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
@contextmanager
|
|
236
|
+
def _open_store(dandelion_dir: Path) -> Iterator[VectorStore]:
|
|
237
|
+
"""Open the corpus with its adjacent KV store installed for reverse lookup."""
|
|
238
|
+
previous_kv = kv_module._store
|
|
239
|
+
kv_module._store = KVStore(path=dandelion_dir / "facts.json")
|
|
240
|
+
store: VectorStore | None = None
|
|
241
|
+
try:
|
|
242
|
+
store = VectorStore(path=dandelion_dir / "qdrant")
|
|
243
|
+
yield store
|
|
244
|
+
finally:
|
|
245
|
+
if store is not None:
|
|
246
|
+
store.close()
|
|
247
|
+
kv_module._store = previous_kv
|
|
248
|
+
|
|
249
|
+
|
|
250
|
+
def _profile_call(store: VectorStore, request: dict[str, Any], trace: bool) -> dict[str, Any]:
|
|
251
|
+
stage_for, ranges = _line_stage_map()
|
|
252
|
+
metrics = CallMetrics()
|
|
253
|
+
started = time.perf_counter()
|
|
254
|
+
with _external_stage_wrappers(store, metrics, stage_for):
|
|
255
|
+
if trace:
|
|
256
|
+
with _LineTracer(stage_for) as tracer:
|
|
257
|
+
results = store.search_chunks(
|
|
258
|
+
query=request["query"], domains=request["domains"], limit=request["limit"],
|
|
259
|
+
partition_ids=request["partition_ids"], topology_version=request["topology_version"],
|
|
260
|
+
)
|
|
261
|
+
line_stages = {name: _milliseconds(value) for name, value in tracer.durations.items()}
|
|
262
|
+
else:
|
|
263
|
+
results = store.search_chunks(
|
|
264
|
+
query=request["query"], domains=request["domains"], limit=request["limit"],
|
|
265
|
+
partition_ids=request["partition_ids"], topology_version=request["topology_version"],
|
|
266
|
+
)
|
|
267
|
+
line_stages = {}
|
|
268
|
+
elapsed = time.perf_counter() - started
|
|
269
|
+
return {
|
|
270
|
+
"query_id": request["id"],
|
|
271
|
+
"query": request["query"],
|
|
272
|
+
"trace_enabled": trace,
|
|
273
|
+
"total_ms": _milliseconds(elapsed),
|
|
274
|
+
"line_stage_ms": line_stages,
|
|
275
|
+
"external_stage_ms": {name: _milliseconds(value) for name, value in metrics.external_seconds.items()},
|
|
276
|
+
"external_stage_calls": dict(metrics.external_calls),
|
|
277
|
+
"line_stage_ranges": {name: list(value) for name, value in ranges.items()} if trace else {},
|
|
278
|
+
"result_count": len(results),
|
|
279
|
+
"candidate_result_ids": [row.get("id") for row in results],
|
|
280
|
+
"structural_reject": store.last_structural_reject,
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
|
|
284
|
+
def _summarize(records: list[dict[str, Any]]) -> dict[str, Any]:
|
|
285
|
+
grouped: dict[str, list[float]] = defaultdict(list)
|
|
286
|
+
for record in records:
|
|
287
|
+
grouped[record["query_id"]].append(record["total_ms"])
|
|
288
|
+
return {
|
|
289
|
+
query_id: {"runs": len(values), "median_ms": round(_median(values), 3), "mean_ms": round(_mean(values), 3)}
|
|
290
|
+
for query_id, values in grouped.items()
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
|
|
294
|
+
def main() -> int:
|
|
295
|
+
parser = argparse.ArgumentParser(description="Profile VectorStore.search_chunks without changing retrieval semantics.")
|
|
296
|
+
parser.add_argument("--dandelion-dir", type=Path, required=True, help="Existing corpus .dandelion directory")
|
|
297
|
+
parser.add_argument("--queries", type=Path, required=True, help="Fixed JSON query fixture")
|
|
298
|
+
parser.add_argument("--warm-runs", type=int, default=3, help="Traced calls per query on one open store")
|
|
299
|
+
parser.add_argument("--cold-runs", type=int, default=1, help="Fresh-store traced calls per query")
|
|
300
|
+
parser.add_argument("--control-runs", type=int, default=3, help="No-trace warm calls per query")
|
|
301
|
+
parser.add_argument("--output", type=Path, required=True, help="JSON output path")
|
|
302
|
+
args = parser.parse_args()
|
|
303
|
+
if min(args.warm_runs, args.cold_runs, args.control_runs) < 0:
|
|
304
|
+
raise ValueError("Run counts must be non-negative")
|
|
305
|
+
dandelion_dir = args.dandelion_dir.resolve()
|
|
306
|
+
if not (dandelion_dir / "qdrant").is_dir() or not (dandelion_dir / "facts.json").is_file():
|
|
307
|
+
raise ValueError("--dandelion-dir must contain facts.json and qdrant/")
|
|
308
|
+
|
|
309
|
+
queries = _load_queries(args.queries)
|
|
310
|
+
cold: list[dict[str, Any]] = []
|
|
311
|
+
for _ in range(args.cold_runs):
|
|
312
|
+
for request in queries:
|
|
313
|
+
with _open_store(dandelion_dir) as store:
|
|
314
|
+
cold.append(_profile_call(store, request, trace=True))
|
|
315
|
+
|
|
316
|
+
warm: list[dict[str, Any]] = []
|
|
317
|
+
control: list[dict[str, Any]] = []
|
|
318
|
+
with _open_store(dandelion_dir) as store:
|
|
319
|
+
for _ in range(args.warm_runs):
|
|
320
|
+
for request in queries:
|
|
321
|
+
warm.append(_profile_call(store, request, trace=True))
|
|
322
|
+
for _ in range(args.control_runs):
|
|
323
|
+
for request in queries:
|
|
324
|
+
control.append(_profile_call(store, request, trace=False))
|
|
325
|
+
|
|
326
|
+
output = {
|
|
327
|
+
"schema_version": 1,
|
|
328
|
+
"generated_at_epoch": time.time(),
|
|
329
|
+
"environment": _environment_fingerprint(dandelion_dir),
|
|
330
|
+
"queries": queries,
|
|
331
|
+
"cold_store_traced": cold,
|
|
332
|
+
"warm_traced": warm,
|
|
333
|
+
"warm_control_no_trace": control,
|
|
334
|
+
"summary": {
|
|
335
|
+
"cold_store_traced": _summarize(cold),
|
|
336
|
+
"warm_traced": _summarize(warm),
|
|
337
|
+
"warm_control_no_trace": _summarize(control),
|
|
338
|
+
"trace_overhead_estimate_ms": {
|
|
339
|
+
query_id: round(warm_summary["mean_ms"] - _summarize(control).get(query_id, {"mean_ms": 0})["mean_ms"], 3)
|
|
340
|
+
for query_id, warm_summary in _summarize(warm).items()
|
|
341
|
+
},
|
|
342
|
+
},
|
|
343
|
+
}
|
|
344
|
+
args.output.parent.mkdir(parents=True, exist_ok=True)
|
|
345
|
+
args.output.write_text(json.dumps(output, indent=2, sort_keys=True), encoding="utf-8")
|
|
346
|
+
print(json.dumps(output["summary"], indent=2, sort_keys=True))
|
|
347
|
+
return 0
|
|
348
|
+
|
|
349
|
+
|
|
350
|
+
if __name__ == "__main__":
|
|
351
|
+
raise SystemExit(main())
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
"""Offline mechanism proof through a fresh authenticated FAQ-only owner.
|
|
2
|
+
|
|
3
|
+
This does not invoke models, evaluate answers, inspect an oracle, or modify the
|
|
4
|
+
source corpus. Public output contains only hashes and aggregate metadata.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import argparse
|
|
10
|
+
import asyncio
|
|
11
|
+
import hashlib
|
|
12
|
+
import json
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
|
|
15
|
+
from fastmcp import Client
|
|
16
|
+
|
|
17
|
+
from dandelion.agent_adapter import AdapterContext, create_mcp
|
|
18
|
+
from dandelion.canonical_bootstrap import prepare_canonical_bootstrap
|
|
19
|
+
from dandelion.canonical_memory import CanonicalMemory
|
|
20
|
+
from dandelion.memory_client import MemoryClient
|
|
21
|
+
from dandelion.memory_owner import MemoryOwner
|
|
22
|
+
from dandelion.source_reader import PUBLIC_RANGES_V1, SourceReadError, read_current
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
async def tool(client, name, args):
|
|
26
|
+
result = await client.call_tool(name, args)
|
|
27
|
+
if result.is_error:
|
|
28
|
+
raise RuntimeError("Public tool failed")
|
|
29
|
+
return json.loads(next(block.text for block in result.content if getattr(block, "text", None)))
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def prove(source_path: Path, output: Path) -> dict:
|
|
33
|
+
source_path = source_path.resolve(strict=True)
|
|
34
|
+
original = source_path.read_bytes()
|
|
35
|
+
original_sha = hashlib.sha256(original).hexdigest()
|
|
36
|
+
if output.exists():
|
|
37
|
+
raise ValueError("Proof output must be a fresh isolated directory")
|
|
38
|
+
output.mkdir(parents=True)
|
|
39
|
+
source = output / "source"
|
|
40
|
+
source.mkdir()
|
|
41
|
+
(source / "FAQ.md").write_bytes(original)
|
|
42
|
+
strict_denied = False
|
|
43
|
+
try:
|
|
44
|
+
read_current(source, "FAQ.md")
|
|
45
|
+
except SourceReadError as exc:
|
|
46
|
+
strict_denied = exc.code == "SOURCE_UNAVAILABLE"
|
|
47
|
+
assert strict_denied
|
|
48
|
+
strict_plan = prepare_canonical_bootstrap(source)
|
|
49
|
+
assert "FAQ.md" not in strict_plan["source_catalog"]
|
|
50
|
+
opted = prepare_canonical_bootstrap(source, source_policy=PUBLIC_RANGES_V1)
|
|
51
|
+
assert opted["source_catalog"]["FAQ.md"]["source_policy"] == PUBLIC_RANGES_V1
|
|
52
|
+
memory = CanonicalMemory(output / "owner", source_policy=PUBLIC_RANGES_V1)
|
|
53
|
+
memory._apply_bootstrap_plan(opted)
|
|
54
|
+
service = MemoryOwner(memory.workspace, memory)
|
|
55
|
+
service.start()
|
|
56
|
+
pages = []
|
|
57
|
+
try:
|
|
58
|
+
context = AdapterContext(memory.workspace, source, source,
|
|
59
|
+
MemoryClient.for_workspace(memory.workspace), service.descriptor.owner_id)
|
|
60
|
+
async def exercise():
|
|
61
|
+
async with Client(create_mcp(context, recall_v2_preview=True)) as client:
|
|
62
|
+
catalog = await tool(client, "source_catalog", {})
|
|
63
|
+
assert [entry["path"] for entry in catalog["sources"]] == ["FAQ.md"]
|
|
64
|
+
args = {"path": "FAQ.md", "max_bytes": 8192, "max_lines": 80}
|
|
65
|
+
for _ in range(2000):
|
|
66
|
+
page = await tool(client, "source_read", args)
|
|
67
|
+
assert page["status"] == "SUPPORTED"
|
|
68
|
+
content = page["text"].encode("utf-8")
|
|
69
|
+
assert content == original[page["byte_start"]:page["byte_end"]]
|
|
70
|
+
assert page["range_sha256"] == hashlib.sha256(content).hexdigest()
|
|
71
|
+
assert page["sha256"] == original_sha
|
|
72
|
+
assert page["restricted_content_omitted"] and page["partial"]
|
|
73
|
+
assert page["complete_file"] is False
|
|
74
|
+
pages.append(page)
|
|
75
|
+
if page["continuation"] is None:
|
|
76
|
+
assert page["eof"]
|
|
77
|
+
break
|
|
78
|
+
args = {"path": "FAQ.md", "max_bytes": 8192, "max_lines": 80, **page["continuation"]}
|
|
79
|
+
else:
|
|
80
|
+
raise RuntimeError("Proof page budget exhausted")
|
|
81
|
+
asyncio.run(exercise())
|
|
82
|
+
finally:
|
|
83
|
+
service.stop()
|
|
84
|
+
ranged = read_current(source, "FAQ.md", source_policy=PUBLIC_RANGES_V1)
|
|
85
|
+
forbidden = [index for index, line in enumerate(ranged._chunks) if line is None]
|
|
86
|
+
offsets = ranged._offsets
|
|
87
|
+
for page in pages:
|
|
88
|
+
assert all(page["byte_end"] <= offsets[index] or page["byte_start"] >= offsets[index + 1]
|
|
89
|
+
for index in forbidden)
|
|
90
|
+
assert hashlib.sha256(source_path.read_bytes()).hexdigest() == original_sha
|
|
91
|
+
report = {
|
|
92
|
+
"schema": "dandelion.public-ranges-faq-mechanism-proof.v1",
|
|
93
|
+
"source_path": str(source_path), "source_sha256": original_sha,
|
|
94
|
+
"source_bytes": len(original), "source_lines": len(original.decode("utf-8").splitlines()),
|
|
95
|
+
"source_unchanged": True, "strict_read_denied": strict_denied,
|
|
96
|
+
"strict_catalog_contains_faq": False, "range_catalog_contains_faq": True,
|
|
97
|
+
"source_policy": PUBLIC_RANGES_V1, "authenticated_owner": True,
|
|
98
|
+
"pages": len(pages), "returned_safe_bytes": sum(page["byte_end"] - page["byte_start"] for page in pages),
|
|
99
|
+
"omitted_line_count": len(forbidden),
|
|
100
|
+
"omitted_bytes": sum(offsets[index + 1] - offsets[index] for index in forbidden),
|
|
101
|
+
"all_page_hashes_and_original_offsets_verified": True,
|
|
102
|
+
"forbidden_line_bytes_not_delivered": True,
|
|
103
|
+
"all_pages_partial": all(page["partial"] for page in pages),
|
|
104
|
+
"any_complete_file_claim": any(page["complete_file"] for page in pages),
|
|
105
|
+
"model_calls": 0, "oracle_access": False, "semantic_quality_evaluated": False,
|
|
106
|
+
"range_transitions_supported": False,
|
|
107
|
+
}
|
|
108
|
+
(output / "report.json").write_text(json.dumps(report, indent=2) + "\n", encoding="utf-8", newline="")
|
|
109
|
+
return report
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def main():
|
|
113
|
+
parser = argparse.ArgumentParser()
|
|
114
|
+
parser.add_argument("--source-faq", type=Path, required=True)
|
|
115
|
+
parser.add_argument("--output", type=Path, required=True)
|
|
116
|
+
args = parser.parse_args()
|
|
117
|
+
print(json.dumps(prove(args.source_faq, args.output.resolve()), indent=2))
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
if __name__ == "__main__":
|
|
121
|
+
main()
|