llm-wiki-engine 5.0.0__tar.gz
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.
- llm_wiki_engine-5.0.0/LICENSE +21 -0
- llm_wiki_engine-5.0.0/MANIFEST.in +4 -0
- llm_wiki_engine-5.0.0/PKG-INFO +68 -0
- llm_wiki_engine-5.0.0/README.md +48 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/__init__.py +15 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/analysis_compatibility.py +322 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/canonical_json.py +195 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/circuit_breaker.py +172 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/concept_identity.py +1085 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/context_knowledge_contract.py +1833 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/context_request_format.py +472 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/contracts.py +335 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/engine_events.py +203 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/extract_format.py +309 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/filesystem_guard.py +2727 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/freshness_wording.py +5 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/gitignore.py +218 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/host.py +287 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/immutable.py +58 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/infrastructure_state.py +214 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/integrations.py +89 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/io.py +235 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/knowledge_artifacts.py +2135 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/knowledge_audit.py +162 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/knowledge_consumption.py +1034 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/knowledge_coverage.py +130 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/knowledge_envelope.py +2011 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/knowledge_evidence.py +953 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/knowledge_freshness.py +1007 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/knowledge_governance.py +3584 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/knowledge_graph.py +2523 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/knowledge_index.py +2096 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/knowledge_kinds.py +288 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/knowledge_links.py +621 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/knowledge_loader.py +764 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/knowledge_model.py +2308 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/knowledge_observability.py +752 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/knowledge_packs.py +844 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/knowledge_reuse_format.py +82 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/knowledge_storage.py +896 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/knowledge_storage_access.py +291 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/knowledge_storage_diagnostics.py +568 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/knowledge_storage_io.py +464 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/knowledge_storage_lifecycle.py +708 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/knowledge_stream_audit.py +168 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/knowledge_validators.py +220 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/knowledge_verification.py +298 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/lockfile.py +140 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/maintenance_evidence.py +940 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/maintenance_projection.py +331 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/maintenance_protocol.py +461 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/maintenance_queue_format.py +439 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/maintenance_recovery.py +403 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/maintenance_shapes.py +1027 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/maintenance_state.py +1171 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/maintenance_status.py +711 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/maintenance_status_format.py +532 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/manifest_storage.py +317 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/markdown_sections.py +961 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/normalization_diagnostics.py +101 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/packet_field_policy.py +226 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/path_policy.py +239 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/paths.py +103 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/progress.py +288 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/protected_artifacts.py +1811 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/py.typed +0 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/query_result_format.py +307 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/redaction.py +345 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/request_json.py +44 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/runtime_output.py +99 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/search_discovery.py +377 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/search_discovery_capture.py +136 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/search_lexical.py +440 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/search_rank.py +171 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/search_source.py +102 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/section_ownership.py +1290 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/secure_file.py +22 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/source_retirement.py +296 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/source_selection.py +903 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/storage_receipts.py +149 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/storage_sort.py +114 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/storage_spool.py +193 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/surface_index_format.py +306 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/sync_manifest.py +1714 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/sync_recovery.py +563 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/sync_retained_links.py +129 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/task_compact_readable.py +43 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/validation.py +1348 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/verification_contracts.py +1577 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/wiki_media.py +736 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/wiki_surface.py +449 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/wiki_surface_index.py +468 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/wiki_write_basis.py +54 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine/workflow_profile.py +179 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine.egg-info/PKG-INFO +68 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine.egg-info/SOURCES.txt +99 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine.egg-info/dependency_links.txt +1 -0
- llm_wiki_engine-5.0.0/llm_wiki_engine.egg-info/top_level.txt +1 -0
- llm_wiki_engine-5.0.0/pyproject.toml +36 -0
- llm_wiki_engine-5.0.0/release_build_backend.py +125 -0
- llm_wiki_engine-5.0.0/setup.cfg +4 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Denis Sivagin
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: llm-wiki-engine
|
|
3
|
+
Version: 5.0.0
|
|
4
|
+
Summary: Standard-library-only core of the LLM Wiki engine: canonical encodings, host boundary and format validators.
|
|
5
|
+
Author-email: Denis Sivagin <denissvgn@gmail.com>
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/Denissvgn/python-wiki-llm
|
|
8
|
+
Project-URL: Repository, https://github.com/Denissvgn/python-wiki-llm
|
|
9
|
+
Project-URL: Issues, https://github.com/Denissvgn/python-wiki-llm/issues
|
|
10
|
+
Keywords: llm,wiki,documentation,knowledge,engine
|
|
11
|
+
Classifier: Development Status :: 4 - Beta
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Topic :: Software Development :: Documentation
|
|
15
|
+
Classifier: Typing :: Typed
|
|
16
|
+
Requires-Python: >=3.11
|
|
17
|
+
Description-Content-Type: text/markdown
|
|
18
|
+
License-File: LICENSE
|
|
19
|
+
Dynamic: license-file
|
|
20
|
+
|
|
21
|
+
# LLM Wiki Engine
|
|
22
|
+
|
|
23
|
+
`llm-wiki-engine` is the standard-library-only core of LLM Wiki. It has no
|
|
24
|
+
third-party dependencies. Processes, environment variables, the working
|
|
25
|
+
directory and the clock are reached only through a replaceable host object.
|
|
26
|
+
|
|
27
|
+
It provides:
|
|
28
|
+
|
|
29
|
+
- canonical JSON encodings and SHA-256 digests used by every stored format;
|
|
30
|
+
- the host boundary: process runner, environment, working directory and clock;
|
|
31
|
+
- path, request and redaction rules;
|
|
32
|
+
- guarded filesystem writes, which keep the destination's directories from
|
|
33
|
+
being swapped for links or junctions mid-write, and wiki file I/O;
|
|
34
|
+
- ignore-file matching, source-selection profiles and protected-artifact
|
|
35
|
+
checks;
|
|
36
|
+
- the knowledge graph, evidence and concept-identity vocabularies;
|
|
37
|
+
- the knowledge store: the knowledge model and index, governance, packed
|
|
38
|
+
storage, the sync manifest, maintenance state and recovery, and the
|
|
39
|
+
freshness, consumption and verification formats;
|
|
40
|
+
- analysis-compatibility records;
|
|
41
|
+
- wiki surface, media, surface-index and section-ownership rules;
|
|
42
|
+
- lexical search ranking;
|
|
43
|
+
- validators for published formats such as extract payloads, documentation
|
|
44
|
+
query and search results, and maintenance status and queue reports.
|
|
45
|
+
|
|
46
|
+
The knowledge store does not analyze sources itself. Concept implementation
|
|
47
|
+
evidence, source snapshots, the active domain pack and a few issued state
|
|
48
|
+
types come from the application through `llm_wiki_engine.integrations`, which
|
|
49
|
+
names a provider module for each capability. `agent-wiki-cli` provides all of
|
|
50
|
+
them as soon as `llm_wiki_cli` is imported, so a program that uses the engine
|
|
51
|
+
next to the CLI imports `llm_wiki_cli` first. An operation that needs a
|
|
52
|
+
capability nobody provided fails with `IntegrationUnavailable`.
|
|
53
|
+
|
|
54
|
+
The import package is `llm_wiki_engine`. It requires Python 3.11 or later.
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
pip install llm-wiki-engine
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
The code-documentation CLI, [`agent-wiki-cli`](https://pypi.org/project/agent-wiki-cli/),
|
|
61
|
+
depends on an exact version of this package. Both are released together and
|
|
62
|
+
share one version number. Its older
|
|
63
|
+
`llm_wiki_cli.services.<module>` import paths for these modules still work as
|
|
64
|
+
aliases of the same modules, but they are deprecated: importing one raises a
|
|
65
|
+
`DeprecationWarning` that names the `llm_wiki_engine.<module>` path to use.
|
|
66
|
+
|
|
67
|
+
Source: <https://github.com/Denissvgn/python-wiki-llm>, in the `src/`
|
|
68
|
+
directory. Licensed under the MIT License.
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
# LLM Wiki Engine
|
|
2
|
+
|
|
3
|
+
`llm-wiki-engine` is the standard-library-only core of LLM Wiki. It has no
|
|
4
|
+
third-party dependencies. Processes, environment variables, the working
|
|
5
|
+
directory and the clock are reached only through a replaceable host object.
|
|
6
|
+
|
|
7
|
+
It provides:
|
|
8
|
+
|
|
9
|
+
- canonical JSON encodings and SHA-256 digests used by every stored format;
|
|
10
|
+
- the host boundary: process runner, environment, working directory and clock;
|
|
11
|
+
- path, request and redaction rules;
|
|
12
|
+
- guarded filesystem writes, which keep the destination's directories from
|
|
13
|
+
being swapped for links or junctions mid-write, and wiki file I/O;
|
|
14
|
+
- ignore-file matching, source-selection profiles and protected-artifact
|
|
15
|
+
checks;
|
|
16
|
+
- the knowledge graph, evidence and concept-identity vocabularies;
|
|
17
|
+
- the knowledge store: the knowledge model and index, governance, packed
|
|
18
|
+
storage, the sync manifest, maintenance state and recovery, and the
|
|
19
|
+
freshness, consumption and verification formats;
|
|
20
|
+
- analysis-compatibility records;
|
|
21
|
+
- wiki surface, media, surface-index and section-ownership rules;
|
|
22
|
+
- lexical search ranking;
|
|
23
|
+
- validators for published formats such as extract payloads, documentation
|
|
24
|
+
query and search results, and maintenance status and queue reports.
|
|
25
|
+
|
|
26
|
+
The knowledge store does not analyze sources itself. Concept implementation
|
|
27
|
+
evidence, source snapshots, the active domain pack and a few issued state
|
|
28
|
+
types come from the application through `llm_wiki_engine.integrations`, which
|
|
29
|
+
names a provider module for each capability. `agent-wiki-cli` provides all of
|
|
30
|
+
them as soon as `llm_wiki_cli` is imported, so a program that uses the engine
|
|
31
|
+
next to the CLI imports `llm_wiki_cli` first. An operation that needs a
|
|
32
|
+
capability nobody provided fails with `IntegrationUnavailable`.
|
|
33
|
+
|
|
34
|
+
The import package is `llm_wiki_engine`. It requires Python 3.11 or later.
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
pip install llm-wiki-engine
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
The code-documentation CLI, [`agent-wiki-cli`](https://pypi.org/project/agent-wiki-cli/),
|
|
41
|
+
depends on an exact version of this package. Both are released together and
|
|
42
|
+
share one version number. Its older
|
|
43
|
+
`llm_wiki_cli.services.<module>` import paths for these modules still work as
|
|
44
|
+
aliases of the same modules, but they are deprecated: importing one raises a
|
|
45
|
+
`DeprecationWarning` that names the `llm_wiki_engine.<module>` path to use.
|
|
46
|
+
|
|
47
|
+
Source: <https://github.com/Denissvgn/python-wiki-llm>, in the `src/`
|
|
48
|
+
directory. Licensed under the MIT License.
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
"""Standard-library-only core of the LLM Wiki engine.
|
|
2
|
+
|
|
3
|
+
The modules in this package hold the parts of the engine that need nothing
|
|
4
|
+
beyond the Python standard library: canonical JSON encodings and digests,
|
|
5
|
+
the host boundary (processes, environment, working directory, clock), path
|
|
6
|
+
and request validation, the knowledge graph and evidence vocabularies, wiki
|
|
7
|
+
surface and media rules, search ranking, and validators for the published
|
|
8
|
+
JSON formats. They import only the standard library and each other.
|
|
9
|
+
|
|
10
|
+
``agent-wiki-cli`` builds the code-documentation product on top of this
|
|
11
|
+
package. Its ``llm_wiki_cli.services.<module>`` import paths for these
|
|
12
|
+
modules remain available as aliases of the same module objects.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
__version__ = "5.0.0"
|
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
"""Pure, versioned comparison of application-owned analysis commitments.
|
|
2
|
+
|
|
3
|
+
This module is also shipped in the isolated release harness. Keep it stdlib-only
|
|
4
|
+
and never resolve executable paths or declarations from knowledge documents.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from collections.abc import Mapping
|
|
10
|
+
from contextlib import contextmanager
|
|
11
|
+
from contextvars import ContextVar
|
|
12
|
+
from functools import wraps
|
|
13
|
+
from typing import Callable, ParamSpec, TypeVar
|
|
14
|
+
import hashlib
|
|
15
|
+
import json
|
|
16
|
+
import re
|
|
17
|
+
|
|
18
|
+
EXTENSION = "llm-wiki/analysis-compatibility-v1"
|
|
19
|
+
SCHEMA = "llm-wiki-analysis-compatibility/v1"
|
|
20
|
+
COMPARISON_SCHEMA = "llm-wiki-analysis-comparison/v1"
|
|
21
|
+
POLICIES = frozenset({"auto", "exact-v1", "analysis-v1"})
|
|
22
|
+
_ACTIVE: ContextVar[str] = ContextVar("analysis_comparison_policy", default="auto")
|
|
23
|
+
_HASH = re.compile(r"sha256:[0-9a-f]{64}\Z")
|
|
24
|
+
_FIELDS = frozenset({"schema_version", "component", "contract", "implementation",
|
|
25
|
+
"configuration", "runtime", "provenance", "identity"})
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def digest(value: object) -> str:
|
|
29
|
+
raw = json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True,
|
|
30
|
+
allow_nan=False).encode("utf-8")
|
|
31
|
+
return "sha256:" + hashlib.sha256(raw).hexdigest()
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def selected_policy(value: str | None = None) -> str:
|
|
35
|
+
value = _ACTIVE.get() if value is None else value
|
|
36
|
+
if not isinstance(value, str) or value not in POLICIES:
|
|
37
|
+
raise ValueError("comparison_policy must be auto, exact-v1 or analysis-v1")
|
|
38
|
+
return value
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
@contextmanager
|
|
42
|
+
def comparison_scope(value: str):
|
|
43
|
+
token = _ACTIVE.set(selected_policy(value))
|
|
44
|
+
try:
|
|
45
|
+
yield
|
|
46
|
+
finally:
|
|
47
|
+
_ACTIVE.reset(token)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def validate_record(value: object, component: str | None = None) -> dict:
|
|
51
|
+
if not isinstance(value, Mapping) or set(value) != _FIELDS:
|
|
52
|
+
raise ValueError("analysis compatibility fields do not match v1")
|
|
53
|
+
result = dict(value)
|
|
54
|
+
if result["schema_version"] != SCHEMA:
|
|
55
|
+
raise ValueError("unsupported analysis compatibility schema")
|
|
56
|
+
for key in ("component", "contract"):
|
|
57
|
+
if not isinstance(result[key], str) or not 0 < len(result[key]) <= 256:
|
|
58
|
+
raise ValueError("invalid analysis component/contract")
|
|
59
|
+
if component is not None and result["component"] != component:
|
|
60
|
+
raise ValueError("analysis compatibility belongs to another component")
|
|
61
|
+
if result["contract"] != "structural-observations/v1":
|
|
62
|
+
raise ValueError("unsupported observation contract")
|
|
63
|
+
if result["component"] not in {"agent-wiki-cli", *("llm-wiki/extractor/" + x for x in ("python", "typescript", "javascript", "go", "rust", "haskell", "infrastructure"))}:
|
|
64
|
+
raise ValueError("unsupported analysis component")
|
|
65
|
+
for key in ("implementation", "configuration", "runtime", "identity"):
|
|
66
|
+
if not isinstance(result[key], str) or not _HASH.fullmatch(result[key]):
|
|
67
|
+
raise ValueError("invalid analysis commitment")
|
|
68
|
+
provenance = result["provenance"]
|
|
69
|
+
if not isinstance(provenance, Mapping) or set(provenance) != {"python", "platform", "helper"}:
|
|
70
|
+
raise ValueError("invalid analysis runtime provenance")
|
|
71
|
+
if any(not isinstance(v, str) or len(v) > 8192 for v in provenance.values()):
|
|
72
|
+
raise ValueError("invalid analysis runtime provenance value")
|
|
73
|
+
if result["identity"] != digest({k: result[k] for k in sorted(_FIELDS - {"identity", "provenance"})}):
|
|
74
|
+
raise ValueError("analysis compatibility identity differs from its inputs")
|
|
75
|
+
return result
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def make_record(component: str, contract: str, implementation: str,
|
|
79
|
+
configuration: str, runtime: str, provenance: Mapping) -> dict:
|
|
80
|
+
result = dict(schema_version=SCHEMA, component=component, contract=contract,
|
|
81
|
+
implementation=implementation, configuration=configuration,
|
|
82
|
+
runtime=runtime, provenance=dict(provenance))
|
|
83
|
+
result["identity"] = digest({k: v for k, v in result.items() if k != "provenance"})
|
|
84
|
+
return validate_record(result, component)
|
|
85
|
+
|
|
86
|
+
|
|
87
|
+
def component_record(component) -> dict | None:
|
|
88
|
+
extensions = component.get("extensions", {}) if isinstance(component, Mapping) else component.extensions
|
|
89
|
+
value = extensions.get(EXTENSION)
|
|
90
|
+
if value is None:
|
|
91
|
+
return None
|
|
92
|
+
name = component["id"] if isinstance(component, Mapping) else component.component_id
|
|
93
|
+
record = validate_record(value, name)
|
|
94
|
+
configured = component["configuration_hash"] if isinstance(component, Mapping) else component.configuration_hash
|
|
95
|
+
if configured != configuration_commitment(record):
|
|
96
|
+
raise ValueError("analysis metadata is not bound by producer configuration")
|
|
97
|
+
return record
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def has_contract(producer) -> bool:
|
|
101
|
+
return component_record(producer.tool) is not None
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
def committed_configuration(configuration: Mapping, record: Mapping) -> dict:
|
|
105
|
+
return {"analysis_configuration": record["configuration"], "analysis_compatibility": record["identity"]}
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def configuration_commitment(record: Mapping) -> str:
|
|
109
|
+
return digest({"domain": "llm-wiki/component-configuration/v1", "configuration": committed_configuration({}, record)})
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
def compare_components(recorded, live, *, policy: str = "auto", plugins: bool = False, configuration_required: bool = True) -> str | None:
|
|
113
|
+
"""Return the differing basis, or None; callers map it to their contract."""
|
|
114
|
+
policy = selected_policy(policy)
|
|
115
|
+
def get(component, name):
|
|
116
|
+
if isinstance(component, Mapping):
|
|
117
|
+
return component["id" if name == "component_id" else name]
|
|
118
|
+
return getattr(component, name)
|
|
119
|
+
if get(recorded, "component_id") != get(live, "component_id"):
|
|
120
|
+
return "id"
|
|
121
|
+
for item in (recorded, live):
|
|
122
|
+
if get(item, "version") == "unknown" or "version-unknown" in get(item, "limitations"):
|
|
123
|
+
return "version"
|
|
124
|
+
if "configuration-basis-unknown" in get(item, "limitations") or (configuration_required and get(item, "configuration_hash") is None):
|
|
125
|
+
return "configuration"
|
|
126
|
+
left, right = component_record(recorded), component_record(live)
|
|
127
|
+
if left is not None:
|
|
128
|
+
if right is None:
|
|
129
|
+
return "configuration"
|
|
130
|
+
if any(left[k] != right[k] for k in ("contract", "implementation", "configuration", "runtime")):
|
|
131
|
+
return "configuration"
|
|
132
|
+
elif policy == "analysis-v1":
|
|
133
|
+
return "configuration"
|
|
134
|
+
exact = policy == "exact-v1" or plugins or left is None or right is None
|
|
135
|
+
if exact and get(recorded, "version") != get(live, "version"):
|
|
136
|
+
return "version"
|
|
137
|
+
if get(recorded, "configuration_hash") != get(live, "configuration_hash"):
|
|
138
|
+
return "configuration"
|
|
139
|
+
if get(recorded, "limitations") != get(live, "limitations"):
|
|
140
|
+
return "limitations"
|
|
141
|
+
return None
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def analysis_diagnostic(recorded: Mapping, live: Mapping) -> dict | None:
|
|
145
|
+
"""Explain bound analysis commitments without making an eligibility decision.
|
|
146
|
+
|
|
147
|
+
``None`` means the available analysis commitments match, not that an exact
|
|
148
|
+
version/plugin policy passes. Missing, unsupported or unbound metadata cannot
|
|
149
|
+
establish a changed dimension. The legacy comparison vocabulary stays intact.
|
|
150
|
+
"""
|
|
151
|
+
if not recorded and not live:
|
|
152
|
+
return {
|
|
153
|
+
"changes": {}, "unavailable": (),
|
|
154
|
+
"description": "Analysis-basis details unavailable: no components were captured.",
|
|
155
|
+
"hint": "Inspect the unavailable recorded/live analysis commitments before selecting a repair.",
|
|
156
|
+
}
|
|
157
|
+
changes = {}
|
|
158
|
+
unavailable = []
|
|
159
|
+
for key in sorted(set(recorded) | set(live)):
|
|
160
|
+
try:
|
|
161
|
+
before = component_record(recorded[key])
|
|
162
|
+
after = component_record(live[key])
|
|
163
|
+
if (before is None or after is None
|
|
164
|
+
or before["component"] != key or after["component"] != key):
|
|
165
|
+
raise ValueError("comparable analysis commitments unavailable")
|
|
166
|
+
except (AttributeError, KeyError, TypeError, ValueError):
|
|
167
|
+
unavailable.append(key)
|
|
168
|
+
continue
|
|
169
|
+
dimensions = tuple(
|
|
170
|
+
name for name in ("contract", "implementation", "configuration", "runtime")
|
|
171
|
+
if before[name] != after[name]
|
|
172
|
+
)
|
|
173
|
+
if dimensions:
|
|
174
|
+
changes[key] = dimensions
|
|
175
|
+
if not changes and not unavailable:
|
|
176
|
+
return None
|
|
177
|
+
parts = []
|
|
178
|
+
if changes:
|
|
179
|
+
parts.append("Analysis commitments changed: " + "; ".join(
|
|
180
|
+
key + ": " + ", ".join(dimensions) for key, dimensions in changes.items()
|
|
181
|
+
) + ".")
|
|
182
|
+
if unavailable:
|
|
183
|
+
parts.append(f"Analysis-basis details unavailable for {len(unavailable)} component(s).")
|
|
184
|
+
if not changes:
|
|
185
|
+
parts.append("No contract, implementation, configuration or runtime cause can be inferred.")
|
|
186
|
+
hint = "Inspect the unavailable recorded/live analysis commitments before selecting a repair."
|
|
187
|
+
else:
|
|
188
|
+
dimensions = {name for names in changes.values() for name in names}
|
|
189
|
+
actions = []
|
|
190
|
+
if "contract" in dimensions:
|
|
191
|
+
actions.append("Use a supported observation contract before refreshing evidence.")
|
|
192
|
+
if "implementation" in dimensions:
|
|
193
|
+
actions.append("Align the producer/helper implementation with the intended analysis basis.")
|
|
194
|
+
if "configuration" in dimensions:
|
|
195
|
+
actions.append("Restore the recorded configuration, or review an owning refresh with the intended configuration.")
|
|
196
|
+
if "runtime" in dimensions:
|
|
197
|
+
actions.append("Review the changed execution runtime and capture on the intended target host with the same source selection and helper cache.")
|
|
198
|
+
actions.append("Re-run strict validation after the reviewed owning refresh.")
|
|
199
|
+
hint = " ".join(actions)
|
|
200
|
+
return {"changes": changes, "unavailable": tuple(unavailable),
|
|
201
|
+
"description": " ".join(parts), "hint": hint}
|
|
202
|
+
|
|
203
|
+
|
|
204
|
+
def report_schema(requested: str, details: Mapping | None, *, legacy: str = "v1") -> str:
|
|
205
|
+
migrated = bool(details and details.get("schema_version") == "llm-wiki-health-details/v2")
|
|
206
|
+
if requested == "auto":
|
|
207
|
+
return "v4" if migrated else legacy
|
|
208
|
+
if migrated and details is not None and requested != "v4" and details["basis"]["policy"] != "exact-v1":
|
|
209
|
+
raise ValueError("migrated knowledge requires report-schema v4 or comparison-policy exact-v1")
|
|
210
|
+
return requested
|
|
211
|
+
|
|
212
|
+
|
|
213
|
+
def legacy_details(details: Mapping) -> dict:
|
|
214
|
+
result = json.loads(json.dumps(details))
|
|
215
|
+
result["schema_version"] = "llm-wiki-health-details/v1"
|
|
216
|
+
result["basis"]["policy"] = "exact-producer-versions"
|
|
217
|
+
result["basis"]["analysis_contract"] = None
|
|
218
|
+
result["basis"].pop("comparison", None)
|
|
219
|
+
return result
|
|
220
|
+
|
|
221
|
+
|
|
222
|
+
_P = ParamSpec("_P")
|
|
223
|
+
_R = TypeVar("_R")
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def comparison_entrypoint(function: Callable[_P, _R]) -> Callable[_P, _R]:
|
|
227
|
+
@wraps(function)
|
|
228
|
+
def wrapped(*args: _P.args, **kwargs: _P.kwargs) -> _R:
|
|
229
|
+
value = kwargs.get("comparison_policy")
|
|
230
|
+
if value is None:
|
|
231
|
+
return function(*args, **kwargs)
|
|
232
|
+
if kwargs.get("service") is not None:
|
|
233
|
+
raise ValueError("service owns its captured comparison policy")
|
|
234
|
+
if not isinstance(value, str):
|
|
235
|
+
raise ValueError("comparison_policy must be a string")
|
|
236
|
+
with comparison_scope(value):
|
|
237
|
+
return function(*args, **kwargs)
|
|
238
|
+
return wrapped
|
|
239
|
+
|
|
240
|
+
|
|
241
|
+
|
|
242
|
+
def detailed_v2(details: Mapping) -> dict:
|
|
243
|
+
result = json.loads(json.dumps(details))
|
|
244
|
+
if result["schema_version"] == "llm-wiki-health-details/v2":
|
|
245
|
+
return result
|
|
246
|
+
result["schema_version"] = "llm-wiki-health-details/v2"
|
|
247
|
+
result["basis"]["policy"] = "exact-v1"
|
|
248
|
+
contracts: dict = {"schema_version": COMPARISON_SCHEMA}
|
|
249
|
+
for side in ("recorded", "live"):
|
|
250
|
+
producer = result["basis"][side]
|
|
251
|
+
contracts[side] = None if producer is None else {
|
|
252
|
+
c["id"]: None for c in [producer["tool"], *producer["extractors"], *producer["plugins"]]
|
|
253
|
+
}
|
|
254
|
+
result["basis"]["analysis_contract"] = contracts
|
|
255
|
+
result["basis"]["comparison"] = basis_decision(result["basis"])
|
|
256
|
+
return result
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
def producer_contracts(producer) -> dict:
|
|
261
|
+
return {c.component_id: component_record(c) for c in (producer.tool, *producer.extractors, *producer.plugins)}
|
|
262
|
+
|
|
263
|
+
|
|
264
|
+
def captured_components(basis: Mapping, side: str) -> dict:
|
|
265
|
+
producer = basis[side]
|
|
266
|
+
if not isinstance(producer, Mapping):
|
|
267
|
+
raise ValueError("analysis producer is unavailable")
|
|
268
|
+
components = [producer["tool"], *producer["extractors"], *producer["plugins"]]
|
|
269
|
+
analysis = basis["analysis_contract"]
|
|
270
|
+
if not isinstance(analysis, Mapping) or set(analysis) != {"schema_version", "recorded", "live"} or analysis["schema_version"] != COMPARISON_SCHEMA:
|
|
271
|
+
raise ValueError("unsupported analysis comparison contract")
|
|
272
|
+
records = analysis[side]
|
|
273
|
+
if not isinstance(records, Mapping) or set(records) != {c["id"] for c in components}:
|
|
274
|
+
raise ValueError("analysis records do not cover the producer")
|
|
275
|
+
result = {}
|
|
276
|
+
for component in components:
|
|
277
|
+
record = records[component["id"]]
|
|
278
|
+
if record is not None:
|
|
279
|
+
validate_record(record, component["id"])
|
|
280
|
+
result[component["id"]] = {**component, "extensions": {} if record is None else {EXTENSION: record}}
|
|
281
|
+
component_record(result[component["id"]])
|
|
282
|
+
return result
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def basis_decision(basis: Mapping) -> dict:
|
|
286
|
+
def decision(state, reason, component=None):
|
|
287
|
+
return {"state": state, "reason": reason, "component": component}
|
|
288
|
+
if basis["recorded"] is None or basis["live"] is None:
|
|
289
|
+
return decision("unavailable", "basis-unavailable")
|
|
290
|
+
left, right = captured_components(basis, "recorded"), captured_components(basis, "live")
|
|
291
|
+
recorded, live = basis["recorded"], basis["live"]
|
|
292
|
+
for key in ("knowledge_schema_version", "generation_options_hash"):
|
|
293
|
+
if recorded[key] != live[key]:
|
|
294
|
+
return decision("incompatible", "schema-changed" if key == "knowledge_schema_version" else "generation-options-changed")
|
|
295
|
+
if {c["id"] for c in recorded["plugins"]} != {c["id"] for c in live["plugins"]}:
|
|
296
|
+
return decision("incompatible", "plugin-set-changed")
|
|
297
|
+
policy = selected_policy(basis["policy"])
|
|
298
|
+
for key, value in left.items():
|
|
299
|
+
if key not in right:
|
|
300
|
+
return decision("unavailable", "producer-component-absent", key)
|
|
301
|
+
difference = compare_components(value, right[key], policy=policy,
|
|
302
|
+
plugins=bool(recorded["plugins"] or live["plugins"]), configuration_required=key != recorded["tool"]["id"])
|
|
303
|
+
if difference is not None:
|
|
304
|
+
return decision("incompatible", {"version": "producer-version-changed", "configuration": "analysis-configuration-changed", "limitations": "producer-limitations-changed", "id": "producer-id-changed"}[difference], key)
|
|
305
|
+
mode = "matching-exact-inputs" if policy == "exact-v1" or component_record(left[recorded["tool"]["id"]]) is None else "matching-analysis-inputs"
|
|
306
|
+
if recorded["plugins"]:
|
|
307
|
+
mode = "matching-analysis-and-exact-plugin-inputs"
|
|
308
|
+
return decision("compatible", mode)
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def compatible_basis(basis: Mapping) -> bool:
|
|
312
|
+
return basis_decision(basis)["state"] == "compatible"
|
|
313
|
+
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def bound_comparison(function: Callable[_P, _R]) -> Callable[_P, _R]:
|
|
317
|
+
@wraps(function)
|
|
318
|
+
def wrapped(*args: _P.args, **kwargs: _P.kwargs) -> _R:
|
|
319
|
+
owner = args[0]
|
|
320
|
+
with comparison_scope(getattr(owner, "comparison_policy", "auto")):
|
|
321
|
+
return function(*args, **kwargs)
|
|
322
|
+
return wrapped
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
"""Named canonical JSON encodings, bounded chunks and exact scalar sizes.
|
|
2
|
+
|
|
3
|
+
Only immutable JSON syntax is handled here. There is no filesystem or validity
|
|
4
|
+
cache. Persisted digests depend on each encoding byte for byte:
|
|
5
|
+
|
|
6
|
+
- ``compact``: sorted keys, ``,``/``:`` separators, UTF-8, no trailing LF.
|
|
7
|
+
- ``compact_line``: ``compact`` plus one LF; the storage and maintenance form,
|
|
8
|
+
also emitted by :func:`canonical_chunks`.
|
|
9
|
+
- ``ascii_compact``: ``compact`` with non-ASCII escaped.
|
|
10
|
+
- ``indented_line``: two-space indent, sorted keys, UTF-8, one trailing LF.
|
|
11
|
+
|
|
12
|
+
Encoders reject NaN and infinities unless ``allow_nan=True`` is passed for a
|
|
13
|
+
format that already accepts them.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
import hashlib
|
|
19
|
+
import json
|
|
20
|
+
import math
|
|
21
|
+
import re
|
|
22
|
+
from functools import lru_cache
|
|
23
|
+
from collections.abc import Iterator, Mapping
|
|
24
|
+
from typing import Any
|
|
25
|
+
|
|
26
|
+
_ESCAPED = re.compile(r'["\\\x00-\x1f]')
|
|
27
|
+
_SHORT = frozenset('"\\\b\f\n\r\t')
|
|
28
|
+
CHUNK_BYTES = 65_536
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def compact_text(value: Any, *, allow_nan: bool = False) -> str:
|
|
32
|
+
return json.dumps(value, ensure_ascii=False, sort_keys=True,
|
|
33
|
+
separators=(",", ":"), allow_nan=allow_nan)
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def compact_bytes(value: Any, *, allow_nan: bool = False) -> bytes:
|
|
37
|
+
return compact_text(value, allow_nan=allow_nan).encode("utf-8")
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def compact_line_bytes(value: Any) -> bytes:
|
|
41
|
+
return (compact_text(value) + "\n").encode("utf-8")
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def ascii_compact_bytes(value: Any, *, allow_nan: bool = False) -> bytes:
|
|
45
|
+
return json.dumps(value, ensure_ascii=True, sort_keys=True,
|
|
46
|
+
separators=(",", ":"), allow_nan=allow_nan).encode("utf-8")
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def indented_line_text(value: Any) -> str:
|
|
50
|
+
return json.dumps(value, ensure_ascii=False, indent=2, sort_keys=True,
|
|
51
|
+
allow_nan=False) + "\n"
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def sha256_digest(data: bytes) -> str:
|
|
55
|
+
"""The ``sha256:<hex>`` wire form of a digest over raw bytes."""
|
|
56
|
+
return "sha256:" + hashlib.sha256(data).hexdigest()
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class CanonicalArray:
|
|
60
|
+
"""Explicit repeatable array stream for internal spill-backed operations."""
|
|
61
|
+
|
|
62
|
+
def __init__(self, values):
|
|
63
|
+
self.values = values
|
|
64
|
+
|
|
65
|
+
def __iter__(self):
|
|
66
|
+
return iter(self.values)
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
def _string_size(value: str) -> int:
|
|
70
|
+
size = len(value.encode("utf-8")) + 2
|
|
71
|
+
if _ESCAPED.search(value) is None:
|
|
72
|
+
return size
|
|
73
|
+
return size + sum(1 if m[0] in _SHORT else 5 for m in _ESCAPED.finditer(value))
|
|
74
|
+
|
|
75
|
+
|
|
76
|
+
_short_string_size = lru_cache(maxsize=8192)(_string_size)
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
def scalar_size(value: Any) -> int:
|
|
80
|
+
"""Exact encoded bytes, excluding a trailing newline, without JSON buffers."""
|
|
81
|
+
if isinstance(value, str):
|
|
82
|
+
return _short_string_size(value) if len(value) <= 512 else _string_size(value)
|
|
83
|
+
if value is None:
|
|
84
|
+
return 4
|
|
85
|
+
if value is True:
|
|
86
|
+
return 4
|
|
87
|
+
if value is False:
|
|
88
|
+
return 5
|
|
89
|
+
if isinstance(value, int):
|
|
90
|
+
return len(int.__repr__(value))
|
|
91
|
+
if isinstance(value, float) and math.isfinite(value):
|
|
92
|
+
return len(float.__repr__(value))
|
|
93
|
+
raise ValueError("requires a finite JSON scalar")
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def _fits(value: Any, budget: int) -> bool:
|
|
97
|
+
# A bounded conservative estimate chooses the C encoder for record-sized
|
|
98
|
+
# subtrees. Large values use the streaming path, without a whole-model dump.
|
|
99
|
+
pending = [value]
|
|
100
|
+
nodes = 0
|
|
101
|
+
while pending:
|
|
102
|
+
item = pending.pop()
|
|
103
|
+
nodes += 1
|
|
104
|
+
if nodes > 512:
|
|
105
|
+
return False
|
|
106
|
+
if isinstance(item, str):
|
|
107
|
+
budget -= 2 + 6 * len(item)
|
|
108
|
+
elif isinstance(item, dict):
|
|
109
|
+
if len(item) > 512 or any(not isinstance(k, str) for k in item):
|
|
110
|
+
return False
|
|
111
|
+
budget -= 2 + 2 * len(item)
|
|
112
|
+
pending.extend(item.keys())
|
|
113
|
+
pending.extend(item.values())
|
|
114
|
+
elif isinstance(item, (list, tuple)):
|
|
115
|
+
if len(item) > 512:
|
|
116
|
+
return False
|
|
117
|
+
budget -= 2 + len(item)
|
|
118
|
+
pending.extend(item)
|
|
119
|
+
elif isinstance(item, int):
|
|
120
|
+
budget -= max(5, item.bit_length() // 3 + 2)
|
|
121
|
+
elif item is None or isinstance(item, float):
|
|
122
|
+
budget -= 32
|
|
123
|
+
else:
|
|
124
|
+
return False
|
|
125
|
+
if budget < 0:
|
|
126
|
+
return False
|
|
127
|
+
return True
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def canonical_chunks(value: Any, *, chunk_bytes: int = CHUNK_BYTES) -> Iterator[bytes]:
|
|
131
|
+
"""Emit exactly json.dumps(sort_keys=True, ensure_ascii=False, compact)+LF."""
|
|
132
|
+
if type(chunk_bytes) is not int or chunk_bytes < 64:
|
|
133
|
+
raise ValueError("chunk_bytes must be at least 64")
|
|
134
|
+
encoder = json.JSONEncoder(sort_keys=True, ensure_ascii=False, separators=(",", ":"), allow_nan=False)
|
|
135
|
+
active: set[int] = set()
|
|
136
|
+
|
|
137
|
+
def emit(item, depth=0):
|
|
138
|
+
if depth > 256:
|
|
139
|
+
raise ValueError("JSON nesting exceeds the streaming bound")
|
|
140
|
+
if _fits(item, chunk_bytes):
|
|
141
|
+
raw = encoder.encode(item).encode("utf-8")
|
|
142
|
+
for offset in range(0, len(raw), chunk_bytes):
|
|
143
|
+
yield raw[offset:offset + chunk_bytes]
|
|
144
|
+
return
|
|
145
|
+
if isinstance(item, str):
|
|
146
|
+
yield b'"'
|
|
147
|
+
# Six escaped bytes per code point is the largest JSON expansion.
|
|
148
|
+
width = max(1, (chunk_bytes - 2) // 6)
|
|
149
|
+
for offset in range(0, len(item), width):
|
|
150
|
+
yield encoder.encode(item[offset:offset + width])[1:-1].encode("utf-8")
|
|
151
|
+
yield b'"'
|
|
152
|
+
return
|
|
153
|
+
if not isinstance(item, (Mapping, list, tuple, CanonicalArray)):
|
|
154
|
+
raw = encoder.encode(item).encode("utf-8")
|
|
155
|
+
for offset in range(0, len(raw), chunk_bytes):
|
|
156
|
+
yield raw[offset:offset + chunk_bytes]
|
|
157
|
+
return
|
|
158
|
+
identity = id(item)
|
|
159
|
+
if identity in active:
|
|
160
|
+
raise ValueError("circular JSON value")
|
|
161
|
+
active.add(identity)
|
|
162
|
+
try:
|
|
163
|
+
if isinstance(item, Mapping):
|
|
164
|
+
if any(not isinstance(key, str) for key in item):
|
|
165
|
+
raise TypeError("JSON object keys must be strings")
|
|
166
|
+
yield b"{"
|
|
167
|
+
for index, key in enumerate(sorted(item)):
|
|
168
|
+
if index:
|
|
169
|
+
yield b","
|
|
170
|
+
yield from emit(key, depth + 1)
|
|
171
|
+
yield b":"
|
|
172
|
+
yield from emit(item[key], depth + 1)
|
|
173
|
+
yield b"}"
|
|
174
|
+
else:
|
|
175
|
+
yield b"["
|
|
176
|
+
for index, child in enumerate(item):
|
|
177
|
+
if index:
|
|
178
|
+
yield b","
|
|
179
|
+
yield from emit(child, depth + 1)
|
|
180
|
+
yield b"]"
|
|
181
|
+
finally:
|
|
182
|
+
active.remove(identity)
|
|
183
|
+
|
|
184
|
+
buffer = bytearray()
|
|
185
|
+
for part in emit(value):
|
|
186
|
+
offset = 0
|
|
187
|
+
while offset < len(part):
|
|
188
|
+
take = min(chunk_bytes - len(buffer), len(part) - offset)
|
|
189
|
+
buffer.extend(part[offset:offset + take])
|
|
190
|
+
offset += take
|
|
191
|
+
if len(buffer) == chunk_bytes:
|
|
192
|
+
yield bytes(buffer)
|
|
193
|
+
buffer.clear()
|
|
194
|
+
buffer.extend(b"\n")
|
|
195
|
+
yield bytes(buffer)
|