knowledgenet 1.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.
Files changed (31) hide show
  1. knowledgenet-1.0.0/LICENSE +201 -0
  2. knowledgenet-1.0.0/PKG-INFO +13 -0
  3. knowledgenet-1.0.0/pyproject.toml +45 -0
  4. knowledgenet-1.0.0/readme.md +16 -0
  5. knowledgenet-1.0.0/setup.cfg +4 -0
  6. knowledgenet-1.0.0/src/api/conf.py +24 -0
  7. knowledgenet-1.0.0/src/knowledgenet/__init__.py +11 -0
  8. knowledgenet-1.0.0/src/knowledgenet/container.py +158 -0
  9. knowledgenet-1.0.0/src/knowledgenet/controls.py +65 -0
  10. knowledgenet-1.0.0/src/knowledgenet/core/__init__.py +0 -0
  11. knowledgenet-1.0.0/src/knowledgenet/core/file_trace_exporter.py +90 -0
  12. knowledgenet-1.0.0/src/knowledgenet/core/graph.py +189 -0
  13. knowledgenet-1.0.0/src/knowledgenet/core/perm.py +19 -0
  14. knowledgenet-1.0.0/src/knowledgenet/core/session.py +179 -0
  15. knowledgenet-1.0.0/src/knowledgenet/core/tracer.py +101 -0
  16. knowledgenet-1.0.0/src/knowledgenet/decorator.py +69 -0
  17. knowledgenet-1.0.0/src/knowledgenet/factset.py +235 -0
  18. knowledgenet-1.0.0/src/knowledgenet/ftypes.py +114 -0
  19. knowledgenet-1.0.0/src/knowledgenet/helper.py +37 -0
  20. knowledgenet-1.0.0/src/knowledgenet/node.py +143 -0
  21. knowledgenet-1.0.0/src/knowledgenet/repository.py +20 -0
  22. knowledgenet-1.0.0/src/knowledgenet/rule.py +158 -0
  23. knowledgenet-1.0.0/src/knowledgenet/ruleset.py +34 -0
  24. knowledgenet-1.0.0/src/knowledgenet/scanner.py +135 -0
  25. knowledgenet-1.0.0/src/knowledgenet/service.py +90 -0
  26. knowledgenet-1.0.0/src/knowledgenet/util.py +58 -0
  27. knowledgenet-1.0.0/src/knowledgenet.egg-info/PKG-INFO +13 -0
  28. knowledgenet-1.0.0/src/knowledgenet.egg-info/SOURCES.txt +29 -0
  29. knowledgenet-1.0.0/src/knowledgenet.egg-info/dependency_links.txt +1 -0
  30. knowledgenet-1.0.0/src/knowledgenet.egg-info/requires.txt +3 -0
  31. knowledgenet-1.0.0/src/knowledgenet.egg-info/top_level.txt +2 -0
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,13 @@
1
+ Metadata-Version: 2.4
2
+ Name: knowledgenet
3
+ Version: 1.0.0
4
+ Author: Amit Chatterjee
5
+ Project-URL: Homepage, https://github.com/amitchatterjee/knowledgenet
6
+ Project-URL: Issues, https://github.com/amitchatterjee/knowledgenet
7
+ Project-URL: Repository, https://github.com/amitchatterjee/knowledgenet.git
8
+ Project-URL: Documentation, https://github.com/amitchatterjee/knowledgenet/tree/develop/docs
9
+ License-File: LICENSE
10
+ Requires-Dist: opentelemetry-api>=1.39.1
11
+ Requires-Dist: opentelemetry-sdk>=1.39.1
12
+ Requires-Dist: opentelemetry-exporter-otlp>=1.39.1
13
+ Dynamic: license-file
@@ -0,0 +1,45 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "knowledgenet"
7
+ version = "1.0.0"
8
+ authors = [
9
+ { name="Amit Chatterjee"},
10
+ ]
11
+
12
+ dependencies = [
13
+ "opentelemetry-api >= 1.39.1",
14
+ "opentelemetry-sdk >= 1.39.1",
15
+ "opentelemetry-exporter-otlp >= 1.39.1"
16
+ ]
17
+
18
+ [dependency-groups]
19
+ dev = ["pytest", "pytest-cov", "build", "debugpy", "twine", "pip-tools", "sphinx", "sphinx-markdown-builder"]
20
+
21
+ description = "Knowledgenet RETE engine"
22
+ requires-python = ">=3.13"
23
+ classifiers = [
24
+ "Programming Language :: Python :: 3",
25
+ "Operating System :: OS Independent",
26
+ "Development Status :: 5 - Production/Stable",
27
+ "Intended Audience :: Developers",
28
+ ]
29
+ keywords = [
30
+ "RETE",
31
+ "rules engine",
32
+ "knowledgebase",
33
+ "inference engine",
34
+ "expert systems",
35
+ "rule.based system",
36
+ "forward chaining",
37
+ "backward chaining",
38
+ ]
39
+ license = "Apache-2.0"
40
+ readme = "readme.md"
41
+ [project.urls]
42
+ Homepage = "https://github.com/amitchatterjee/knowledgenet"
43
+ Issues = "https://github.com/amitchatterjee/knowledgenet"
44
+ Repository = "https://github.com/amitchatterjee/knowledgenet.git"
45
+ Documentation = "https://github.com/amitchatterjee/knowledgenet/tree/develop/docs"
@@ -0,0 +1,16 @@
1
+ # Knowledgenet
2
+ Knowledgenet is a Python Language software library that enables application developers to build applications that make complex decisions based on **facts** supplied to the service entrypoint and **rules** developed by **application developers** and **business users**. Knowledgenet is an implementation of an **Inference Engine** using an adaptation of the Rete algorithm designed by **Charles L. Forgy** of Carnegie Melon University. Rete is an efficient pattern matching algorithm that is widely used in many AI systems including Expert Systems.
3
+
4
+ Please refer to the product documentation in [docs/index.md](docs/index.md) and in the [Knowledgenet Repository](https://github.com/amitchatterjee/knowledgenet/tree/develop/docs).
5
+
6
+ ## Setup
7
+
8
+ ### Install Python 3.14
9
+ - Recommended: download the Windows installer from `https://www.python.org/downloads/release/python-3140/` and run it. During installation:
10
+ - check "Add Python to PATH"
11
+
12
+ ### Create and activate a virtual environment
13
+ ```bash
14
+ python -m venv ~/venvs/knowledgenet
15
+ source ~/venvs/knowledgenet/bin/activate
16
+ ```
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,24 @@
1
+ import os
2
+ import sys
3
+
4
+ sys.path.insert(0, os.path.abspath(".."))
5
+
6
+ project = "Knowledgenet API"
7
+ author = "Knowledgenet Contributors"
8
+
9
+ extensions = [
10
+ "sphinx.ext.autodoc",
11
+ "sphinx.ext.napoleon",
12
+ ]
13
+
14
+ templates_path = []
15
+ exclude_patterns = ["_build", "Thumbs.db", ".DS_Store"]
16
+
17
+ autodoc_default_options = {
18
+ "members": True,
19
+ "undoc-members": True,
20
+ "show-inheritance": True,
21
+ }
22
+
23
+ html_theme = "alabaster"
24
+ html_static_path = []
@@ -0,0 +1,11 @@
1
+ """Public package entrypoint for the Knowledgenet rules engine.
2
+
3
+ This package exposes the rule authoring DSL, scanner utilities, and service
4
+ runtime used to execute repositories of rulesets against transaction facts.
5
+
6
+ Typical transaction lifecycle:
7
+ 1. Build or scan a Repository of Rulesets and Rules.
8
+ 2. Initialize Service(repository).
9
+ 3. Execute many transactions with ``service.execute(input_facts)``.
10
+ 4. Consume returned fact set containing original and derived facts.
11
+ """
@@ -0,0 +1,158 @@
1
+ """Collection primitives used to aggregate facts during session execution."""
2
+
3
+ from typing import Callable
4
+ from numbers import Number
5
+ import inspect
6
+ import hashlib
7
+ import statistics
8
+
9
+ from knowledgenet.util import of_type, to_tuple
10
+ from knowledgenet.core.tracer import trace
11
+
12
+ class Collector:
13
+ """Accumulates facts of one type and exposes aggregate operations.
14
+
15
+ Collector is itself a fact and can participate in rule matching through
16
+ ``Collection(...)`` or ``Fact(of_type=Collector, group=...)``.
17
+
18
+ Example:
19
+ Aggregate C1 facts and expose sum/size to rules::
20
+
21
+ Collector(
22
+ of_type=C1,
23
+ group='sum_of_c1s',
24
+ value=lambda obj: obj.val,
25
+ )
26
+ """
27
+
28
+ def __init__(self, group: str,
29
+ of_type: type | str,
30
+ filter: list[Callable] | tuple[Callable] | Callable | str = lambda this,child: True,
31
+ value: Callable | None = None, key: Callable | None = None,
32
+ **kwargs):
33
+ from knowledgenet.ftypes import EventFact
34
+ if of_type in (Collector, EventFact):
35
+ raise Exception('Nested Collector and Eventfact types are not supported')
36
+ self.of_type = of_type
37
+ self.group = group
38
+ self.filter = to_tuple(filter)
39
+ self.value = value
40
+ self.key = key
41
+ self.init_args = kwargs
42
+ for key,value in kwargs.items(): # type: ignore
43
+ setattr(self, key, value) # type: ignore
44
+
45
+ self.collection = set()
46
+ self._cached_sum = None
47
+ self._cached_variance = None
48
+ self._cached_min = None
49
+ self._cached_max = None
50
+
51
+ hasher = hashlib.sha256(group.encode())
52
+ for key,value in sorted(kwargs.items()): # type: ignore
53
+ hasher.update(str(key).encode())
54
+ hasher.update(str(value).encode())
55
+ self.__int_hash = int(hasher.hexdigest(), 16)
56
+
57
+ def __str__(self):
58
+ return f"Collector({self.group}, args={self.init_args})"
59
+
60
+ def __repr__(self):
61
+ return self.__str__()
62
+
63
+ def __hash__(self):
64
+ return self.__int_hash
65
+
66
+ def __eq__(self, other):
67
+ if not isinstance(other, Collector):
68
+ return False
69
+ return self.__hash__() == other.__hash__()
70
+
71
+ def size(self) -> int:
72
+ """Return the number of currently collected facts."""
73
+ return len(self.collection)
74
+
75
+ def empty(self) -> bool:
76
+ """Return True when the collector has no facts."""
77
+ return len(self.collection) == 0
78
+
79
+ def reset_cache(self):
80
+ """Clear cached aggregate values after collection changes."""
81
+ self._cached_sum = None
82
+ self._cached_variance = None
83
+ self._cached_min = None
84
+ self._cached_max = None
85
+
86
+ def _filter_obj(self, obj):
87
+ for each_filter in self.filter:
88
+ if not each_filter(self, obj):
89
+ return False
90
+ return True
91
+
92
+ @trace(level=14)
93
+ def add(self, obj: object) -> bool:
94
+ """Attempt to add one fact to the collection.
95
+
96
+ Returns True only when type checks, filter checks, and deduplication all
97
+ pass and the collection actually changes.
98
+ """
99
+ if of_type(obj) != self.of_type:
100
+ return False
101
+ if obj in self.collection:
102
+ return False
103
+ if not self._filter_obj(obj):
104
+ return False
105
+
106
+ self.collection.add(obj)
107
+ self.reset_cache()
108
+ return True
109
+
110
+ @trace(level=14)
111
+ def remove(self, obj: object) -> bool:
112
+ """Attempt to remove one fact from the collection.
113
+
114
+ Returns True only when the fact is currently present and passes the same
115
+ filter constraints used for insertion.
116
+ """
117
+ if of_type(obj) != self.of_type:
118
+ return False
119
+ if obj not in self.collection:
120
+ return False
121
+ if not self._filter_obj(obj):
122
+ return False
123
+
124
+ self.collection.remove(obj)
125
+ self.reset_cache()
126
+ return True
127
+
128
+ def sum(self) -> Number:
129
+ """Return sum of collected values using configured ``value`` accessor."""
130
+ if self._cached_sum is None:
131
+ if not self.value:
132
+ raise Exception("Don't know how to compute sum as value function is not defined")
133
+ self._cached_sum = sum([self.value(each) for each in self.collection])
134
+ return self._cached_sum
135
+
136
+ def variance(self) -> float:
137
+ """Return variance of collected values using configured ``value`` accessor."""
138
+ if self._cached_variance is None:
139
+ if not self.value:
140
+ raise Exception("Don't know how to compute variance as value function is not defined")
141
+ self._cached_variance = statistics.variance([self.value(each) for each in self.collection]) if len(self.collection) >= 2 else 0.0
142
+ return self._cached_variance
143
+
144
+ def minimum(self) -> object:
145
+ """Return minimum collected fact according to configured ``key`` accessor."""
146
+ if self._cached_min is None:
147
+ if not self.key:
148
+ raise Exception("Don't know how to compute min as key function is not defined")
149
+ self._cached_min = min(self.collection, key=self.key)
150
+ return self._cached_min
151
+
152
+ def maximum(self) -> object:
153
+ """Return maximum collected fact according to configured ``key`` accessor."""
154
+ if self._cached_max is None:
155
+ if not self.key:
156
+ raise Exception("Don't know how to compute max as key function is not defined")
157
+ self._cached_max = max(self.collection, key=self.key)
158
+ return self._cached_max
@@ -0,0 +1,65 @@
1
+ """Rule action helpers used from then clauses.
2
+
3
+ These helpers do not mutate Factset directly. Instead they record requested
4
+ changes in ``ctx._changes`` so Session can apply merges in a deterministic
5
+ order after node execution.
6
+ """
7
+
8
+ from knowledgenet.core.tracer import trace
9
+ from knowledgenet.ftypes import Switch
10
+
11
+ def _add_key(ctx, key, fact):
12
+ if key not in ctx._changes:
13
+ ctx._changes[key] = []
14
+ ctx._changes[key].append(fact)
15
+
16
+ @trace(level=3)
17
+ def insert(ctx, fact):
18
+ """Request insertion of fact(s) after current node completes."""
19
+ _add_key(ctx, 'insert', fact)
20
+
21
+ @trace(level=3)
22
+ def update(ctx, fact):
23
+ """Request update propagation for fact(s) modified in place.
24
+
25
+ Example:
26
+ After mutating an existing fact, call update so dependent rules can be
27
+ re-evaluated::
28
+
29
+ ctx.item.val = 0
30
+ update(ctx, ctx.item)
31
+ """
32
+ _add_key(ctx, 'update', fact)
33
+
34
+ @trace(level=3)
35
+ def delete(ctx, fact):
36
+ """Request deletion of fact(s) after current node completes."""
37
+ _add_key(ctx, 'delete', fact)
38
+
39
+ @trace(level=3)
40
+ def next_ruleset(ctx):
41
+ """Stop the current ruleset session and continue with next repository ruleset."""
42
+ ctx._changes['break'] = True
43
+
44
+ @trace(level=3)
45
+ def switch(ctx, ruleset):
46
+ """Stop current session and request jump to a specific ruleset id.
47
+
48
+ Example:
49
+ Jump from current ruleset to ``rs3``::
50
+
51
+ switch(ctx, 'rs3')
52
+ """
53
+ ctx._changes['switch'] = Switch(ruleset)
54
+
55
+ @trace(level=3)
56
+ def end(ctx):
57
+ """Stop all remaining ruleset execution for this transaction.
58
+
59
+ Example:
60
+ End processing when validation fails::
61
+
62
+ if not ctx.validation.ok:
63
+ end(ctx)
64
+ """
65
+ switch(ctx, None)
File without changes
@@ -0,0 +1,90 @@
1
+ import json
2
+ import threading
3
+ from typing import Sequence
4
+
5
+ from opentelemetry.sdk.trace.export import SpanExporter, SpanExportResult
6
+
7
+ class FileSpanExporter(SpanExporter):
8
+ """A simple OpenTelemetry span exporter that writes spans to a file as JSON lines.
9
+
10
+ This exporter performs a best-effort conversion of span objects to JSON-serializable
11
+ dictionaries and appends them to the configured file. It is intended for local
12
+ debugging or CI use where an OTLP backend is not available.
13
+ """
14
+ def __init__(self, file_path: str = "trace.ndjson"):
15
+ self._file_path = file_path
16
+ self._lock = threading.Lock()
17
+
18
+ def export(self, spans: Sequence[object]) -> "SpanExportResult":
19
+ records = []
20
+ for span in spans:
21
+ try:
22
+ rec = self._span_to_dict(span)
23
+ except Exception:
24
+ # fallback to a minimal representation
25
+ rec = {"name": getattr(span, "name", str(span)), "error": "serialization_failed"}
26
+ records.append(rec)
27
+
28
+ # append JSON lines
29
+ try:
30
+ with self._lock:
31
+ with open(self._file_path, "a", encoding="utf-8") as fh:
32
+ for r in records:
33
+ fh.write(json.dumps(r, default=str))
34
+ fh.write("\n")
35
+ return SpanExportResult.SUCCESS
36
+ except Exception:
37
+ return SpanExportResult.FAILURE if hasattr(SpanExportResult, 'FAILURE') else SpanExportResult.SUCCESS
38
+
39
+ def shutdown(self) -> None:
40
+ # nothing to clean up for file exporter
41
+ return None
42
+
43
+ def _span_to_dict(self, span: object) -> dict:
44
+ # span is typically an opentelemetry.sdk.trace._Span
45
+ d = {
46
+ "name": getattr(span, "name", None),
47
+ "context": {
48
+ "span_id": getattr(getattr(span, "context", None), "span_id", None),
49
+ "trace_id": getattr(getattr(span, "context", None), "trace_id", None),
50
+ },
51
+ "parent_span_id": getattr(getattr(span, "parent", None), "span_id", None) or getattr(span, "parent_span_id", None),
52
+ "start_time": getattr(span, "start_time", None),
53
+ "end_time": getattr(span, "end_time", None),
54
+ "attributes": {},
55
+ "events": [],
56
+ "status": None,
57
+ }
58
+
59
+ # attributes
60
+ attrs = getattr(span, "attributes", None)
61
+ if attrs:
62
+ try:
63
+ for k, v in attrs.items():
64
+ d["attributes"][k] = v
65
+ except Exception:
66
+ d["attributes"] = {str(k): str(v) for k, v in attrs.items()}
67
+
68
+ # events
69
+ events = getattr(span, "events", None)
70
+ if events:
71
+ try:
72
+ for ev in events:
73
+ evdict = {
74
+ "name": getattr(ev, "name", None),
75
+ "attributes": getattr(ev, "attributes", None),
76
+ "timestamp": getattr(ev, "timestamp", None),
77
+ }
78
+ d["events"].append(evdict)
79
+ except Exception:
80
+ pass
81
+
82
+ # status
83
+ st = getattr(span, "status", None)
84
+ if st is not None:
85
+ try:
86
+ d["status"] = {"status_code": getattr(st, "status_code", None), "description": getattr(st, "description", None)}
87
+ except Exception:
88
+ d["status"] = str(st)
89
+
90
+ return d