mercury-composable 4.12.1__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 (37) hide show
  1. mercury_composable-4.12.1/.gitignore +48 -0
  2. mercury_composable-4.12.1/CHANGELOG.md +142 -0
  3. mercury_composable-4.12.1/LICENSE.txt +202 -0
  4. mercury_composable-4.12.1/PKG-INFO +265 -0
  5. mercury_composable-4.12.1/README.md +227 -0
  6. mercury_composable-4.12.1/examples/demo_app.py +457 -0
  7. mercury_composable-4.12.1/examples/resources/application.yml +22 -0
  8. mercury_composable-4.12.1/pyproject.toml +86 -0
  9. mercury_composable-4.12.1/src/mercury_composable/__init__.py +48 -0
  10. mercury_composable-4.12.1/src/mercury_composable/actuator.py +282 -0
  11. mercury_composable-4.12.1/src/mercury_composable/bus.py +387 -0
  12. mercury_composable-4.12.1/src/mercury_composable/cli.py +69 -0
  13. mercury_composable-4.12.1/src/mercury_composable/client.py +501 -0
  14. mercury_composable-4.12.1/src/mercury_composable/config.py +188 -0
  15. mercury_composable-4.12.1/src/mercury_composable/default-log-context.yaml +19 -0
  16. mercury_composable-4.12.1/src/mercury_composable/envelope.py +214 -0
  17. mercury_composable-4.12.1/src/mercury_composable/event_stream.py +340 -0
  18. mercury_composable-4.12.1/src/mercury_composable/exceptions.py +29 -0
  19. mercury_composable-4.12.1/src/mercury_composable/log.py +113 -0
  20. mercury_composable-4.12.1/src/mercury_composable/log_context.py +172 -0
  21. mercury_composable-4.12.1/src/mercury_composable/py.typed +0 -0
  22. mercury_composable-4.12.1/src/mercury_composable/registry.py +145 -0
  23. mercury_composable-4.12.1/src/mercury_composable/server.py +293 -0
  24. mercury_composable-4.12.1/src/mercury_composable/trace.py +126 -0
  25. mercury_composable-4.12.1/src/mercury_composable/version.py +3 -0
  26. mercury_composable-4.12.1/tests/test_actuator.py +234 -0
  27. mercury_composable-4.12.1/tests/test_bus.py +229 -0
  28. mercury_composable-4.12.1/tests/test_client.py +69 -0
  29. mercury_composable-4.12.1/tests/test_config.py +60 -0
  30. mercury_composable-4.12.1/tests/test_envelope.py +118 -0
  31. mercury_composable-4.12.1/tests/test_event_stream.py +484 -0
  32. mercury_composable-4.12.1/tests/test_llm_chat.py +252 -0
  33. mercury_composable-4.12.1/tests/test_llm_stream.py +234 -0
  34. mercury_composable-4.12.1/tests/test_log.py +47 -0
  35. mercury_composable-4.12.1/tests/test_log_context.py +106 -0
  36. mercury_composable-4.12.1/tests/test_server.py +198 -0
  37. mercury_composable-4.12.1/tests/vectors/vectors.json +133 -0
@@ -0,0 +1,48 @@
1
+ __pycache__/
2
+ *.pyc
3
+ .venv/
4
+ venv/
5
+ dist/
6
+ build/
7
+ *.egg-info/
8
+ .pytest_cache/
9
+ .mypy_cache/
10
+ .ruff_cache/
11
+ uv.lock
12
+ .idea/
13
+ .DS_Store
14
+
15
+ # === agent-memory: AI infrastructure (personal / per-machine — do not commit) ===
16
+ # Steering files (CLAUDE.md, GEMINI.md, AGENTS.md, .cursorrules, .windsurfrules,
17
+ # .github/copilot-instructions.md), the shared memory layer (memory/, .agent/,
18
+ # legacy/), and the shared skills layer (agent-skills/) are intentionally TRACKED — they
19
+ # are committed and shared across the team, so do NOT ignore them. Only personal
20
+ # AI-IDE runtime directories and local history/caches are ignored below (the
21
+ # "infrastructure", not the steering). The vendor dirs below also hold per-machine
22
+ # skill *adapters* (.claude/skills/, .gemini/commands/, .cursor/rules/, .kiro/skills/,
23
+ # .github/skills/, .agents/skills/) regenerated from agent-skills/ — local only; the neutral
24
+ # agent-skills/ is the shared source of truth. NOTE: GitHub Copilot's skill adapter lives at
25
+ # .github/skills/, so it is ignored path-scoped (below) — never ignore all of .github/, which holds
26
+ # the tracked copilot-instructions.md and workflows/. .agents/skills/ is the Agent Skills standard dir
27
+ # read by Google Antigravity (agy, the Gemini CLI successor — it ignores .gemini/commands).
28
+ .kiro/
29
+ .claude/
30
+ .cursor/
31
+ .continue/
32
+ .windsurf/
33
+ .codeium/
34
+ .gemini/
35
+ .github/skills/
36
+ .agents/
37
+ .cline/
38
+ .roo/
39
+ .zed/
40
+ .codex/
41
+ .aider.chat.history.md
42
+ .aider.input.history
43
+ .aider.tags.cache*
44
+ review-scratch/
45
+ *.py[cod]
46
+
47
+ # mkdocs build output
48
+ site/
@@ -0,0 +1,142 @@
1
+ # Changelog
2
+
3
+ ## Version 4.12.1, 9/1/2026
4
+
5
+ The first PyPI release: `pip install mercury-composable`. The v4.12.0 lock-step line
6
+ plus the AI-node demo functions below.
7
+
8
+ ### Added
9
+
10
+ - `llm.chat` demo function (examples/demo_app.py) - the AI node of the agent-orchestration
11
+ experiment E0: a provider-neutral LLM adapter (Anthropic and Gemini backends behind one
12
+ contract; select with `llm.provider` config / `-Dllm.provider=...` / `params.provider`)
13
+ with structured output (`schema` -> JSON verdicts for graph decision routing;
14
+ additionalProperties defaults closed), usage/stop_reason surfacing, provider-error
15
+ mapping onto the envelope status, and the params.timeout_ms time-budget mapping.
16
+ The SDKs are an optional extra (`pip install "mercury-composable[llm]"`); the package
17
+ itself stays SDK-free (scope fence intact).
18
+ - `llm.stream` demo function - the STREAMING AI node: pulls the provider's real token
19
+ stream (Anthropic `messages.stream` or Gemini `generate_content_stream`) and relays
20
+ each token batch over the multi-shot reply contract, so a calling engine renders it
21
+ progressively out its own HTTP edge as SSE. Terminal metadata carries model,
22
+ stop_reason, usage and the trace/business correlation ids; provider errors fail the
23
+ stream in-band. Live-proven end to end with real Gemini tokens (2026-08-31).
24
+ - PyPI publication metadata: SPDX license expression (PEP 639), trove classifiers,
25
+ keywords, project URLs, and a constrained sdist (package sources, tests, examples
26
+ and top-level docs only - repo-internal layers never ship).
27
+
28
+ ## 4.12.0 (2026-08-30)
29
+
30
+ The progressive-rendering milestone release. The version aligns with the Mercury
31
+ Composable engine lock-step line (Java and Rust engines, Python and Node.js
32
+ language packs all at v4.12.0): token/event streaming end to end with full
33
+ OpenTelemetry lineage, business-correlation continuity and application log
34
+ context across all four runtimes - useful on its own, and the foundation for
35
+ the AI SDLC (agent, MCP and tool adapters as wrapper-side functions with
36
+ complete observability).
37
+
38
+ - **Event streaming** - the platform-wide multi-shot reply contract, both halves.
39
+ Producer: `@preload(..., interceptor=True)` handlers receive the raw envelope
40
+ and stream through `EventStreamWriter` (the engines' exact API - `first`,
41
+ `write`, `write_named`, `close` with trailing metadata, `fail` with the standard
42
+ error key-values); the `/api/event` host answers a caller that accepts
43
+ `text/event-stream` with the platform's hybrid SSE dialect (envelope frames for
44
+ the head, the terminals and non-text segments; raw frames for text tokens),
45
+ refuses a non-accepting caller of a streaming function with the pinned 406, and
46
+ keeps single-shot replies over the capable path byte-identical. Consumer:
47
+ `PostOffice.stream()` (an async iterator yielding the same decoded envelopes an
48
+ engine reply route receives, with the dialect conformance guards) and
49
+ `PostOffice.stream_to()` (the relay form: forward your caller's reply address
50
+ and segments flow through verbatim - engine-parity composition). Under it all,
51
+ the primitive event bus gained the engines' reply_to mechanism: envelope-routed
52
+ delivery to a LOCAL function or per-request reply sink - simple routing, no
53
+ orchestration. Same keep-alive config key as the engines
54
+ (`event.stream.keep.alive`). Engine-identical wire and messages
55
+ (Java PR #299-#301 / Rust PR #216-#218 lineage).
56
+ - **Business correlation-id continuity** (the engines' PostOffice parity): the
57
+ client stamps the current context's business correlation-id onto outbound
58
+ events as the engine-managed `my_cid` tag, local bus deliveries inject the
59
+ read-only `my_correlation_id` header view exactly like the HTTP host, and
60
+ `get_trace()` / `trace_context()` carry `my_correlation_id` - so the business
61
+ correlation-id continues across engine⇄wrapper and wrapper⇄wrapper hops.
62
+ - **Span lineage** (the engines' telemetry model): every traced execution mints
63
+ a 16-hex span with the caller's span (from the inbound envelope) as its
64
+ parent, outbound events carry the current span so the next hop parents onto
65
+ it (`PostOffice.touch` parity, W3C `traceparent` included), streaming
66
+ segments carry the producer's span, and non-RPC executions emit the engines'
67
+ distributed-trace dataset record on the `distributed.tracing` log stream -
68
+ the same `{"trace": {...}, "annotations": {...}}` shape the Java engine
69
+ logs, so stdout log-ingest agents stitch spans across all four runtimes.
70
+ RPC round-trips are suppressed exactly like the engines (the new `rpc`
71
+ envelope tag rides `request()` calls). `trace_context()` accepts `span_id`
72
+ to parent onto an external OpenTelemetry span. Outbound events and stream
73
+ segments also fill their sender with the executing function's route, and
74
+ the `/api/event` host fills `event.api.service` for an anonymous caller -
75
+ the engines' sender-attribution rules.
76
+ - **Application log context** (the engines' app-log-context feature, on by
77
+ default via the packaged `default-log-context.yaml` - the engines' resource
78
+ twin): with `log.format` json/compact, every log line inside a traced
79
+ request carries a `context` block - cid (the business correlation-id),
80
+ traceId, tracePath, spanId, parentSpanId, service, timestamp - so app logs
81
+ and the distributed-trace records correlate end to end. Customize with
82
+ `resources/app-log-context.yaml` (reserved `$tokens` or constants with
83
+ `${ENV:default}`), opt out with `app.log.context=false`, and add
84
+ per-request key-values with `update_context()` (reserved keys guarded).
85
+ - Documentation site (mkdocs-material, the engine repo's theme): the three-layer theme
86
+ reference, rationale/design foundations, function-writing patterns, flow and
87
+ knowledge-graph join chapters, a one-page AI agent guide with llms.txt, and
88
+ configuration/HTTP references - published to
89
+ https://accenture.github.io/mercury-python/ by the new CI workflow, which also runs
90
+ the three quality gates (pytest, ruff, basedpyright) on every push and pull request.
91
+ - Host polish for engine parity: `GET /` serves the engines' minimal index page linking
92
+ the actuator endpoints (embedded - no static file service by design); actuator JSON
93
+ responses are pretty-printed (the engines' default-serializer presentation); unknown
94
+ paths and non-GET methods answer the engines' error shape
95
+ `{"status": 404, "message": "Resource not found", "type": "error"}`.
96
+ - Sync bridge: `PostOffice.request_sync()` / `send_sync()` let a plain `def` handler
97
+ (the synchronous ecosystem - `requests`, NumPy/ML inference, database drivers) call
98
+ sibling or remote functions - the call runs on the host event loop while only the
99
+ handler's worker thread blocks; the trace chain rides across unbroken. Calling the
100
+ bridge from async code, or outside a hosted function, is refused with a teaching
101
+ error. The sync-vs-async handler rationale is now documented (README and the
102
+ registry module).
103
+ - Actuator endpoints `/info`, `/info/routes`, `/env`, `/health` and `/livenessprobe` -
104
+ the engines' operational surface, for Kubernetes probes and one-dashboard monitoring
105
+ of polyglot installations. Health check functions are normal registered functions
106
+ speaking the engines' `type=info` / `type=health` interface contract, listed in
107
+ `mandatory.health.dependencies` / `optional.health.dependencies` and called through
108
+ the event bus. `/health` answers `UP` (200) / `DOWN` (400); `/livenessprobe` follows
109
+ the most recent health outcome.
110
+ - `log.format` carries the engines' three presentations: `text` (default), `json`
111
+ (pretty-printed) and `compact` (single-line JSONL for log aggregators). A sample
112
+ `examples/resources/application.yml` demonstrates the resources convention and the
113
+ well-known keys.
114
+ - Primitive in-process event bus - the single dispatch pipeline: one FIFO mailbox per
115
+ route consumed by `instances` worker tasks (the parameter is faithful); RPC deliveries
116
+ are ttl-bounded with a dead-work skip; drop-n-forget returns the 202-shape ack. The
117
+ HTTP host and the local side of PostOffice are thin ingress adapters over it. No spill
118
+ tier and no queue cap by design - back-pressure belongs to the engines' flows/graphs;
119
+ a leaf host fails fast by deadline.
120
+ - PostOffice without an endpoint delivers locally (engine semantics): private routes are
121
+ callable in-app while the wire keeps its 403; headers pass verbatim; the reply envelope
122
+ shape is identical to the remote path.
123
+
124
+ Repository repurposed for the Mercury Composable **polyglot initiative** (August 2026).
125
+
126
+ - Lightweight Event-over-HTTP function host (`POST /api/event`) mirroring the engines'
127
+ EventApiService semantics (x-ttl execution bound, x-async drop-n-forget with 202 ack,
128
+ reserved header hygiene, `my_cid` → `my_correlation_id` injection, portable error
129
+ contract, engine-identical error messages).
130
+ - Standard event envelope wire format codec, verified against the golden conformance
131
+ vectors shared with the Java and Rust engines; compact format detected and rejected.
132
+ - `@preload` function registry with instance-count concurrency limits and private routes.
133
+ - `PostOffice` thin client with the engines' relay HTTP contract (octet-stream, x-ttl,
134
+ x-no-stream, trace headers) for calling engine or peer polyglot functions.
135
+ - Minimalist utilities in engine-consistent style: `AppConfig` (`${ENV:default}`
136
+ substitution, runtime overrides), logging in the reference log4j2 presentation
137
+ (`log.format=text|json`, `LOG_LEVEL`), and distributed-trace context with reply
138
+ annotations.
139
+ - `mercury-serve` developer runner.
140
+
141
+ The legacy Mercury language-pack implementation (pre-composable, websocket-based) remains
142
+ available in the git history prior to this version.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2018-2026 Accenture.
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,265 @@
1
+ Metadata-Version: 2.5
2
+ Name: mercury-composable
3
+ Version: 4.12.1
4
+ Summary: Lightweight Event-over-HTTP function host and client for Mercury Composable
5
+ Project-URL: Homepage, https://github.com/Accenture/mercury-python
6
+ Project-URL: Documentation, https://accenture.github.io/mercury-python
7
+ Project-URL: Repository, https://github.com/Accenture/mercury-python
8
+ Project-URL: Changelog, https://github.com/Accenture/mercury-python/blob/main/CHANGELOG.md
9
+ Author: Accenture Technology
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE.txt
12
+ Keywords: composable,event-driven,event-over-http,mercury,microservices
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Framework :: AsyncIO
15
+ Classifier: Intended Audience :: Developers
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Classifier: Topic :: Software Development :: Libraries
24
+ Requires-Python: >=3.10
25
+ Requires-Dist: aiohttp<4,>=3.10
26
+ Requires-Dist: msgpack<2,>=1.0
27
+ Requires-Dist: pyyaml<7,>=6.0
28
+ Provides-Extra: dev
29
+ Requires-Dist: anthropic<2,>=1; extra == 'dev'
30
+ Requires-Dist: google-genai<3,>=2; extra == 'dev'
31
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
32
+ Requires-Dist: pytest>=8; extra == 'dev'
33
+ Requires-Dist: ruff>=0.9; extra == 'dev'
34
+ Provides-Extra: llm
35
+ Requires-Dist: anthropic<2,>=1; extra == 'llm'
36
+ Requires-Dist: google-genai<3,>=2; extra == 'llm'
37
+ Description-Content-Type: text/markdown
38
+
39
+ # Mercury Composable — polyglot functions for Python
40
+
41
+ Write decoupled functions in Python and let [Mercury Composable](https://github.com/Accenture/mercury-composable)
42
+ engines (Java, and the official [Rust port](https://github.com/Accenture/mercury)) orchestrate
43
+ them from Event Script flows and MiniGraph knowledge graphs — with no orchestration code in
44
+ Python at all.
45
+
46
+ This package is a deliberately **lightweight wrapper of the Event-over-HTTP protocol**:
47
+
48
+ - an **Event API host** (`POST /api/event`) that dispatches incoming event envelopes to your
49
+ registered functions,
50
+ - a **thin client** (`PostOffice`) to call functions on peer applications the same way,
51
+ - the **standard event envelope wire format** codec (language-neutral MsgPack), and
52
+ - a **primitive in-process event bus** — the single dispatch pipeline: one FIFO mailbox
53
+ per route consumed by `instances` worker tasks, and
54
+ - the **minimalist utilities** shared with the engines for consistency: configuration
55
+ management, logging in the engines' presentation format, and distributed-trace context.
56
+
57
+ Orchestration deliberately stays in the engines. Functions written here are addressed by
58
+ route name through the engines' declarative `yaml.event.over.http` map, so a flow or a
59
+ graph task calls a Python function exactly as if it were local.
60
+
61
+ **Documentation:** <https://accenture.github.io/mercury-python/> — including the
62
+ [AI Agent Guide](https://accenture.github.io/mercury-python/guides/ai-agent-guide/)
63
+ for deterministic function generation.
64
+
65
+ > **Status: pre-release.** This repository was repurposed in August 2026 for the polyglot
66
+ > initiative. The legacy Mercury language-pack implementation remains available in the git
67
+ > history.
68
+
69
+ ## Quick start
70
+
71
+ ```python
72
+ # app.py
73
+ from mercury_composable import AppException, Body, platform, preload
74
+
75
+ @preload(route="hello.python", instances=10)
76
+ def handle_event(headers: dict[str, str], body: Body):
77
+ if not isinstance(body, dict) or "text" not in body:
78
+ raise AppException(400, "missing 'text'")
79
+ return {"text": str(body["text"]).upper(), "language": "python"}
80
+
81
+ if __name__ == "__main__":
82
+ platform.run() # port from rest.server.port (default 8085)
83
+ ```
84
+
85
+ Run it:
86
+
87
+ ```bash
88
+ pip install -e '.[dev]'
89
+ mercury-serve app.py -Drest.server.port=8086
90
+ ```
91
+
92
+ Call it from a Mercury engine application with two configuration entries and no code —
93
+ `application.properties`:
94
+
95
+ ```properties
96
+ yaml.event.over.http=classpath:/event-over-http.yaml
97
+ ```
98
+
99
+ `event-over-http.yaml`:
100
+
101
+ ```yaml
102
+ event.http:
103
+ - route: 'hello.python'
104
+ target: 'http://127.0.0.1:8086/api/event'
105
+ ```
106
+
107
+ Any Event Script task or MiniGraph `graph.task` node that names the route `hello.python`
108
+ now executes the Python function, with trace context carried end to end.
109
+
110
+ ## The function contract
111
+
112
+ A handler receives the same two-part input as an engine `TypedLambdaFunction` —
113
+ `(headers: dict[str, str], body: Body)` — `Body` is any MsgPack value — and returns the reply body (or an `EventEnvelope` for full
114
+ control of status and reply headers). **Both `async def` and plain `def` handlers are
115
+ first-class**, because Python has two library ecosystems and a polyglot function must be
116
+ able to wrap either:
117
+
118
+ - **plain `def`** — for the synchronous world: `requests` (one of the most popular HTTP
119
+ clients), NumPy/pandas and most ML inference stacks, database drivers. These handlers
120
+ run in a thread-pool executor, so a blocking call can never stall the event loop that
121
+ hosts every other function. This is the Python analog of the Java engine's virtual
122
+ threads: write sequential blocking-style code and the platform makes it safe.
123
+ - **`async def`** — for asyncio-native I/O and for composing sibling functions with
124
+ `await po.request(...)`.
125
+
126
+ The style is detected automatically (no flag to set), and trace context, `instances`,
127
+ envelopes and telemetry behave identically in both. Rule of thumb: wrapping a blocking
128
+ library → plain `def`; composing functions or async I/O → `async def`.
129
+
130
+ - Raise `AppException(status, message)` for intentional errors — it becomes the portable
131
+ error contract on the wire (envelope status + message), handled by the calling flow's
132
+ exception handler or the graph's `error.*` contract.
133
+ - `get_trace()` exposes `trace_id` / `trace_path` / `cid`; `annotate_trace(k, v)` sends an
134
+ annotation back on the reply envelope.
135
+ - Outside a hosted function (batch jobs, tests), `trace_context(trace_id, trace_path)`
136
+ establishes the context your `PostOffice` calls inherit — the node `runWithTrace` twin.
137
+ - Functions must be stateless; anything you must keep belongs to the caller's flow model
138
+ or state machine.
139
+
140
+ ### Local function calls
141
+
142
+ `PostOffice` **without an endpoint** delivers through this application's own event bus —
143
+ the engines' semantics for an in-app `po` call:
144
+
145
+ - `private=True` means exactly what it means in the engines: callable **in-app only**.
146
+ Local calls reach private and public routes alike; the HTTP host keeps answering 403
147
+ for private targets from the wire.
148
+ - `instances` is faithful: each route has one FIFO mailbox consumed by that many worker
149
+ tasks. RPC waits are bounded by `timeout_ms` (the standard 408 envelope on breach), and
150
+ a queued call whose caller already timed out is skipped, never wastefully executed.
151
+ - **Sync handlers compose too**: `po.request_sync(...)` / `po.send_sync(...)` run the
152
+ same call on the host loop while blocking only the handler's own worker thread — the
153
+ trace chain rides across the bridge unbroken. Calling the sync bridge from async code
154
+ is refused with a teaching error (`await po.request(...)` is the async way), and using
155
+ it outside a hosted function tells you to use `asyncio.run(po.request(...))` instead.
156
+ - There is **no spill tier and no queue cap** by design: back-pressure belongs to the tier
157
+ that owns recovery — the engines' flows and graphs. A leaf host fails fast by deadline
158
+ instead of hoarding work.
159
+
160
+ Local eventing is for simple leaf-side composition. Workflow processing belongs in Event
161
+ Script and Knowledge Graph on the engines — that boundary is the architecture.
162
+
163
+ ## Configuration, logging, telemetry
164
+
165
+ The same conventions as the engines, so a polyglot installation stays uniform:
166
+
167
+ | Key | Meaning | Default |
168
+ |-----|---------|---------|
169
+ | `application.name` | application identity in logs | `application` |
170
+ | `rest.server.port` | Event API port | `8085` |
171
+ | `log.format` | `text`, `json` (pretty-printed) or `compact` (single-line JSONL) | `text` |
172
+ | `log.level` | log level (`LOG_LEVEL` env var wins) | `INFO` |
173
+
174
+ Configuration lives in the `resources` folder, mirroring the engines:
175
+ `resources/application.yml` (or `.yaml` / `.properties`) in the working directory or next
176
+ to the application file, or an explicit `--config` path — see
177
+ [`examples/resources/application.yml`](examples/resources/application.yml) for a worked
178
+ sample. Values support `${ENV_VAR:default}` substitution. Runtime parameter overrides use the
179
+ same `-D` syntax as the Java engine and the Rust port — checked first on every read
180
+ (`AppConfig.set(key, value)` does the same programmatically, the `f:setConfig` analog):
181
+
182
+ ```bash
183
+ mercury-serve app.py -Drest.server.port=8086 -Dlog.format=json
184
+ ```
185
+
186
+ Log lines follow the Java reference engine's pattern for one-aggregation consistency:
187
+
188
+ ```text
189
+ 2026-08-22 10:15:30.123 INFO my_app:42 - Loaded PUBLIC hello.python, instances=10
190
+ ```
191
+
192
+ ## Actuator endpoints
193
+
194
+ The host serves the engines' operational endpoints on the same port as `/api/event`, so
195
+ Kubernetes probes and dashboards treat a Python app exactly like a Java or Rust engine app:
196
+
197
+ | Endpoint | Purpose |
198
+ |----------|---------|
199
+ | `GET /` | minimal index page linking the endpoints below |
200
+ | `GET /info` | app identity, runtime, origin id, start time, uptime |
201
+ | `GET /info/routes` | registered routes split by visibility, with instance counts |
202
+ | `GET /env` | selected environment variables and configuration parameters |
203
+ | `GET /health` | dependency health checks — `UP` (HTTP 200) or `DOWN` (HTTP 400) |
204
+ | `GET /livenessprobe` | `OK` while the last health outcome was good, else HTTP 400 |
205
+
206
+ Configuration keys carry the engines' names: `info.app.version`, `info.app.description`,
207
+ `show.env.variables` and `show.application.properties` (opt-in lists — secrets are never
208
+ dumped wholesale), and `mandatory.health.dependencies` / `optional.health.dependencies`
209
+ (routes of health check functions; optional ones never change the overall status). A
210
+ health check function is a normal registered function — usually private — speaking the
211
+ engines' interface contract, called through the event bus:
212
+
213
+ ```python
214
+ @preload("demo.health", private=True)
215
+ async def health(headers: dict[str, str], _body: Body) -> Body:
216
+ if headers.get("type") == "info":
217
+ return {"service": "demo.service", "href": "http://127.0.0.1"}
218
+ return "demo.service is running fine" # a non-200 reply marks it down
219
+ ```
220
+
221
+ JSON responses are pretty-printed — the engines' default-serializer presentation — and
222
+ unknown paths answer the engines' error shape
223
+ (`{"status": 404, "message": "Resource not found", "type": "error"}`).
224
+
225
+ Kubernetes wiring: point `livenessProbe` at `/livenessprobe` and `readinessProbe` at
226
+ `/health`.
227
+
228
+ ## Wire compatibility
229
+
230
+ The codec implements the
231
+ [Event Envelope Wire Format](https://accenture.github.io/mercury-composable/guides/event-envelope-wire-format/)
232
+ (standard format) and is verified against the golden conformance vectors shared by the
233
+ Java and Rust engines (`tests/vectors/vectors.json`). The classic compact format is
234
+ detected and rejected with a teaching error — engines default to the standard format for
235
+ Event over HTTP.
236
+
237
+ Serialization notes: integers and floats follow MsgPack's natural widths (the same
238
+ long/integer care as the engines applies); timestamps travel as ISO-8601 UTC strings with
239
+ millisecond precision; binary payloads use MsgPack `bin`.
240
+
241
+ ## Scope
242
+
243
+ This package intentionally contains **no orchestration: no flows, no graphs, no
244
+ persistence, no pub/sub broadcast** — those live in the engines. What it does carry is
245
+ deliberately minimal: functions, a primitive in-process event bus (route mailboxes +
246
+ workers, RPC and drop-n-forget — nothing more), and the minimalist foundation utilities,
247
+ keeping Python fast to prototype with while the composable core guarantees the
248
+ architecture.
249
+
250
+ ## Development
251
+
252
+ ```bash
253
+ uv venv .venv && uv pip install -e '.[dev]' # environment (uv-managed python)
254
+ .venv/bin/pytest -q # tests
255
+ uvx ruff check . # lint (config in pyproject.toml)
256
+ uvx basedpyright # type check (config in pyproject.toml)
257
+ ```
258
+
259
+ PyCharm: use interpreter type **uv** pointing at the project `.venv`, and set
260
+ *Settings → Tools → Python Integrated Tools → Package requirements file* to
261
+ `pyproject.toml` so the requirements inspection reads `[project.dependencies]`.
262
+
263
+ ## License
264
+
265
+ Apache 2.0 — see [LICENSE.txt](LICENSE.txt).