Computation fingerprints¶
A computation fingerprint answers “would the same operation run?” It covers the implementation, effective configuration and relevant external dependencies. Together with the effective argument identity, it selects a cached result. Automatic discovery is a bounded aid for quick experimentation: it does not guarantee that every change affecting a result invalidates the cache. The limits below explain when to reload definitions, provide an explicit identity or clear retained entries.
Let the decorator identify the computation¶
Normally, add @cached. It derives computation identity, uses the shared cache, and chooses
Pydantic serialization from the return annotation. FingerprintedDataModel handles data identity:
from triplum.cache import cached
from triplum.datatype import FingerprintedDataModel
class Text(FingerprintedDataModel):
text: str
@cached
def normalize(value: Text) -> Text:
return Text(text=value.text.casefold())
print(normalize(Text(text="Straße")).text)
print(normalize(Text(text="Straße")).text)
Both calls print strasse; the second can reuse the first result, including an accepted write
that has not reached disk yet. Existing persisted entries may also be reused on the first call.
The value fingerprint answers which inputs are equivalent; the decorator handles
which computation runs on them. No manually maintained version label is needed.
Configure a function with a factory¶
Capture a setting in a function factory; the decorator includes its value in computation identity.
Continue with the imports and Text model above:
def make_append(suffix: str):
@cached
def append(value: Text) -> Text:
print("Computing", suffix)
return Text(text=value.text + suffix)
return append
value = Text(text="Hello")
for suffix in ("!", "!", "?", "!"):
print(make_append(suffix)(value).text)
With an empty cache:
Computing !
Hello!
Hello!
Computing ?
Hello?
Hello!
Each factory call creates a function, but equal captured settings select the same computation.
Changing ! to ? selects another entry; returning to ! reuses the earlier result.
On later runs, persisted entries can also remove the Computing lines. Captured settings are
read again before each lookup; keep them stable throughout each call.
Change context between calls¶
A supported global setting is reread for each lookup on the same decorated function. This complete example uses a temporary owner so each run starts empty:
from pathlib import Path
from tempfile import TemporaryDirectory
from triplum.cache import Cache, SQLiteBackend
from triplum.datatype import FingerprintedDataModel
DESCRIPTION = "Collection A"
class Rendered(FingerprintedDataModel):
text: str
with TemporaryDirectory() as directory:
with Cache(SQLiteBackend(Path(directory) / "cache.sqlite")) as cache:
@cache.cached
def render(text: str) -> Rendered:
print("Computing", DESCRIPTION)
return Rendered(text=DESCRIPTION + ": " + text)
for description in ("Collection A", "Collection B", "Collection A"):
DESCRIPTION = description
print(render("Evidence").text)
Output:
Computing Collection A
Collection A: Evidence
Computing Collection B
Collection B: Evidence
Collection A: Evidence
The original function and input stay the same. A→B→A performs two computations and then reuses
the retained A result. The shared definition_hash() also rereads its bounded loaded-definition
projection on every request; computation mixins and CachedStep refresh definitions and selected
configuration. Immutable code/disassembly work remains cached. Codec selection and opening the
shared cache remain lazy; their lifecycle is separate from identity refresh.
Keep inputs and context stable during a call¶
Keep effective inputs and context stable while identity is calculated and throughout computation. The cache does not provide snapshot consistency or detect mutations during that interval. If context changes from A to B while a call runs, its result can mix A and B; neither fingerprint necessarily identifies that result. There is no post-computation identity check or mutation tracking. Even a final check could not establish consistent execution or detect change-and-restore. Between-call changes to represented context are supported; changes during a call are outside the guarantee. This applies to both static and traced mode. Existing discovery rejects some recognized mutation patterns; it does not enforce context stability.
Call helpers normally¶
The decorator follows ordinary Python helpers in application code. Continue with Text above:
def fold(text: str) -> str:
return text.casefold()
@cached
def transform(value: Text) -> Text:
return Text(text=fold(value.text))
print(transform(Text(text="Straße")).text)
print(transform(Text(text="Straße")).text)
Both calls print strasse. Rebinding fold to a new loaded implementation changes the next
lookup's computation identity, even if the original decorated transform is unchanged. No
dependency list or version string is needed.
Ordinary application classes can be helpers too. Continue with the same imports and Text model:
class Folder:
def run(self, text: str) -> str:
return text.casefold()
@cached
def transform_with_class(value: Text) -> Text:
return Text(text=Folder().run(value.text))
print(transform_with_class(Text(text="Straße")).text)
print(transform_with_class(Text(text="Straße")).text)
Both calls print strasse. In the default static mode, editing Folder.run and loading the
new definitions changes the computation identity. Supported referenced application classes use
loaded-definition hashing: methods, bases and supported immutable constants contribute. This
does not call a class's fingerprint() or Python's hash(); an instance's fingerprint() still defines its selected
value when that instance is an input or configuration.
Know the automatic boundary¶
Bare @cached and @cache.cached identify loaded Python definitions, evaluated defaults,
nonlocal captures, supported globals and statically resolved application helpers before every
lookup. Helpers may be defined later in the module, provided they exist when called. Referenced helpers
can call further helpers; recursive calls are supported. Direct global names and module attribute
chains are resolved without executing properties or descriptors.
Application helpers belong to the same top-level package, or the same source directory for a
standalone script, as the decorated computation. A function counts where it was defined, not
where a decorator's functools.wraps says it was. Calls outside that boundary contribute the
callable's qualified name, not its implementation.
Decorators are the exception: a decorated function contributes both the wrapper and the function
it wraps (__wrapped__). When either comes from a library, its own code, default arguments and
captured values count, so @scale(2) and @scale(3) differ; the library functions it calls
still count by name, as does a library function decorated inside its own library. A library decorator also does not move the application boundary: that is
taken from the innermost decorated function. Captured values that cannot be fingerprinted, such
as a decorator's populated memoization cache, raise TypeError rather than risk a stale result. Supported referenced global settings contribute too, including mappings of
application helpers. Discarded append-only instrumentation on plain lists or sets, and counters
updated only by NAME += constant, are excluded. Semantic mutation of global settings is
unsupported: a global that the computation assigns and otherwise reads raises TypeError. Keep
counters and diagnostic collections separate from semantic settings. Import application helpers
at module level; a function-local import of application code raises TypeError, while local
imports of external libraries are outside identity like other external calls.
In static mode, ordinary application classes referenced through global names or module attributes
follow the same boundary on a best-effort basis. If the existing class projection cannot handle
a definition, such as a generated class with unsupported descriptors or native bases, that
reference falls back to its qualified name. External classes, Pydantic model classes and class
references in traced mode also contribute their qualified names, not their definitions.
Class-valued defaults, captures and selected configuration still require an explicit projection.
Changing an external library, file, model weight or hidden resource state is therefore not
automatically detected.
Arbitrary dynamic dispatch through input objects also remains outside static helper discovery.
Optional runtime tracing can record supported
input/owner method calls and validate those dependencies on later lookups.
Defaults and captures support finite scalars, lists, tuples, string-keyed mappings, paths and
objects with fingerprint(). A path identifies its spelling, not file contents. Between-call
changes to represented settings or helper bindings change identity on the next lookup. Reload
edited implementations to run and identify the new loaded code; editing a source file alone
does not change a function already in memory. Loaded-code identity also works without inspectable
source, including functions defined interactively. It is not guaranteed stable across Python interpreter versions.
Module references work through statically resolved attributes; module-valued defaults/configuration
and dynamic module passing are unsupported. Unsupported identity projections raise TypeError
rather than silently omitting state. If supported state becomes unsupported or a referenced
binding disappears, the existing error is raised on the next lookup, before reuse.
Each static lookup walks and hashes the represented definitions/settings, so identity cost grows with that state. Cache expensive composite operations where avoided work justifies this cost.
When external state affects an answer, make its effective identity part of the input or captured
configuration. An explicit process_id remains available for applications that already have a
complete computation identity; it replaces automatic inference. There is no manual dependency
parameter.
Cache a chunker¶
A cached computation must return a Pydantic model that implements fingerprint(). A bare
list[Chunk] is not one, so @cached raises TypeError and asks you to wrap the list in a
model or supply an output_type or codec. Wrap the chunks in a small
FingerprintedDataModel:
from pathlib import Path
from tempfile import TemporaryDirectory
from uuid import UUID
from triplum.cache import Cache, SQLiteBackend
from triplum.datatype import Chunk, Collection, FingerprintedDataModel, Source
from triplum.steps.chunking import FixedSize
class Chunks(FingerprintedDataModel):
chunks: list[Chunk]
chunker = FixedSize(20)
text = "Returns are accepted within 30 days."
with TemporaryDirectory() as directory:
with Cache(SQLiteBackend(Path(directory) / "cache.sqlite")) as cache:
@cache.cached
def chunk(source: Source) -> Chunks:
print("Chunking", source.origin)
return Chunks(chunks=chunker(source))
pinned = Collection(id=UUID("019a0000-0000-7000-8000-000000000001"), name="Notes")
for collection in (pinned, pinned, Collection(name="Notes")):
source = Source(collection_id=collection.id, origin="returns.md", text=text)
print([c.text for c in chunk(source).chunks])
Output:
Chunking returns.md
['Returns are accepted', ' within 30 days.']
['Returns are accepted', ' within 30 days.']
Chunking returns.md
['Returns are accepted', ' within 30 days.']
The third call computes again although the text is the same. A Source's fingerprint includes
its collection_id, and Collection(name=...) without an id gets a new random id each
time. A program that creates its collection that way therefore misses the cache on every run.
To reuse results across runs, keep the collection's id fixed, as pinned does above; see
Collection. The example's temporary cache disappears when it
ends; to reuse results in a later process, use the persistent default cache (bare @cached, see
ownership) or a fixed cache path.
Report progress from a cached step¶
Globals and captured values that a cached step references must be fingerprintable, and an open
stream is not. A step
that calls print(..., file=sys.stderr) therefore raises TypeError with
cannot fingerprint TextIOWrapper. A module-level logger = logging.getLogger(__name__) fails
the same way, because a Logger cannot be fingerprinted either. Look the logger up inside the
step instead; the logging calls are library calls, which count by name only:
import logging
from pathlib import Path
from tempfile import TemporaryDirectory
from triplum.cache import Cache, SQLiteBackend
from triplum.datatype import FingerprintedDataModel
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
class Text(FingerprintedDataModel):
text: str
with TemporaryDirectory() as directory:
with Cache(SQLiteBackend(Path(directory) / "cache.sqlite")) as cache:
@cache.cached
def shout(value: Text) -> Text:
logging.getLogger(__name__).info("Computing %s", value.text)
return Text(text=value.text.upper())
print(shout(Text(text="hello")).text)
print(shout(Text(text="hello")).text)
This prints HELLO twice on stdout, and INFO Computing hello once on stderr: the second call
reuses the result. A plain print(...) to stdout also works.
Keep restricted text out of a shared cache¶
The cache stores each result as plain bytes in its SQLite file. By default that is
cache.sqlite in your user cache folder, shared by every program that uses the default cache
(see ownership). Cached results are not scoped to a
viewer: anyone who can read the file can read the text, and any program using that cache can
reuse the result.
- Do not cache steps over restricted text into a shared cache. Give them their own cache file
with
Cache(SQLiteBackend(path)), as in the examples above. triplum cache cleardrops tables but does not runVACUUM, so the freed pages in the file can still contain the text (see administration). If those bytes must be gone, stop every writer, clear, then runVACUUMon the file, for examplesqlite3 <path> VACUUMif thesqlite3tool is installed, orpython -c "import sqlite3; sqlite3.connect('<path>').execute('VACUUM')".
Use a class when the operation needs one¶
CachedStep is optional. It supplies cache lookup and __call__ for
classes with a compute(value) method and a fingerprint_config() hook selecting effective
settings. Continue with the Text model above:
from triplum.cache import CachedStep
class Append(CachedStep[Text, Text]):
def __init__(self, suffix: str) -> None:
super().__init__()
self.suffix = suffix
def fingerprint_config(self) -> dict[str, object]:
return {"suffix": self.suffix}
def compute(self, value: Text) -> Text:
return Text(text=value.text + self.suffix)
print(Append("!")(Text(text="Hello")).text)
This prints Hello!. The inherited fingerprint combines loaded computation code with selected
settings, so equivalent instances can reuse results. super().__init__() uses the shared cache;
the compute return annotation selects serialization. Counters, clients, locks and cache resources
stay outside identity unless explicitly selected. Return {} for a stateless class. Configuration
is read on each call; do not change it while computation runs.
Pass cache=None to the base initializer to bypass caching, or supply an explicit owner as
shown in cache ownership. A step borrows its owner and never closes it.
When combining with a domain Protocol, put CachedStep first in the bases. This does not adapt
existing indexing steps' input/output shapes to fingerprintable values.
Select settings for a computation class¶
Supported configuration contains plain finite numbers, strings, booleans, None, lists, tuples,
string-keyed dictionaries, paths and objects implementing fingerprint(). Mapping insertion order
does not affect selected class configuration; use ordered pairs when the computation observes
order. A path identifies its spelling, not file bytes. Select the model's actual identity or file
content fingerprint when it affects the result.
Loaded class identity covers the qualified name, application method definitions and supported immutable class constants, including ordinary bases. Its helper discovery uses the same boundary as the decorator. Unused or overridden methods can also invalidate entries. Comments and non-executed docstring text do not affect identity; adding or removing a docstring can conservatively change it. Configuration is selected explicitly rather than scanning instance attributes, so resources and counters remain outside identity.
Other class attributes, including compiled regexes, Enum members, mutable containers and nested
classes, are not inferred. Select their effective values in fingerprint_config() when needed.
Loaded definitions and helper bindings are read on each fingerprint request. Changes to supported
methods and immutable constants therefore change the next identity; unsupported attributes still
need an explicit configuration projection.
Use the computation mixin without caching¶
FingerprintedComputationMixin
supplies computation identity independently of cache lookup. For an ordinary configured callable:
from triplum.utils.fingerprint import FingerprintedComputationMixin
class Append(FingerprintedComputationMixin):
def __init__(self, suffix: str) -> None:
self.suffix = suffix
def fingerprint_config(self) -> dict[str, object]:
return {"suffix": self.suffix}
def __call__(self, text: str) -> str:
return text + self.suffix
print(Append("!")("Hello"))
print(Append("!").fingerprint() == Append("!").fingerprint())
This prints Hello! and True. CachedStep already inherits this mixin, so it needs no extra base.
See configured-object identity for reference steps
that use it. definition_hash() exposes the shared
loaded-definition digest when an application needs to compose its own identity. A custom
fingerprint() override can supply a complete computation identity instead.
| Change | How identity follows it |
|---|---|
| A setting changes the answer | Select it in fingerprint_config() |
| Application method implementation changes | Loaded method definitions enter the automatic fingerprint |
| An application helper changes behavior | Statically resolved helper definitions enter automatically |
| External model or file content changes | Include its actual identity in effective settings or input data |
| Output schema or codec becomes incompatible | Represent its relevant definition explicitly, or clear the computation's table |
| Backend, queue policy or pipeline position changes | Keep the same semantic computation fingerprint |
Automatic identity is a useful aid for quick experiments, with bounded discovery rather than
complete correctness for arbitrary Python code. Mutable or opaque class attributes and hidden
state are not inferred. Unsupported referenced class definitions fall back to name-only identity;
explicit root class hashing with definition_hash() or the computation mixin can still reject
unsupported descriptors. Fresh observation does not widen these discovery limits.
Output-model schema, validator and default changes are not automatically hashed: stop writers and
use triplum cache clear --name my_pipeline.normalize for the affected computation, or
supply a complete process_id that includes those definitions. See
administration for name selection.
There is no hidden serialization-format key or migration layer. An ordinary read decodes the
saved value; it does not prove that current code would compute that value again. Equal value
projections remain interchangeable for consumers of those projected fields, even if upstream
histories differ. That does not guarantee
that another output model can decode an older stored payload. An explicit output_type contributes
its qualified name to the default CachedStep identity, not its full schema.
The optional decorator process_id argument overrides inference with a complete computation
digest. CacheKey.process stores its 32 bytes; cache stats displays the 64-character hexadecimal
form accepted by --computation. These are representations of the same identity.
Next: Administration to inspect and clear stored results. The advanced pages cover runtime dependency tracing and serialization.