fastcache-ai 1.1.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.
@@ -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 [yyyy] [name of copyright owner]
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,103 @@
1
+ Metadata-Version: 2.4
2
+ Name: fastcache-ai
3
+ Version: 1.1.0
4
+ Summary: Zero-infrastructure, off-heap, virtual-threaded cache for AI workloads
5
+ License-Expression: Apache-2.0
6
+ Project-URL: Homepage, https://github.com/adi407/fast_cache
7
+ Project-URL: Repository, https://github.com/adi407/fast_cache
8
+ Project-URL: Issues, https://github.com/adi407/fast_cache/issues
9
+ Keywords: cache,llm,embeddings,sidecar,off-heap
10
+ Classifier: Programming Language :: Python :: 3.10
11
+ Classifier: Programming Language :: Python :: 3.11
12
+ Classifier: Programming Language :: Python :: 3.12
13
+ Classifier: Topic :: Database
14
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
15
+ Requires-Python: >=3.10
16
+ Description-Content-Type: text/markdown
17
+ License-File: LICENSE
18
+ Provides-Extra: fast
19
+ Requires-Dist: zstandard>=0.21; extra == "fast"
20
+ Requires-Dist: msgpack>=1.0; extra == "fast"
21
+ Provides-Extra: numpy
22
+ Requires-Dist: numpy>=1.23; extra == "numpy"
23
+ Provides-Extra: jre
24
+ Requires-Dist: jdk4py>=21; extra == "jre"
25
+ Provides-Extra: dev
26
+ Requires-Dist: pytest>=7.4; extra == "dev"
27
+ Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
28
+ Requires-Dist: numpy>=1.23; extra == "dev"
29
+ Requires-Dist: msgpack>=1.0; extra == "dev"
30
+ Requires-Dist: zstandard>=0.21; extra == "dev"
31
+ Dynamic: license-file
32
+
33
+ # fastcache-ai
34
+
35
+ **A cache for AI workloads that needs no infrastructure.** No Redis, no Docker, no connection string.
36
+
37
+ ```bash
38
+ pip install fastcache-ai
39
+ ```
40
+
41
+ ```python
42
+ from fastcache_ai import fastcache
43
+
44
+ @fastcache(ttl="15m")
45
+ def embed(prompt: str):
46
+ return model.encode(prompt)
47
+ ```
48
+
49
+ That is the entire setup. On first use the library finds or boots a Java engine process, reuses it across
50
+ runs, and reaps it if your process dies. A JDK 21+ runtime is required; `pip install "fastcache-ai[jre]"`
51
+ bundles one if you do not have it.
52
+
53
+ > **The import name is `fastcache_ai`, not `fastcache`.** The bare name on PyPI belongs to an unrelated
54
+ > C implementation of `functools.lru_cache`; sharing it would make the two packages overwrite each other.
55
+
56
+ ## Why it exists
57
+
58
+ Caching an LLM response should be a one-line change. Instead it usually means standing up Redis, choosing a
59
+ serialization format, and then discovering that a 50 MB context window on the JVM heap causes GC pauses
60
+ costing more than the cache saves. FastCache stores payloads **off-heap**, invisible to the garbage
61
+ collector, and hands you two front doors onto the same engine: this decorator, and a Spring Boot
62
+ annotation for JVM services.
63
+
64
+ ## What you get
65
+
66
+ - **Off-heap storage** sized for 20–50 MB context windows and vector matrices
67
+ - **Hot-key L1 cache** — a celebrity prompt hit thousands of times per second collapses to one network
68
+ round trip every few seconds
69
+ - **Stampede protection** — when a hot key expires under concurrency, exactly one caller recomputes and
70
+ everyone else is served the still-valid previous value
71
+ - **A management console** on `http://127.0.0.1:8081/dashboard` with live memory, hit rate and an
72
+ estimated-savings figure
73
+ - **Fail-open** — if the engine is unreachable, your function simply runs
74
+
75
+ ```python
76
+ import fastcache_ai as fc
77
+
78
+ fc.dashboard(open_browser=True) # live console
79
+ fc.stats() # engine, L1 and client telemetry
80
+ fc.info() # everything needed to diagnose a problem
81
+ ```
82
+
83
+ ## Configuration
84
+
85
+ Zero configuration is a supported configuration. Common overrides:
86
+
87
+ | Variable | Purpose | Default |
88
+ |---|---|---|
89
+ | `FASTCACHE_OFFHEAP_MAX` | Native memory budget | `2g` |
90
+ | `FASTCACHE_DEFAULT_TTL` | TTL when the decorator omits one | `15m` |
91
+ | `FASTCACHE_METRICS_PORT` | Console port (`off` disables) | `8081` |
92
+ | `FASTCACHE_L1_TTL` | Local hot-key cache window, seconds | `5.0` |
93
+ | `FASTCACHE_HEARTBEAT_TIMEOUT` | Orphan-reaping window (`0` disables) | `40s` |
94
+
95
+ ## Status
96
+
97
+ Pre-release. Single-node, non-durable and unauthenticated — it binds to loopback and is not a replacement
98
+ for Redis where you need replication, failover or persistence.
99
+
100
+ Full documentation, design notes and source:
101
+ **[github.com/adi407/fast_cache](https://github.com/adi407/fast_cache)**
102
+
103
+ Apache 2.0 licensed.
@@ -0,0 +1,71 @@
1
+ # fastcache-ai
2
+
3
+ **A cache for AI workloads that needs no infrastructure.** No Redis, no Docker, no connection string.
4
+
5
+ ```bash
6
+ pip install fastcache-ai
7
+ ```
8
+
9
+ ```python
10
+ from fastcache_ai import fastcache
11
+
12
+ @fastcache(ttl="15m")
13
+ def embed(prompt: str):
14
+ return model.encode(prompt)
15
+ ```
16
+
17
+ That is the entire setup. On first use the library finds or boots a Java engine process, reuses it across
18
+ runs, and reaps it if your process dies. A JDK 21+ runtime is required; `pip install "fastcache-ai[jre]"`
19
+ bundles one if you do not have it.
20
+
21
+ > **The import name is `fastcache_ai`, not `fastcache`.** The bare name on PyPI belongs to an unrelated
22
+ > C implementation of `functools.lru_cache`; sharing it would make the two packages overwrite each other.
23
+
24
+ ## Why it exists
25
+
26
+ Caching an LLM response should be a one-line change. Instead it usually means standing up Redis, choosing a
27
+ serialization format, and then discovering that a 50 MB context window on the JVM heap causes GC pauses
28
+ costing more than the cache saves. FastCache stores payloads **off-heap**, invisible to the garbage
29
+ collector, and hands you two front doors onto the same engine: this decorator, and a Spring Boot
30
+ annotation for JVM services.
31
+
32
+ ## What you get
33
+
34
+ - **Off-heap storage** sized for 20–50 MB context windows and vector matrices
35
+ - **Hot-key L1 cache** — a celebrity prompt hit thousands of times per second collapses to one network
36
+ round trip every few seconds
37
+ - **Stampede protection** — when a hot key expires under concurrency, exactly one caller recomputes and
38
+ everyone else is served the still-valid previous value
39
+ - **A management console** on `http://127.0.0.1:8081/dashboard` with live memory, hit rate and an
40
+ estimated-savings figure
41
+ - **Fail-open** — if the engine is unreachable, your function simply runs
42
+
43
+ ```python
44
+ import fastcache_ai as fc
45
+
46
+ fc.dashboard(open_browser=True) # live console
47
+ fc.stats() # engine, L1 and client telemetry
48
+ fc.info() # everything needed to diagnose a problem
49
+ ```
50
+
51
+ ## Configuration
52
+
53
+ Zero configuration is a supported configuration. Common overrides:
54
+
55
+ | Variable | Purpose | Default |
56
+ |---|---|---|
57
+ | `FASTCACHE_OFFHEAP_MAX` | Native memory budget | `2g` |
58
+ | `FASTCACHE_DEFAULT_TTL` | TTL when the decorator omits one | `15m` |
59
+ | `FASTCACHE_METRICS_PORT` | Console port (`off` disables) | `8081` |
60
+ | `FASTCACHE_L1_TTL` | Local hot-key cache window, seconds | `5.0` |
61
+ | `FASTCACHE_HEARTBEAT_TIMEOUT` | Orphan-reaping window (`0` disables) | `40s` |
62
+
63
+ ## Status
64
+
65
+ Pre-release. Single-node, non-durable and unauthenticated — it binds to loopback and is not a replacement
66
+ for Redis where you need replication, failover or persistence.
67
+
68
+ Full documentation, design notes and source:
69
+ **[github.com/adi407/fast_cache](https://github.com/adi407/fast_cache)**
70
+
71
+ Apache 2.0 licensed.
@@ -0,0 +1,191 @@
1
+ """FastCache — a zero-infrastructure cache for AI workloads.
2
+
3
+ Installed as ``fastcache-ai``, imported as ``fastcache_ai``. The import name carries the suffix
4
+ because the bare ``fastcache`` name on PyPI already belongs to an unrelated C implementation of
5
+ ``functools.lru_cache``; sharing it would make the two packages overwrite each other on disk.
6
+
7
+ .. code-block:: python
8
+
9
+ from fastcache_ai import fastcache
10
+
11
+ @fastcache(ttl="15m")
12
+ def embed(prompt: str):
13
+ return model.encode(prompt)
14
+
15
+ Importing this package starts a background thread that locates or boots the Java engine. The import itself
16
+ never blocks and never raises: if no JVM can be found, the decorator degrades to calling your function, and
17
+ the reason is available from :func:`info`.
18
+
19
+ Set ``FASTCACHE_AUTOSTART=0`` to skip the background warm-up; the sidecar will then be started lazily on
20
+ first cache use instead.
21
+ """
22
+
23
+ from __future__ import annotations
24
+
25
+ import logging
26
+ import os
27
+ import threading
28
+ from typing import Any, Dict, Optional
29
+
30
+ from .bootstrap import console_url, ensure_sidecar, shutdown_sidecar
31
+ from .client import FastCacheClient
32
+ from .codec import Codec, describe_capabilities
33
+ from .decorator import build_key, default_client, fastcache, set_default_client, single_flight_stats
34
+ from .errors import (
35
+ FastCacheError,
36
+ ProtocolError,
37
+ SerializationError,
38
+ SidecarStartupError,
39
+ SidecarUnavailable,
40
+ WriteRejected,
41
+ )
42
+ from .l1 import HotKeyCache, NullL1
43
+ from .ttl import format_ttl, parse_ttl
44
+
45
+ __version__ = "1.1.0"
46
+
47
+ __all__ = [
48
+ "fastcache",
49
+ "FastCacheClient",
50
+ "HotKeyCache",
51
+ "NullL1",
52
+ "Codec",
53
+ "FastCacheError",
54
+ "SidecarUnavailable",
55
+ "SidecarStartupError",
56
+ "ProtocolError",
57
+ "WriteRejected",
58
+ "SerializationError",
59
+ "get",
60
+ "put",
61
+ "set",
62
+ "delete",
63
+ "stats",
64
+ "flush",
65
+ "ping",
66
+ "info",
67
+ "configure",
68
+ "ensure_sidecar",
69
+ "shutdown_sidecar",
70
+ "console_url",
71
+ "dashboard",
72
+ "single_flight_stats",
73
+ "default_client",
74
+ "set_default_client",
75
+ "build_key",
76
+ "parse_ttl",
77
+ "format_ttl",
78
+ "__version__",
79
+ ]
80
+
81
+ log = logging.getLogger("fastcache")
82
+
83
+ _startup_error: Optional[BaseException] = None
84
+ _startup_thread: Optional[threading.Thread] = None
85
+
86
+
87
+ # ---------------------------------------------------------------------------------------------------
88
+ # Module-level convenience API
89
+ # ---------------------------------------------------------------------------------------------------
90
+
91
+ def get(key: str, default: Any = None) -> Any:
92
+ """Reads a value from the shared client."""
93
+ return default_client().get(key, default)
94
+
95
+
96
+ def put(key: str, value: Any, ttl: Any = None) -> int:
97
+ """Writes a value through the shared client. Returns the wire status (0 = stored)."""
98
+ return default_client().put(key, value, ttl=ttl)
99
+
100
+
101
+ #: Redis-style alias for :func:`put`.
102
+ set = put # noqa: A001 - shadowing the builtin is intentional and scoped to this module's namespace
103
+
104
+
105
+ def delete(key: str) -> bool:
106
+ return default_client().delete(key)
107
+
108
+
109
+ def stats() -> Dict[str, Any]:
110
+ """Engine, L1 and client telemetry."""
111
+ return default_client().stats()
112
+
113
+
114
+ def flush() -> int:
115
+ """Drops every cached entry. Mostly useful between test cases."""
116
+ return default_client().flush()
117
+
118
+
119
+ def ping() -> bool:
120
+ return default_client().ping()
121
+
122
+
123
+ def configure(**kwargs: Any) -> FastCacheClient:
124
+ """Replaces the shared client with one built from ``kwargs``.
125
+
126
+ .. code-block:: python
127
+
128
+ fastcache.configure(host="10.0.0.5", port=7431, timeout=2.0)
129
+ fastcache.configure(l1=fastcache.NullL1()) # disable local caching entirely
130
+ """
131
+ client = FastCacheClient(**kwargs)
132
+ set_default_client(client)
133
+ return client
134
+
135
+
136
+ def dashboard(open_browser: bool = False) -> Optional[str]:
137
+ """Returns the management console URL, optionally opening it.
138
+
139
+ .. code-block:: python
140
+
141
+ fastcache.dashboard(open_browser=True) # live savings, memory and hit-rate console
142
+
143
+ Returns None when the console is disabled (``FASTCACHE_METRICS_PORT=off``) or its port was already
144
+ taken — the cache itself is unaffected either way.
145
+ """
146
+ ensure_sidecar()
147
+ url = console_url()
148
+ if url and open_browser:
149
+ import webbrowser
150
+
151
+ webbrowser.open(url)
152
+ return url
153
+
154
+
155
+ def info() -> Dict[str, Any]:
156
+ """Everything needed to diagnose a FastCache problem in one call."""
157
+ from . import bootstrap
158
+
159
+ details = bootstrap.info()
160
+ details["version"] = __version__
161
+ details["codecs"] = describe_capabilities()
162
+ details["autostart_error"] = repr(_startup_error) if _startup_error else None
163
+ details["single_flight"] = single_flight_stats()
164
+ return details
165
+
166
+
167
+ # ---------------------------------------------------------------------------------------------------
168
+ # Import-time autopilot
169
+ # ---------------------------------------------------------------------------------------------------
170
+
171
+ def _autostart() -> None:
172
+ """Warms the sidecar in the background.
173
+
174
+ Running on a daemon thread is the point: booting a JVM takes a few hundred milliseconds, and an
175
+ ``import`` that blocks that long is one people work around. By the time the first cache call arrives,
176
+ the engine is usually already up; if it is not, the call resolves it synchronously.
177
+
178
+ Failures are recorded, never raised. A missing JDK on a developer laptop must not break
179
+ ``import fastcache_ai`` at the top of a training script.
180
+ """
181
+ global _startup_error
182
+ try:
183
+ ensure_sidecar()
184
+ except BaseException as exc: # noqa: BLE001 - an import must not be able to fail here
185
+ _startup_error = exc
186
+ log.debug("fastcache: sidecar autostart deferred (%s)", exc)
187
+
188
+
189
+ if os.environ.get("FASTCACHE_AUTOSTART", "1").lower() not in {"0", "false", "no"}:
190
+ _startup_thread = threading.Thread(target=_autostart, name="fastcache-autostart", daemon=True)
191
+ _startup_thread.start()