SAMJournal

class smarter.lib.journal.models.SAMJournal(*args, **kwargs)[source]

Bases: Model

Model representing a journal entry: one request to the Smarter api, and its response.

Every request that is answered with a SmarterJournaledJsonResponse is journaled while the ENABLE_JOURNAL switch is on, whether it is a cli command (api/v1/cli), an LLMClient’s prompt, or a console api. Each journal entry records the user responsible, the kind of entity affected, the command executed, the request and response documents, and the status code.

The documents are read and written as JSON through request and response. They are stored in request_document and response_document, as compressed skeletons whose large and repeated parts are SAMJournalBlob rows.

Example:

Creating a new journal entry:

entry = SAMJournal.objects.create_entry(
    user=request.user,
    thing=SmarterJournalThings.PROMPT.value,
    command=SmarterJournalCliCommands.CREATE.value,
    request={"data": "example"},
    response={"result": "success"},
    status_code=201
)

See also:

Parameters:
  • key (Unknown) – Primary key: Key

  • created_at (Unknown) – Created at

  • thing (Unknown) – Thing

  • command (Unknown) – Command

  • request_document (Unknown) – Request document. The request’s skeleton, compressed. See smarter.lib.journal.storage.

  • response_document (Unknown) – Response document. The response’s skeleton, compressed. See smarter.lib.journal.storage.

  • status_code (Unknown) – Status code

Relationship fields:

Parameters:

user (Unknown) – User (related name: samjournal)

exception DoesNotExist

Bases: ObjectDoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

exception NotUpdated

Bases: ObjectNotUpdated, DatabaseError

command

CharField

Command

Choices:

  • apply

  • prompt

  • chat_config

  • delete

  • deploy

  • describe

  • get

  • journal

  • logs

  • example_manifest

  • and 8 more

Type:

Type

created_at

DateTimeField

Created at

Type:

Type

documents()[source]

Return the documents that were given or read, by name: request and response.

Return type:

dict[str, JsonValue]

Returns:

The documents, a dict of this instance.

get_command_display(*, field=<django.db.models.CharField: command>)

Shows the label of the command. See get_FOO_display() for more information.

get_thing_display(*, field=<django.db.models.CharField: thing>)

Shows the label of the thing. See get_FOO_display() for more information.

key

CharField

Primary key: Key

Type:

Type

objects = <smarter.lib.journal.models.SAMJournalManager object>
read_document(name, stored)[source]

Return a document: the one given, or the one stored, read once.

Parameters:
  • name (str) – The document’s name, request or response.

  • stored (bytes | memoryview | None) – The document’s compressed skeleton, or empty if the entry has none yet.

Return type:

JsonValue

Returns:

The document.

Raises:

smarter.lib.journal.storage.JournalStorageError – If a blob of the document is missing.

property request: JsonValue

The serialized http request, as JSON.

request_document

BinaryField

Request document. The request’s skeleton, compressed. See smarter.lib.journal.storage.

Type:

Type

property response: JsonValue

The response’s JSON body.

response_document

BinaryField

Response document. The response’s skeleton, compressed. See smarter.lib.journal.storage.

Type:

Type

save(*args, **kwargs)[source]

Save the entry, giving it a random 64-character key if it has none.

The documents given to request and response are encoded, and their new blobs are saved before the entry, so that a saved entry never references a missing blob.

Parameters:
  • args – Passed to Django’s save().

  • kwargs – Passed to Django’s save().

status_code

PositiveSmallIntegerField

Status code

Type:

Type

thing

CharField

Thing

Choices:

  • Account

  • ApiConnection

  • ApiPlugin

  • SmarterAuthToken

  • Budget

  • CustomDomain

  • Guardrail

  • ImageSearchPlugin

  • LLMClient

  • MCPClient

  • and 14 more

Type:

Type

user

ForeignKey to User

User (related name: samjournal)

Type:

Type

user_id: int | None

Internal field, use user instead.

The id of user, which Django adds: None for an anonymous request.

class smarter.lib.journal.models.SAMJournalManager(*args, **kwargs)[source]

The manager of SAMJournal.

create_entry(request, response, **fields)[source]

Create a journal entry with its documents.

SAMJournal.objects.create(request=..., response=...) does the same, but type checkers don’t know the documents, which are properties, not fields.

Parameters:
  • request (JsonValue) – The serialized http request.

  • response (JsonValue) – The response’s JSON body.

  • fields – The entry’s other fields, e.g. user, thing, command, status_code.

Return type:

SAMJournal

Returns:

The saved entry.

class smarter.lib.journal.models.SAMJournalBlob(*args, **kwargs)[source]

Bases: Model

A part of one or more journal entries’ documents: a large dict or string, or one item of a long list.

Its primary key is the SHA-256 of its JSON, so each part is stored once, however many entries contain it. Its data never changes. It is not deleted with the entries that reference it, but by SAMJournalBlobManager.prune(), once no entry references it.

See smarter.lib.journal.storage.

Parameters:
  • digest (Unknown) – Primary key: Digest

  • data (Unknown) – Data. The blob’s JSON, compressed with zlib.

  • last_used_at (Unknown) – Last used at. When an entry last saved or reused the blob, to within a day. See SAMJournalBlobManager.prune.

exception DoesNotExist

Bases: ObjectDoesNotExist

exception MultipleObjectsReturned

Bases: MultipleObjectsReturned

exception NotUpdated

Bases: ObjectNotUpdated, DatabaseError

data

BinaryField

Data. The blob’s JSON, compressed with zlib.

Type:

Type

digest

CharField

Primary key: Digest

Type:

Type

get_next_by_last_used_at(*, field=<django.db.models.DateTimeField: last_used_at>, is_next=True, **kwargs)

Finds next instance based on last_used_at. See get_next_by_FOO() for more information.

get_previous_by_last_used_at(*, field=<django.db.models.DateTimeField: last_used_at>, is_next=False, **kwargs)

Finds previous instance based on last_used_at. See get_previous_by_FOO() for more information.

last_used_at

DateTimeField

Last used at. When an entry last saved or reused the blob, to within a day. See SAMJournalBlobManager.prune.

Type:

Type

objects = <smarter.lib.journal.models.SAMJournalBlobManager object>
class smarter.lib.journal.models.SAMJournalBlobManager(*args, **kwargs)[source]

The manager of SAMJournalBlob, which saves new blobs and reads them.

mark(pending, visited, reachable)[source]

Mark the pending blobs reachable, and every blob that they reference, reading them in batches.

A blob is visited once as a plain blob and once as a chain’s node, because the two read its value differently.

Parameters:
  • pending (list[tuple[str, bool]]) – The blobs to mark, which this empties.

  • visited (set[tuple[str, bool]]) – The blobs already marked, which this extends.

  • reachable (set[str]) – The digests of the blobs already marked, which this extends.

Return type:

None

prune(grace=datetime.timedelta(days=7), dry_run=False)[source]

Delete the blobs that no journal entry references, and that weren’t used within grace.

The journal’s entries are deleted only when their user is, or by hand, so there is little to prune. Mark and sweep suits that: nothing is counted on each write. A writer may reuse an unreferenced blob while this runs, so the delete itself requires last_used_at to be older than grace, which a reused blob isn’t (see save_blobs()).

Parameters:
  • grace (timedelta) – How long an unreferenced blob is kept after its last use.

  • dry_run (bool) – If True, count the blobs that would be deleted, and delete none.

Return type:

int

Returns:

The number of blobs deleted, or that would be.

Raises:

ValueError – If grace isn’t longer than BLOB_TOUCH_INTERVAL.

reachable()[source]

Return the digests of every blob that a journal entry references, directly or through other blobs.

Every entry’s skeletons are read, and every blob that they reach, once: the whole journal. It is meant to run rarely, e.g. weekly, from prune().

Return type:

set[str]

Returns:

The digests.

read_blob(digest)[source]

Return a blob’s compressed bytes.

Parameters:

digest (str) – The blob’s digest.

Return type:

bytes

Returns:

Its bytes.

Raises:

KeyError – If there is no such blob.

save_blobs(blobs)[source]

Save the blobs that the database doesn’t have yet, and touch the stale ones that it has.

Blobs are content addressed, so a blob that exists already has the same bytes. Another writer may save the same blob at the same time: the conflict is ignored.

A reused blob whose last_used_at is older than BLOB_TOUCH_INTERVAL is touched first, so that prune() can’t delete it before the entry that reuses it is saved. A blob that prune() deleted before it was touched is not found, and is saved again.

Parameters:

blobs (dict[str, bytes]) – Each blob’s compressed bytes, by digest, from smarter.lib.journal.storage.JournalDocumentEncoder.blobs.

Return type:

int

Returns:

The number of blobs that were new.

Document Storage

Content-addressed storage of the Smarter Journal’s request and response documents.

The journal is written far more often than it is read. Most of what it writes is the response of an LLMClient’s prompt, whose messages hold the whole conversation: each turn’s response repeats every message of the turns before it, and adds one or two. Stored as plain JSON, a conversation of n turns costs O(n²) bytes. This module stores it in O(n), without knowing anything about conversations, so that every other kind of journal entry, e.g. a manifest’s apply or describe, gets the same savings wherever its documents repeat.

A document is encoded, by JournalDocumentEncoder, into a small skeleton and a set of blobs:

  • A dict or a string whose JSON is at least BLOB_MIN_BYTES long is stored once, as a blob whose id is the SHA-256 of its JSON, and replaced in the skeleton by {"$journal:ref": <digest>}. The same tool definitions, system prompt, or LLMClient configuration, sent with every turn of every conversation, is stored one time.

  • A list whose JSON is at least LIST_MIN_BYTES long is stored as a chain, a persistent linked list: each item is a node {"parent": <the previous node's digest>, "value": <the item>}, and the skeleton keeps only the last node’s digest, as {"$journal:list": <digest>, "$journal:length": n}. A node’s digest covers its parent’s, so the two lists that share their first k items share their first k nodes. A turn of a conversation stores only its new messages, and a branch of a conversation, e.g. a message edited and sent again, shares the messages before it.

A blob’s bytes never change, and two writers that store the same blob store the same bytes, so entries may be written in any order, by any number of Celery workers, with no locking. The skeleton and every blob are compressed with zlib. Blobs that no entry references any more, e.g. after a user and their entries were deleted, are deleted by smarter.lib.journal.models.SAMJournalBlobManager.prune(), with blob_references() and node_references().

A dict of the document whose keys begin with RESERVED_PREFIX is wrapped in {"$journal:escape": ...}, so that no document can be mistaken for a reference.

This module is pure: it neither reads nor writes the database. See smarter.lib.journal.models.SAMJournalBlob, which stores the blobs.

smarter.lib.journal.storage.BLOB_MIN_BYTES = 1024

A dict or string whose JSON is this long, or longer, is stored as a blob.

smarter.lib.journal.storage.BlobReader

Returns the compressed bytes of a blob, by its digest.

alias of Callable[[str], bytes]

smarter.lib.journal.storage.BlobReference

its digest, and whether it is a chain’s node.

Type:

A blob that a value references

alias of tuple[str, bool]

class smarter.lib.journal.storage.JournalDocumentDecoder(read_blob)[source]

Decodes the skeletons of JournalDocumentEncoder back into their documents.

Each blob is read once per decoder, with read_blob.

Parameters:

read_blob (Callable[[str], bytes]) – Returns a blob’s compressed bytes, by its digest. It raises KeyError if there is no such blob.

__init__(read_blob)[source]
decode(skeleton)[source]

Return the document of a skeleton.

Parameters:

skeleton (JsonValue) – The skeleton, as JournalDocumentEncoder.encode() returned it.

Return type:

JsonValue

Returns:

The document.

Raises:

JournalStorageError – If a blob that the skeleton references is missing.

load(digest)[source]

Return a blob’s value, still encoded.

Parameters:

digest (str) – The blob’s digest.

Return type:

JsonValue

Returns:

Its value.

Raises:

JournalStorageError – If there is no such blob.

class smarter.lib.journal.storage.JournalDocumentEncoder[source]

Encodes documents into skeletons and blobs.

One encoder may encode several documents, e.g. an entry’s request and response, which then share their blobs. After encoding, blobs holds each blob’s compressed bytes, by digest: every blob of the documents, of which the database may already have some.

Example:

encoder = JournalDocumentEncoder()
skeleton = encoder.encode(response)
SAMJournalBlob.objects.save_blobs(encoder.blobs)
stored = pack(skeleton)
__init__()[source]
encode(document)[source]

Return a document’s skeleton, adding its blobs to blobs.

The document itself is never a blob: it is unique to its entry, so the skeleton stays in the entry’s row.

Parameters:

document (JsonValue) – The document, as JSON.

Return type:

JsonValue

Returns:

The skeleton.

store(value)[source]

Add a value to blobs, and return its digest.

Parameters:

value (JsonValue) – The value, already encoded.

Return type:

str

Returns:

The SHA-256 of its JSON, as hexadecimal.

exception smarter.lib.journal.storage.JournalStorageError(message='')[source]

A journal document could not be decoded, e.g. because a blob that it references is missing.

property get_formatted_err_message

The error message prefix of these errors.

smarter.lib.journal.storage.LIST_MIN_BYTES = 256

A list whose JSON is this long, or longer, is stored as a chain.

smarter.lib.journal.storage.blob_references(value)[source]

Return the blobs that an encoded value references directly: its references and its chains’ last nodes.

The blobs themselves may reference more blobs. See node_references().

Parameters:

value (JsonValue) – A skeleton, or the value of a blob that isn’t a chain’s node.

Return type:

list[tuple[str, bool]]

Returns:

The referenced blobs.

smarter.lib.journal.storage.node_references(node)[source]

Return the blobs that a chain’s node references: its parent, and its item’s blobs.

Parameters:

node (JsonValue) – The node’s value.

Return type:

list[tuple[str, bool]]

Returns:

The referenced blobs, none if the value isn’t a node.

smarter.lib.journal.storage.pack(value)[source]

Return a value’s JSON, compressed: the stored form of a skeleton and of a blob.

Parameters:

value (JsonValue) – The value.

Return type:

bytes

Returns:

The compressed JSON.

smarter.lib.journal.storage.unpack(data)[source]

Return the value of what pack() stored.

Parameters:

data (bytes | bytearray | memoryview) – The compressed JSON. Some database drivers return a memoryview.

Return type:

JsonValue

Returns:

The value.

Journal Sources

Journal sources: parts of a journaled response that the worker reads from the database.

Some responses send data that Smarter has already saved. The largest is an LLMClient’s configuration (/config/), whose data.history.chat_history is the chat session’s whole thread, read from its newest PromptHistory row. Queuing it with the journal entry would carry the thread through the Celery broker on every request. Instead, the response names it with a SAMJournalSourceReference: the source’s name, a lookup of the row, the value’s path in the response, and the SHA-256 of the value as the client received it. The value is left out of the queued entry, and the Celery task reads it back with the source’s resolver.

A source is registered by the app that owns its data, with register_journal_source(), from its AppConfig.ready(), so that the journal never imports the app. A resolver raises JournalSourceNotReady while the row has not been written yet, e.g. because another Celery task writes it, and the journal’s task then retries, for as long as it takes, and JournalSourceGone when the row can never be written, e.g. because its chat session was deleted. A value that is gone is journaled as UNRESOLVED_KEY, with its reference.

Example:

# in the app that owns the data, e.g. smarter.apps.prompt.journal
def resolve_chat_history(lookup):
    row = PromptHistory.objects.filter(pk=lookup["prompt_history_id"]).first()
    if row is None:
        raise JournalSourceNotReady("PromptHistory is not written yet.")
    return ...

register_journal_source("prompt.chat_history", resolve_chat_history)

# in the view
SmarterJournaledJsonResponse(
    request=request,
    data=data,
    journal_sources=[
        SAMJournalSource(
            name="prompt.chat_history",
            path=("data", "history", "chat_history"),
            lookup={"prompt_history_id": row.pk},
        )
    ],
)
exception smarter.lib.journal.sources.JournalSourceGone(message='')[source]

A source’s row can never be read, e.g. because it was deleted.

Its reference is journaled instead.

property get_formatted_err_message

The error message prefix of these errors.

exception smarter.lib.journal.sources.JournalSourceNotReady(message='')[source]

A source’s row is not written yet.

The journal’s task retries until it is.

property get_formatted_err_message

The error message prefix of these errors.

class smarter.lib.journal.sources.SAMJournalSource(*, name, path, lookup)[source]

A part of a journaled response that the worker reads from the database: what a view passes.

model_config = {'extra': 'forbid', 'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

class smarter.lib.journal.sources.SAMJournalSourceReference(*, name, path, lookup, digest)[source]

A source, and the SHA-256 of its value as the client received it: what the journal’s task receives.

model_config = {'extra': 'forbid', 'frozen': True}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

smarter.lib.journal.sources.UNRESOLVED_KEY = '$journal:unresolved'

{"$journal:unresolved": <reference>}.

Type:

The key that stands in for a source’s value that could not be read

smarter.lib.journal.sources.attach_sources(document, references)[source]

Return a document with its sources’ values read back from the database.

Parameters:
Return type:

JsonValue

Returns:

The document as the client received it, or with UNRESOLVED_KEY where a value is gone.

Raises:

JournalSourceNotReady – If a source’s row is not written yet.

smarter.lib.journal.sources.detach_sources(document, sources)[source]

Return a document without its sources’ values, and the references that read them back.

A source whose path the document doesn’t have stays in the document, and gets no reference.

Parameters:
  • document (JsonValue) – The response, as JSON.

  • sources (Sequence[SAMJournalSource]) – The sources that the view named.

Return type:

tuple[JsonValue, list[SAMJournalSourceReference]]

Returns:

The document, with None at each source’s path, and the sources’ references.

smarter.lib.journal.sources.register_journal_source(name, resolver)[source]

Register a source’s resolver, by the source’s name.

Call it from the owning app’s AppConfig.ready(), so that the web server and the Celery workers both have it. Registering a name again replaces its resolver.

Parameters:
Return type:

None

smarter.lib.journal.sources.resolve_source(reference)[source]

Return a source’s value, read from the database.

Parameters:

reference (SAMJournalSourceReference) – The source’s reference.

Return type:

JsonValue

Returns:

The value, or {"$journal:unresolved": <reference>} if it is gone, or isn’t the value that the client received.

Raises:

JournalSourceNotReady – If the source’s row is not written yet.

The prompt app’s journal sources: the data of its responses that the journal reads from the database.

An LLMClient’s configuration (/config/) returns the chat session’s whole thread, read from its newest PromptHistory row. The configuration’s journaled response names it as the CHAT_HISTORY_SOURCE source, so that the thread doesn’t pass through the Celery broker with every request: the journal’s task reads it back here. See smarter.lib.journal.sources.

smarter.apps.prompt.journal.CHAT_HISTORY_PATH = ('data', 'history', 'chat_history')

Where a configuration’s response holds the chat thread.

('data', 'history', 'chat_history')
smarter.apps.prompt.journal.CHAT_HISTORY_SOURCE = 'prompt.chat_history'

The name of the source of a configuration’s data.history.chat_history.

smarter.apps.prompt.journal.MESSAGES_ADAPTER = TypeAdapter(list[PromptChatApiMessage])

a list of the contract’s messages.

Type:

Validates and dumps the thread as the configuration does

smarter.apps.prompt.journal.PROMPT_HISTORY_ID = 'prompt_history_id'

The lookup’s key of the PromptHistory row’s id.

smarter.apps.prompt.journal.PROMPT_ID = 'prompt_id'

it says which session a missing row belonged to.

Type:

The lookup’s key of the row’s Prompt, the chat session

smarter.apps.prompt.journal.chat_history_messages(row)[source]

Return a row’s chat thread, as a configuration’s response holds it.

Parameters:

row (PromptHistory) – The PromptHistory row.

Return type:

JsonValue

Returns:

The thread’s messages, validated by the contract and dumped as JSON.

smarter.apps.prompt.journal.chat_history_source(row)[source]

Return the journal source of a configuration’s chat thread.

Parameters:

row (PromptHistory) – The PromptHistory row that the thread was read from.

Return type:

SAMJournalSource

Returns:

The source, for SmarterJournaledJsonResponse(journal_sources=...).

smarter.apps.prompt.journal.register()[source]

Register the prompt app’s journal sources.

Called by PromptConfig.ready().

Return type:

None

smarter.apps.prompt.journal.resolve_chat_history(lookup)[source]

Read a configuration’s chat thread from its PromptHistory row, for the journal.

Parameters:

lookup (dict[str, str | int]) – The source’s lookup, from chat_history_source().

Return type:

JsonValue

Returns:

The thread, as the client received it.

Raises:

JournalSourceGone – If the row was deleted.

The lookup is the id of a row that the configuration read, so the row was written before the entry was queued, and a missing row was deleted, e.g. with its chat session. It is never JournalSourceNotReady, which would retry forever.

Celery Tasks

Celery tasks of the Smarter Journal.

A journaled response doesn’t write its journal entry: it queues create_journal_entry(), with a SAMJournalEntryRecord, and returns. Encoding and saving the entry’s documents happens in a Celery worker, off the request’s thread.

The parts of a response that Smarter has already saved, e.g. an LLMClient configuration’s chat thread, are not queued: the record names them with references (see smarter.lib.journal.sources), and the task reads them from the database. Their rows may be written by other Celery tasks, so while one is missing, the task retries, with a backoff of up to SOURCE_RETRY_MAX_COUNTDOWN seconds, for as long as it takes.

The entry’s key is chosen before it is queued, so that the response can return it in its metadata. The task is idempotent: a retry of an entry that was saved does nothing.

class smarter.lib.journal.tasks.SAMJournalEntryRecord(*, key, created_at, user_id=None, thing, command, status_code, request, response, sources=<factory>)[source]

A journal entry, as it is queued: the fields of a SAMJournal row.

It travels through the Celery broker as JSON, so the user is its id, and the documents are JSON.

model_config = {'extra': 'forbid'}

Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].

smarter.lib.journal.tasks.SOURCE_RETRY_MAX_COUNTDOWN = 300

The longest wait, in seconds, between two tries of an entry whose source’s row is not written yet.

smarter.lib.journal.tasks.queue_journal_entry(record, sources=())[source]

Queue a journal entry, to be saved by a Celery worker.

The values of the response’s sources are left out of the queued entry, which names them instead, so that data that Smarter has already saved doesn’t pass through the broker.

If the entry can’t be queued, e.g. because the broker is down, the whole entry is saved now instead: the response is slower, but the journal has no gap.

Parameters:
Raises:

Exception – Whatever saving the entry raised, if it couldn’t be queued nor saved.

Return type:

None

smarter.lib.journal.tasks.write_journal_entry(record)[source]

Save a journal entry, unless it is saved already, and send journal_entry_created.

The record’s sources are read from the database first.

Parameters:

record (SAMJournalEntryRecord) – The entry.

Return type:

SAMJournal | None

Returns:

The new entry, or None if an entry with its key existed.

Raises:

JournalSourceNotReady – If a source’s row is not written yet.