cultcache-py and cultcache-ts: an injectable cache clock, as the Rust and C# caches have #191

Merged
eureka merged 4 commits from hands/py-ts-cache-clock into main 2026-11-28 02:37:43 +00:00
16 changed files with 263 additions and 44 deletions

View file

@ -13,13 +13,15 @@
### Added
- `CultCache(clock=...)`, `CultCacheBuilder.with_clock(clock)` and a settable `cache.clock`: the one clock (`Callable[[], datetime]`, timezone-aware; the wall clock by default) that stamps every fresh write, as the C# `Clock` and the Rust `set_clock` do. `CultCacheEnvelope.create` takes an optional `stored_at` and keeps the wall clock for direct store callers. A pinned clock alone is not byte-identity where a writer mints random values of its own (the C# writer's unset element ids); this writer mints none.
- `CultCacheError` is exported from the package root (`from cultcache_py import CultCacheError`); it was reachable only from the private `cultcache_py.cache` module.
- `CultCache.update` and `update_global` return `UpdateResult(outcome, document)`; `UpdateOutcome` is `UPDATED`, `DECLINED` or `LOST_RACE`. The single-file store gains `read(key)` (the record and its content version, the SHA-256 C# computes) and `commit_if(envelope, expected)`, the version is the SHA-256 of the record re-encoded as `[key, schemaId, storedAt, payload]` with minimal MessagePack encodings, which is the SHA-256 of the record's stored bytes exactly when the writer encoded it minimally (every writer in this library does; a record another writer encoded with a wider-than-needed length or integer has the version of its minimal form, not of its bytes). Both looked up by the cache and not `BackingStore` protocol members (variants:cut_spec:cut-update-with-retry-py).
- `read_payload_tree(type_name, payload, decoder=None, depth_faults=(msgpack.exceptions.StackError,))`: the exported owner of the one-value, depth-first payload read that `decode_payload` uses, for payloads read outside a definition (`cultnet-py`'s witness bundle decode needs it, so `cultnet-py` now requires `cultcache-py>=0.4.0`). The manifest version is 0.4.0, the minor these Unreleased breaking changes imply, set in this change so the workspace install resolves the new bound; the `## Unreleased` heading becomes `## [0.4.0]` when it is tagged.
### Changed
- A write that replaces a record is stored at a later `stored_at` than the record it replaces, in the single-file store, the JSONL store and a store-less cache, with no exception for identical content (`variants:ruling:py-rs-update-follow-csharp-restamp`); the cache holds the stamp the store wrote. A stored_at is read only in the shape the runtimes write (an RFC 3339 date-time with T, a fraction of 1 to 9 digits, Z or a numeric offset), the same on every Python; any other text, or an instant outside `datetime`'s range, is not a stamp and a write over it is stamped at now. A write over a record stamped at the last instant `datetime` can hold (9999-12-31T23:59:59.999999Z) is refused with `ValueError` and writes nothing.
- A store's restamp of a replacing write (`stored_at_over`) reads no clock: the staged stamp when both parse and it is strictly later, else the replaced stamp plus one microsecond (variants cultlib-gaps ruling `sibling-restamp-staged-derived`, as Rust and TypeScript do). A replaced stamp that does not parse leaves the staged stamp as written; before, such a write was stamped at now. `mint_stored_at` is removed. A store-less cache restamps nothing: a replacing write holds the stamp it was given, as the Rust and TypeScript caches do (it was restamped later before).
- A write that replaces a record is stored at a later `stored_at` than the record it replaces, in the single-file store and the JSONL store, with no exception for identical content (`variants:ruling:py-rs-update-follow-csharp-restamp`); the cache holds the stamp the store wrote. A stored_at is read only in the shape the runtimes write (an RFC 3339 date-time with T, a fraction of 1 to 9 digits, Z or a numeric offset), the same on every Python; any other text, or an instant outside `datetime`'s range, is not a stamp and a write over it is stamped at now. A write over a record stamped at the last instant `datetime` can hold (9999-12-31T23:59:59.999999Z) is refused with `ValueError` and writes nothing.
- `store_write_lock` looks for a link at the store path again once the lock is held, so a link put at the path while a writer waited on the lock is refused with `StoreLinkedError` and the lock released, instead of being replaced. `JsonLinesBackingStore` takes no cross-process lock (only its thread lock, under which it already refuses a link), so it has no lock wait to re-check across. Pinned by a test that puts the link while a foreign process holds the lock.
- `CultCache.is_writable` does not look at store paths: a link at a store path is not predicted, and the write refuses it with `StoreLinkedError`. Pinned by a test through a cache attached to a linked store.
- `JsonLinesBackingStore` writes LF line endings on Windows. It wrote CRLF there, through `write_text` newline translation, before the commit_store_file change (#154, adbbb780).

View file

@ -76,6 +76,7 @@ store.
- `leaves` (typed slot leaves)
- `define_document_registry(...)`
- `CultCache.builder()`
- `CultCache(clock=...)`, `CultCacheBuilder.with_clock(clock)` and the settable `cache.clock`: the one clock (a `() -> datetime`, timezone-aware; the wall clock by default) that stamps fresh writes. Pin it to write reproducible stores; a replacing write is still stamped later than the record it replaces. A pinned clock alone is not byte-identity where a writer mints random values of its own (the C# writer's unset element ids); this writer mints none.
- `register_document_type(...)`
- `register_registry(...)`
- `register_name_lookup(...)`

View file

@ -46,12 +46,14 @@ class CultCacheEnvelope:
payload: bytes,
schema_id: str | None = None,
catalog_entry: CultCacheSchemaCatalogEntry | None = None,
stored_at: str | None = None,
) -> "CultCacheEnvelope":
"""A cache stamps through its own clock and passes `stored_at`; a direct store caller leaves it out and gets the wall clock."""
return cls(
key=key,
type=type,
payload=payload,
stored_at=datetime.now(timezone.utc).isoformat(),
stored_at=datetime.now(timezone.utc).isoformat() if stored_at is None else stored_at,
schema_id=schema_id,
catalog_entry=catalog_entry,
)

View file

@ -7,6 +7,7 @@ import os
import threading
from decimal import Decimal
from dataclasses import dataclass, field, replace
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Callable, Generic, Iterable, TypeVar
@ -18,7 +19,6 @@ from .stores import (
SingleFileMessagePackBackingStore,
parse_stored_at,
retyped,
stored_at_over,
written_owns,
)
@ -188,10 +188,18 @@ _Indexes = dict[tuple[str, str, str], str]
_LookupKeysByType = dict[str, dict[str, _LookupKeys]]
def _wall_clock() -> datetime:
return datetime.now(timezone.utc)
class CultCacheBuilder:
def __init__(self) -> None:
self._cache = CultCache()
def with_clock(self, clock: Callable[[], datetime]) -> "CultCacheBuilder":
self._cache.clock = clock
return self
def register_document_type(self, document: DocumentDefinition[Any]) -> "CultCacheBuilder":
self._cache.register_document_type(document)
return self
@ -227,7 +235,12 @@ class CultCache:
def builder(cls) -> CultCacheBuilder:
return CultCacheBuilder()
def __init__(self) -> None:
def __init__(self, clock: Callable[[], datetime] | None = None) -> None:
"""`clock` is the one source of "now" for every stamp this cache mints: a timezone-aware datetime, the wall clock by default.
Pin it to write reproducible stores. A replacing write is still stamped later than the record it replaces, derived from the
two stamps and no clock. A pinned clock alone is not byte-identity where a writer mints random values of its own (the C#
writer's unset element ids); this writer mints none."""
self._clock: Callable[[], datetime] = clock or _wall_clock
self._state = _State()
# Mutations hold this lock and refuse to start on the thread already inside one (see _mutating).
# It is reentrant so a mutation's extractors, decoders and updaters may still read the cache.
@ -237,6 +250,18 @@ class CultCache:
self._lock = threading.RLock()
self._mutating_thread: int | None = None
@property
def clock(self) -> Callable[[], datetime]:
return self._clock
@clock.setter
def clock(self, clock: Callable[[], datetime]) -> None:
self._clock = clock
def now_stamp(self) -> str:
"""The stored_at a fresh write is stamped with now, from this cache's clock."""
return self._clock().astimezone(timezone.utc).isoformat()
@_mutating
def register_document_type(self, document: DocumentDefinition[Any]) -> None:
self._register_document_type(document)
@ -530,6 +555,7 @@ class CultCache:
payload=document.encode_payload(value),
schema_id=catalog_entry.schema_id,
catalog_entry=catalog_entry,
stored_at=self.now_stamp(),
)
return self._write(document, [(envelope, value)], batch=False, expected=expected)
@ -647,11 +673,6 @@ class CultCache:
stamps[records[0][0].key] = store.push(records[0][0])
if legacy_key is not None:
self._retire_legacy_global(store, type, legacy_key)
else:
for envelope, _ in records:
held_at = next((held for held in (by_type.get(envelope.key) for by_type in self._state.envelopes.values()) if held is not None), None)
if held_at is not None:
stamps[envelope.key] = stored_at_over(envelope.stored_at, held_at.stored_at)
self._state.legacy_global_keys.pop(type, None)
values = self._state.values.setdefault(type, {})
envelopes = self._state.envelopes.setdefault(type, {})
@ -718,7 +739,7 @@ class CultCache:
raise CultCacheError(f"Global document {document.type} must use key {GLOBAL_KEY}")
self._refuse_unread([key])
entry = document.catalog_entry()
probe = CultCacheEnvelope.create(key=key, type=document.type, payload=b"", schema_id=entry.schema_id, catalog_entry=entry)
probe = CultCacheEnvelope.create(key=key, type=document.type, payload=b"", schema_id=entry.schema_id, catalog_entry=entry, stored_at=self.now_stamp())
return self._refuse_retype(document, [probe])
def _refuse_unread(self, keys: list[str]) -> None:

View file

@ -814,27 +814,19 @@ def parse_stored_at(text: Any) -> datetime | None:
return None
def mint_stored_at(previous: str | None, now: datetime) -> str:
"""A stored_at later than `previous` (C# MintStoredAt): `now`, or the microsecond after `previous` when `now` is not later.
A previous that does not parse leaves `now`. Raises ValueError, nothing minted, when `previous` is the last instant a stamp
can name, so a write over it is refused and writes nothing."""
now = now.astimezone(timezone.utc)
last = parse_stored_at(previous)
if last is not None and now <= last:
try:
now = last + timedelta(microseconds=1)
except OverflowError:
raise ValueError(f"stored_at {previous!r} is the last instant a stamp can name; a write over it cannot be stored later") from None
return now.isoformat(timespec="microseconds")
def stored_at_over(staged: str, replaced: str) -> str:
"""The stored_at a record replacing `replaced` is written with (C# StoredAtOver): `staged` when both parse and it is strictly
later, else one minted over `replaced`. No content is compared: every replacing write is stamped later."""
"""The stored_at a record replacing `replaced` is written with (C# StoredAtOver), derived from the two stamps and no clock
(variants:ruling:sibling-restamp-staged-derived): `staged` when both parse and it is strictly later, else the microsecond after
`replaced`. A `replaced` that does not parse leaves nothing to be later than, so `staged` stands as written. Raises ValueError,
nothing minted, when `replaced` is the last instant a stamp can name, so a write over it is refused and writes nothing. No
content is compared: every replacing write is stamped later."""
later, earlier = parse_stored_at(staged), parse_stored_at(replaced)
if later is not None and earlier is not None and later > earlier:
if earlier is None or (later is not None and later > earlier):
return staged
return mint_stored_at(replaced, datetime.now(timezone.utc))
try:
return (earlier + timedelta(microseconds=1)).isoformat(timespec="microseconds")
except OverflowError:
raise ValueError(f"stored_at {replaced!r} is the last instant a stamp can name; a write over it cannot be stored later") from None
def record_version(envelope: CultCacheEnvelope) -> str:

View file

@ -0,0 +1,83 @@
from __future__ import annotations
import shutil
import tempfile
import unittest
from dataclasses import asdict, dataclass
from datetime import datetime, timedelta, timezone
from pathlib import Path
from cultcache_py import CultCache, SingleFileMessagePackBackingStore, define_document_type
from cultcache_py.stores import stored_at_over
@dataclass
class Settings:
theme: str
retries: int
settings_doc = define_document_type("settings", encode=asdict, decode=lambda raw: Settings(**raw))
PINNED = datetime(2026, 3, 4, 5, 6, 7, tzinfo=timezone.utc)
class CacheClockTests(unittest.TestCase):
def setUp(self) -> None:
self.dir = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, self.dir, ignore_errors=True)
def pinned_cache(self, name: str, clock=lambda: PINNED, *, store: bool = True) -> CultCache:
builder = CultCache.builder().register_document_type(settings_doc).with_clock(clock)
if store:
builder.add_generic_store(SingleFileMessagePackBackingStore(self.dir / name))
cache = builder.build()
cache.pull_all_backing_stores()
return cache
def test_a_cache_with_no_clock_stamps_near_now(self) -> None:
cache = CultCache.builder().register_document_type(settings_doc).build()
cache.put(settings_doc, "app", Settings("green", 1))
stamped = datetime.fromisoformat(cache.get_envelope(settings_doc, "app").stored_at)
self.assertLess(abs((datetime.now(timezone.utc) - stamped).total_seconds()), 5)
def test_two_replays_with_a_pinned_clock_write_identical_bytes(self) -> None:
for name in ("a.cc", "b.cc"):
cache = self.pinned_cache(name)
cache.put(settings_doc, "app", Settings("green", 1))
cache.put(settings_doc, "app", Settings("blue", 2))
cache.put(settings_doc, "other", Settings("green", 1))
self.assertEqual((self.dir / "a.cc").read_bytes(), (self.dir / "b.cc").read_bytes())
def test_a_pinned_clock_still_stamps_a_replacing_write_later(self) -> None:
cache = self.pinned_cache("later.cc")
cache.put(settings_doc, "app", Settings("green", 1))
self.assertEqual(cache.get_envelope(settings_doc, "app").stored_at, "2026-03-04T05:06:07+00:00")
cache.put(settings_doc, "app", Settings("blue", 2))
self.assertEqual(cache.get_envelope(settings_doc, "app").stored_at, "2026-03-04T05:06:07.000001+00:00")
def test_the_clock_property_is_settable_and_every_write_reads_it(self) -> None:
cache = self.pinned_cache("set.cc")
cache.clock = lambda: datetime(2030, 1, 1, tzinfo=timezone.utc)
cache.put(settings_doc, "app", Settings("green", 1))
self.assertEqual(cache.get_envelope(settings_doc, "app").stored_at, "2030-01-01T00:00:00+00:00")
def test_a_non_utc_clock_stamps_in_utc(self) -> None:
cache = self.pinned_cache("zone.cc", lambda: datetime(2026, 3, 4, 5, 6, 7, tzinfo=timezone(timedelta(hours=5))))
cache.put(settings_doc, "app", Settings("green", 1))
self.assertEqual(cache.get_envelope(settings_doc, "app").stored_at, "2026-03-04T00:06:07+00:00")
self.assertEqual(cache.now_stamp(), "2026-03-04T00:06:07+00:00")
def test_a_store_less_replacing_write_keeps_the_stamp_it_was_given(self) -> None:
cache = self.pinned_cache("none", store=False)
cache.put(settings_doc, "app", Settings("green", 1))
cache.put(settings_doc, "app", Settings("blue", 2))
self.assertEqual(cache.get_envelope(settings_doc, "app").stored_at, "2026-03-04T05:06:07+00:00")
def test_a_restamp_reads_no_clock(self) -> None:
# stored_at_over takes no clock: the staged stamp when later, else the replaced stamp plus a microsecond.
self.assertEqual(stored_at_over("2000-01-01T00:00:00Z", "2001-01-01T00:00:00Z"), "2001-01-01T00:00:00.000001+00:00")
self.assertEqual(stored_at_over("2100-01-01T00:00:00Z", "2099-01-01T00:00:00Z"), "2100-01-01T00:00:00Z")
if __name__ == "__main__":
unittest.main()

View file

@ -26,7 +26,7 @@ from cultcache_py import (
leaves as t,
)
from cultcache_py.cache import GLOBAL_KEY, CultCacheError
from cultcache_py.stores import parse_stored_at, mint_stored_at, record_version, stored_at_over
from cultcache_py.stores import parse_stored_at, record_version, stored_at_over
@dataclass
@ -633,11 +633,17 @@ class StoreRestampTests(Fixture):
self.assertTrue(self.later_than_alpha(held))
self.assertEqual(held, self.stamp_on_disk(SingleFileMessagePackBackingStore(path)))
def test_a_store_less_cache_stamps_a_replacing_write_later(self) -> None:
def test_a_store_less_cache_keeps_the_stamp_it_was_given(self) -> None:
# No store restamps: put and update alike hold the stamp as written, as the Rust and TypeScript caches do.
cache = self.cache(store=False)
cache.put_envelope(item_doc, self.envelope(1))
cache.put_envelope(item_doc, self.envelope(2, "2000-01-01T00:00:00Z"))
self.assertTrue(self.later_than_alpha(cache.get_envelope(item_doc, "k").stored_at))
self.assertEqual(cache.get_envelope(item_doc, "k").stored_at, "2000-01-01T00:00:00Z")
cache.update(item_doc, "k", lambda item: Item(item.name, 3))
self.assertNotEqual(cache.get_envelope(item_doc, "k").stored_at, "")
cache.clock = lambda: datetime(2031, 1, 1, tzinfo=timezone.utc)
cache.put(item_doc, "k", Item("n", 4))
self.assertEqual(cache.get_envelope(item_doc, "k").stored_at, "2031-01-01T00:00:00+00:00")
def test_only_the_stamp_shape_the_runtimes_write_parses(self) -> None:
"""An RFC 3339 date-time with T, a fraction of 1 to 9 digits and Z or a numeric offset, on every interpreter (the shape is
@ -671,11 +677,8 @@ class StoreRestampTests(Fixture):
for text in ("9999-12-31T23:30:00-05:00", "0001-01-01T00:00:00+05:00"):
with self.subTest(text=text):
self.assertIsNone(parse_stored_at(text))
now = datetime(2030, 1, 1, tzinfo=timezone.utc)
self.assertEqual(mint_stored_at("9999-12-31T23:30:00-05:00", now), "2030-01-01T00:00:00.000000+00:00")
self.assertEqual(stored_at_over("2000-01-01T00:00:00Z", "9999-12-31T23:30:00-05:00"), "2000-01-01T00:00:00Z")
edge = "9999-12-31T23:59:59.9999999Z"
with self.assertRaisesRegex(ValueError, "last instant"):
mint_stored_at(edge, now)
with self.assertRaisesRegex(ValueError, "last instant"):
stored_at_over("2000-01-01T00:00:00Z", edge)
# A write over a record stamped at the edge is refused by the store and writes nothing, from push, commit_if and update.
@ -703,11 +706,9 @@ class StoreRestampTests(Fixture):
self.assertEqual(parse_stored_at(text).tzinfo, timezone.utc)
self.assertIsNone(parse_stored_at("garbage"))
self.assertIsNone(parse_stored_at(None))
now = datetime(2030, 1, 1, tzinfo=timezone.utc)
self.assertEqual(mint_stored_at("garbage", now), "2030-01-01T00:00:00.000000+00:00")
self.assertEqual(stored_at_over("2000-01-01T00:00:00Z", "2000-01-01T00:00:00Z")[:4], str(datetime.now(timezone.utc).year)) # no later: minted at now
self.assertEqual(mint_stored_at("2030-01-01T00:00:00Z", now), "2030-01-01T00:00:00.000001+00:00") # equal is not later
self.assertEqual(mint_stored_at("2099-01-01T00:00:00.1234567Z", now), "2099-01-01T00:00:00.123457+00:00")
self.assertEqual(stored_at_over("2030-01-01T00:00:00Z", "garbage"), "2030-01-01T00:00:00Z") # nothing to be later than
self.assertEqual(stored_at_over("garbage", "garbage"), "garbage")
self.assertEqual(stored_at_over("2000-01-01T00:00:00Z", "2000-01-01T00:00:00Z"), "2000-01-01T00:00:00.000001+00:00") # equal is not later
self.assertEqual(stored_at_over("2000-01-01T00:00:00Z", "2099-01-01T00:00:00.1234567Z"), "2099-01-01T00:00:00.123457+00:00")
for reported in (True, 1, "garbage"):

View file

@ -5,6 +5,10 @@ All notable changes to `@gamecult/cultcache-ts` are recorded here, following
## [Unreleased]
### Added
- `new CultCache({ clock })` and a settable `cache.clock` (`() => Date`; `new Date()` by default): the one clock that stamps every fresh write, as the C# `Clock` and the Rust `set_clock` do. `CultCacheOptions` is exported. A store's restamp of a replacing write already read no clock (`laterStoredAt`), so a pinned clock still stamps a replacing write one millisecond later. A pinned clock alone is not byte-identity where a writer mints random values of its own (the C# writer's unset element ids); this writer mints none.
## [0.16.0] - 2026-11-14
### Added

View file

@ -152,6 +152,7 @@ const settings = cache.getRequiredGlobal(settingsDocument);
- `defineDocumentType(...)`
- `defineDocumentRegistry(...)`
- `CultCache.builder()`
- `new CultCache({ clock })` and the settable `cache.clock` (`() => Date`, `new Date()` by default): the one clock that stamps fresh writes. Pin it to write reproducible stores; a replacing write is still stamped later than the record it replaces. A pinned clock alone is not byte-identity where a writer mints random values of its own (the C# writer's unset element ids); this writer mints none.
- `registerDocumentType(...)`
- `registerRegistry(...)`
- `registerNameLookup(...)`

View file

@ -2,7 +2,7 @@
// (node:fs, koffi). Bring your own CacheBackingStore, or none.
export * as codecs from "./codec";
export type { Codec, SlotsCodec } from "./codec";
export { CultCache, CultCacheBuilder, type CultCacheForeignRecord } from "./cult-cache";
export { CultCache, CultCacheBuilder, type CultCacheForeignRecord, type CultCacheOptions } from "./cult-cache";
export { inspectCultCacheBytes } from "./cult-cache-inspector";
export {
decodeDocumentPayload,

View file

@ -194,9 +194,26 @@ function registryDefinitions(
: (registry as CultCacheDocumentRegistry).definitions;
}
export interface CultCacheOptions {
/** The one source of "now" for every stamp this cache mints; the wall clock by default. Pin it to write reproducible stores. */
clock?: () => Date;
}
export class CultCache {
static readonly GLOBAL_KEY = "__global__";
/**
* The one source of "now" for every stamp this cache mints (`new Date()` by default). Pin it to write reproducible stores. A
* replacing write is still stamped later than the record it replaces, derived from the two stamps and no clock. A pinned clock
* alone is not byte-identity where a writer mints random values of its own (the C# writer's unset element ids); this writer
* mints none.
*/
clock: () => Date;
constructor(options: CultCacheOptions = {}) {
this.clock = options.clock ?? (() => new Date());
}
static {
registerNow = (cache, definition) => cache.#registerNow(definition);
attachNow = (cache, store, types) => cache.#attachNow(store, types);
@ -830,7 +847,7 @@ export class CultCache {
key,
type: definition.type,
payload: this.#cloneBytes(payload),
storedAt: new Date().toISOString(),
storedAt: this.clock().toISOString(),
schemaId: registered.catalogEntry.schemaId,
catalogEntry: registered.catalogEntry,
};

View file

@ -0,0 +1,73 @@
import assert from "node:assert/strict";
import { mkdtemp, readFile, rm } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import test from "node:test";
import { z } from "zod";
import { CultCache, SingleFileMessagePackBackingStore, defineDocumentType } from "../src/index";
const settings = defineDocumentType({
type: "settings",
schemaId: "gamecult.clock_settings.v1",
schemaName: "gamecult.clock_settings",
schemaVersion: "gamecult.clock_settings.v1",
schema: z.object({ theme: z.string(), retries: z.number().int() }),
});
const pinned = () => new Date("2026-03-04T05:06:07.000Z");
async function withDir(run: (dir: string) => Promise<void>): Promise<void> {
const dir = await mkdtemp(join(tmpdir(), "cultcache-clock-"));
try {
await run(dir);
} finally {
await rm(dir, { recursive: true, force: true });
}
}
async function pinnedCache(path: string | null, clock = pinned): Promise<CultCache> {
const cache = new CultCache({ clock });
await cache.registerDocumentType(settings);
if (path !== null) {
await cache.addGenericBackingStore(new SingleFileMessagePackBackingStore(path));
}
await cache.pullAllBackingStores();
return cache;
}
test("a cache with no clock stamps near now", async () => {
const cache = new CultCache();
await cache.registerDocumentType(settings);
await cache.put(settings, "app", { theme: "green", retries: 1 });
const stamped = Date.parse(cache.getEnvelope(settings, "app")!.storedAt);
assert.ok(Math.abs(Date.now() - stamped) < 5000);
});
test("two replays with a pinned clock write identical bytes", async () => {
await withDir(async (dir) => {
for (const name of ["a.cc", "b.cc"]) {
const cache = await pinnedCache(join(dir, name));
await cache.put(settings, "app", { theme: "green", retries: 1 });
await cache.put(settings, "app", { theme: "blue", retries: 2 });
await cache.put(settings, "other", { theme: "green", retries: 1 });
}
assert.deepEqual(await readFile(join(dir, "a.cc")), await readFile(join(dir, "b.cc")));
});
});
test("a pinned clock still stamps a replacing write later", async () => {
await withDir(async (dir) => {
const cache = await pinnedCache(join(dir, "later.cc"));
await cache.put(settings, "app", { theme: "green", retries: 1 });
assert.equal(cache.getEnvelope(settings, "app")!.storedAt, "2026-03-04T05:06:07.000Z");
await cache.put(settings, "app", { theme: "blue", retries: 2 });
assert.equal(cache.getEnvelope(settings, "app")!.storedAt, "2026-03-04T05:06:07.001Z");
});
});
test("the clock property is settable and the next write reads it", async () => {
const cache = await pinnedCache(null);
cache.clock = () => new Date("2030-01-01T00:00:00.000Z");
await cache.put(settings, "app", { theme: "green", retries: 1 });
assert.equal(cache.getEnvelope(settings, "app")!.storedAt, "2030-01-01T00:00:00.000Z");
});

View file

@ -92,7 +92,7 @@ test("update with retry: restock twice reads value 20 through a second cache", a
// The docs show the region between `// snippet:<region>begin` and `end` markers verbatim, the package import aside.
async function assertDocsShow(region: "" | "update:") {
// Compiled to dist-test/test/first-call.test.js, so the package root is two levels up.
const source = await readFile(join(__dirname, "..", "..", "test", "first-call.test.ts"), "utf8");
const source = (await readFile(join(__dirname, "..", "..", "test", "first-call.test.ts"), "utf8")).replace(/\r\n/g, "\n");
const snippet = source
.split(`// snippet:${region}begin\n`)[1]
.split(`// snippet:${region}end\n`)[0]

View file

@ -569,6 +569,7 @@ class CultMeshDatabase:
payload=registered.encode_payload(parsed),
schema_id=catalog_entry.schema_id,
catalog_entry=catalog_entry,
stored_at=self.cache.now_stamp(),
)
value = self.cache.put_envelope(registered, envelope)
# The stamp the write was stored at, which a replacing write mints later than the record it replaces: the cache holds it.

View file

@ -797,12 +797,28 @@ class CultMeshTests(unittest.TestCase):
self.assertEqual(node.get_required(document, "note:second").body, "second catalog publication")
self.assertIsInstance(node.get_required(alias, "note:second"), UiNote)
def attach_store(self, cache) -> None:
directory = tempfile.TemporaryDirectory()
self.addCleanup(directory.cleanup)
cache.add_generic_store(SingleFileMessagePackBackingStore(Path(directory.name) / "store.cc"))
cache.pull_all_backing_stores()
def test_raw_put_stamps_from_the_cache_clock(self) -> None:
document = define_database_entry_type("mesh.clock_item", [("name", 0), ("category", 1), ("value", 2, 0)], cls=Item)
node = create_node(runtime_id="python-node")
node.register_document(document)
node.database.cache.clock = lambda: datetime(2026, 3, 4, 5, 6, 7, tzinfo=UTC)
wire = node.put_raw_message(document, "item:clock", Item("pinned", "gear", 1)).to_wire()
self.assertEqual(wire["document"]["storedAt"], "2026-03-04T05:06:07+00:00")
self.assertEqual(node.database.cache.get_required_envelope(document, "item:clock").stored_at, "2026-03-04T05:06:07+00:00")
def test_raw_put_publishes_and_logs_the_stamp_the_store_wrote(self) -> None:
document = define_database_entry_type("mesh.stamp_item", [("name", 0), ("category", 1), ("value", 2, 0)], cls=Item)
node = create_node(runtime_id="python-node")
node.register_document(document)
cache = node.database.cache
entry = document.catalog_entry()
self.attach_store(cache) # a store restamps a replacing write; a store-less cache holds the stamp as given
future = "2099-01-01T00:00:00.000000+00:00"
cache.put_envelope(
document,
@ -828,6 +844,7 @@ class CultMeshTests(unittest.TestCase):
node.register_document(document)
cache = node.database.cache
entry = document.catalog_entry()
self.attach_store(cache) # a store restamps a replacing write; a store-less cache holds the stamp as given
def envelope(value: int, stored_at: str) -> CultCacheEnvelope:
return CultCacheEnvelope("item:applied", document.type, document.encode_payload(Item("n", "gear", value)), stored_at, entry.schema_id, entry)

View file

@ -89,7 +89,11 @@ class NotificationStampTests(unittest.TestCase):
subscriptions = {"s": _DatabaseSubscription("s", set(), set())}
replies = server._handle_connection_message(put_of(KEY_A, "peer", stored_at=peer_stamp), subscriptions, peer=PEER)
held = node.cache.get_required_envelope(NOTE, KEY_A).stored_at
self.assertGreater(held, local)
# A store restamps a replacing write later than the record it replaces; a store-less cache holds the peer's stamp.
if backing is None:
self.assertEqual(held, peer_stamp)
else:
self.assertGreater(held, local)
self.assertEqual([reply["document"]["storedAt"] for reply in replies], [held])
self.assertEqual(node.database._shard_logs[SHARD_ID][-1]["put"]["document"]["storedAt"], held)