Implementation

Documented internals, for contributors. None of these are part of the public API and they can change in any release.

Types

The marker types and the payloads the REST API parses, and how records print.

Base.show — Method
Base.show(io::IO, x::ResultType)

Print a ResultType on one line, such as Metric(loss = 0.5, step = 1). Julia uses this form for records inside vectors and dictionaries, in print, and in string interpolation, so a vector of records lists one record per line and is trimmed to the terminal like any other vector.

source
Base.show — Method
Base.show(io::IO, ::MIME"text/plain", x::T) where {T<:ResultType}

Print a ResultType as its one-line form followed by its fields, aligned in two columns. Status and stage ids carry their enum name, long or multi-line text is cut to its first line, byte arrays show their size, and the User password hash is left out.

source
DearDiary.IterationSnapshotPayload — Type
IterationSnapshotPayload <: UpsertType

Wire format for the snapshot route. Every field is captured locally by the client (since LibGit2 and Pkg operate on the calling process's working tree) and posted to the server to be persisted on the iteration row.

source
DearDiary.MetricBatchPayload — Type
MetricBatchPayload <: UpsertType

Payload for POST /metric/iteration/{iteration_id}/batch. Records many metric values at the same step and recorded_at in a single round-trip.

Fields

  • step::Optional{Int64}: Shared step for all items. When nothing, each key gets its own max(step)+1.
  • recorded_at::Optional{DateTime}: Shared timestamp. When nothing, the server uses now().
  • metrics::Array{MetricBatchItem,1}: The items to insert.
source
DearDiary.type_from_dict — Function
type_from_dict(::Type{T}, data::AbstractDict)::T where {T}

Build an instance of T from data, whose keys may be Symbols or Strings. Missing keys and missing values become nothing for fields that allow it. Every other value is converted to the field type, and an ArgumentError is thrown when that conversion fails.

source

Database and repositories

Backend-agnostic data access over DuckDB. Every statement goes through execute_query or execute_statement.

DearDiary.archive_production_siblings — Function
archive_production_siblings(model_id::AbstractString, excluded_id::AbstractString)::Bool

Demote every ModelVersion under model_id that currently holds PRODUCTION to ARCHIVED, skipping excluded_id. The service layer calls this immediately after promoting a new version to PRODUCTION to restore the "at most one production version per model" invariant.

source
DearDiary.delete — Function
delete(query::AbstractString, id::AbstractString)::Bool

Execute a DELETE for the row identified by id. Returns true on success, false on error.

source
DearDiary.delete_all — Function
delete_all(::Type{<:ModelVersion}, model_id::AbstractString)::Bool

Delete every ModelVersion under model_id in a single statement. Used by the service-layer cascade when a Model is deleted.

source
DearDiary.duckdbify — Function
duckdbify(query::AbstractString)::String

Rewrite :name bind-parameter placeholders to DuckDB's $name form. DuckDB's SQL parser rejects the :name syntax that the rest of the repository (and DBInterface convention) writes, so every query is normalized at this single execute choke point rather than editing each SQL constant. DDL strings contain no : tokens, so this is a no-op for them.

source
DearDiary.execute_query — Function
execute_query(f::Function, query::AbstractString, parameters::NamedTuple=(;))
execute_query(f::Function, db::DuckDB.DB, query::AbstractString, parameters::NamedTuple=(;))

Run query with parameters under the database lock, pass the result to f, destroy the result and the prepared statement, and return what f returned. f must copy what it needs out of the result; the row helpers below build dictionaries from the Julia-owned columns that Tables.columns materialises.

The statement and the result are destroyed here instead of by their finalizers, so nothing but the DB object keeps the instance alive when close_database runs, whatever the thread count. The generic DBInterface.execute(db, sql, parameters) leaves the prepared statement to its finalizer, which is why the statement is prepared and closed explicitly. Without an explicit db, the open database from get_database is used, read under the lock so a concurrent close cannot hand over an instance that is going away.

source
DearDiary.execute_statement — Function
execute_statement(query::AbstractString, parameters::NamedTuple=(;))::Nothing
execute_statement(db::DuckDB.DB, query::AbstractString, parameters::NamedTuple=(;))::Nothing

Run a statement whose rows are not needed, such as an UPDATE, a DELETE, or DDL, through execute_query.

source
DearDiary.fetch — Function
fetch(query::AbstractString, parameters::NamedTuple)::Optional{Dict{Symbol,Any}}

Execute query with parameters and return the first row as a dictionary, or nothing if no row matches.

source
DearDiary.fetch_all — Function
fetch_all(query::AbstractString; parameters::NamedTuple=(;))::Array{Dict{Symbol,Any},1}

Execute query with parameters and return all rows as an array of dictionaries.

source
DearDiary.fetch_children — Function
fetch_children(::Type{<:Iteration}, parent_id::AbstractString)::Array{Iteration,1}

Return the direct children of parent_id ordered by creation date ascending. Used by the service layer's get_child_iterations to walk an HPO sweep or distributed-worker fan-out one level at a time.

source
DearDiary.fetch_count — Function
fetch_count(query::AbstractString; parameters::NamedTuple=(;))::Int64

Run a SELECT COUNT(*) AS count FROM ... query and return the count, or 0 if the query returns no rows.

source
DearDiary.fetch_page — Function
fetch_page(select_query, count_query; parameters, page::Pagination)::@NamedTuple{rows, total}

Execute select_query (with LIMIT :limit OFFSET :offset appended) and count_query in one call. Returns raw dictionaries; concrete entity overloads typically wrap these into a PaginatedResponse.

Arguments

  • select_query::AbstractString: SELECT query without LIMIT/OFFSET; the helper appends them.
  • count_query::AbstractString: COUNT query filtered by the same parameters.
  • parameters::NamedTuple: Filter parameters shared by both queries.
  • page::Pagination: Page bounds.

Returns

A NamedTuple (rows::Array{Dict{Symbol,Any},1}, total::Int64).

source
DearDiary.insert — Function
insert(query::AbstractString, parameters::NamedTuple)::NamedTuple{id::Optional{String},status::DataType}

Execute an INSERT and return the new row id with a status code.

Arguments

  • query::AbstractString: The INSERT query (must use RETURNING id).
  • parameters::NamedTuple: Bind parameters.

Returns

A named tuple (id, status) where status is one of Created, Duplicate, Unprocessable, or Error. On failure id is nothing.

source
DearDiary.next_metric_step — Function
next_metric_step(iteration_id::AbstractString, key::AbstractString)::Int64

Return max(step) + 1 for the (iteration_id, key) series, or 0 when no metric with that key exists yet. Used by create_metric and log_metrics to auto-assign step when the caller does not pass one.

source
DearDiary.row_to_dict — Function
row_to_dict(row)::Dict{Symbol,Any}

Convert a query row (a NamedTuple from Tables.namedtupleiterator) to a dictionary. DuckDB returns SQL NULL as missing, which type_from_dict turns into nothing for nullable fields.

source
DearDiary.seed_default_user — Function
seed_default_user(db::DuckDB.DB)::Nothing

Insert the default admin user if it is not already present. The bcrypt hash and creation timestamp are computed at call time, so this lives outside the SQL migration system (which accepts only static SQL strings). The underlying ON CONFLICT DO NOTHING makes the call idempotent.

source
DearDiary.update — Function
update(query::AbstractString, object::Optional{<:ResultType}; parameters...)::Type{<:UpsertResult}

Execute an UPDATE for object, setting only the non-nothing keyword fields.

Arguments

  • query::AbstractString: UPDATE query with a {fields} placeholder and :id bind.
  • object::Optional{<:ResultType}: The record to update (provides the :id bind value).
  • parameters: Fields to update; nothing values are skipped.

Returns

Updated on success, Unprocessable on constraint violation, or Error on any other failure.

source
DearDiary.with_database_lock — Function
with_database_lock(f::Function)

Run f() while holding the lock that serialises every statement sent to the open DuckDB connection, and return its result.

DuckDB does not accept concurrent use of one connection, while the REST server handles requests on every thread Julia was started with and the dashboard server runs on the interactive thread pool. Each repository helper takes the lock around its own statement. A service takes it around a sequence that must not interleave with other requests, such as a uniqueness check followed by an insert. The lock is reentrant, so nesting is safe.

source

Services

Business rules shared by the routes and the local API.

Base.Dict — Method
Base.Dict(object::Union{ResultType,UpsertType})::Dict{Symbol,Any}

Transform a ResultType or an UpsertType object into a dictionary keyed by field name.

Arguments

  • object::Union{ResultType,UpsertType}: The object to convert.

Returns

A dictionary representation of the object.

source
DearDiary.compare_object_fields — Function
compare_object_fields(object::ResultType; kwargs...)::Bool

Checks if the object fields are different from the provided keyword arguments.

A nothing argument means "leave this field unchanged", so it never counts as a difference. An update whose arguments are all nothing is therefore a no-op.

Arguments

  • object::ResultType: The object to check.
  • kwargs...: The keyword arguments to compare with the object fields.

Returns

true if any of the object fields are different from the provided non-nothing keyword arguments, false otherwise.

source
DearDiary.delete_metrics — Function
delete_metrics(iteration::Iteration)::Bool

Delete all Metric records associated with a given Iteration.

Arguments

  • iteration::Iteration: The iteration whose metrics are to be deleted.

Returns

true if the records were successfully deleted, false otherwise.

source
DearDiary.delete_parameters — Function
delete_parameters(iteration::Iteration)::Bool

Delete all Parameter records associated with a given Iteration.

Arguments

  • iteration::Iteration: The iteration whose parameters are to be deleted.

Returns

true if the records were successfully deleted, false otherwise.

source
DearDiary.get_project_id — Function
get_project_id(experiment::Experiment)::String

Return the Project id that owns the given Experiment.

Arguments

  • experiment::Experiment: The experiment to inspect.

Returns

The owning project id.

source
get_project_id(iteration::Iteration)::Optional{String}

Return the Project id that owns the given Iteration by walking up to its parent Experiment.

Arguments

  • iteration::Iteration: The iteration to inspect.

Returns

The owning project id, or nothing if the parent experiment is missing.

source
get_project_id(parameter::Parameter)::Optional{String}

Return the Project id that owns the given Parameter by walking up to its parent Iteration and Experiment.

Arguments

  • parameter::Parameter: The parameter to inspect.

Returns

The owning project id, or nothing if any ancestor is missing.

source
get_project_id(metric::Metric)::Optional{String}

Return the Project id that owns the given Metric by walking up to its parent Iteration and Experiment.

Arguments

  • metric::Metric: The metric to inspect.

Returns

The owning project id, or nothing if any ancestor is missing.

source
get_project_id(resource::Resource)::Optional{String}

Return the Project id that owns the given Resource by walking up to its parent Experiment.

Arguments

  • resource::Resource: The resource to inspect.

Returns

The owning project id, or nothing if the parent experiment is missing.

source
get_project_id(model::Model)::String

Return the Project id that owns the given Model.

Arguments

  • model::Model: The model to inspect.

Returns

The owning project id.

source
get_project_id(version::ModelVersion)::Optional{String}

Return the Project id that owns version by walking up to its parent Model.

Arguments

  • version::ModelVersion: The version to inspect.

Returns

The owning project id, or nothing if the parent model is missing.

source
get_project_id(::Type{T}, request::HTTP.Request)::Optional{String} where {T}

Resolve the Project id that scopes a request to entity type T. Each method matches the URL pattern of the route family (/experiment/..., /iteration/..., etc.) and walks the entity hierarchy via the service-layer get_project_id overloads.

Arguments

  • ::Type{T}: The entity type the route operates on (Project, Experiment, Iteration, Metric, Parameter, Resource, Model, ModelVersion, Tag, or UserPermission).
  • request::HTTP.Request: The incoming HTTP request.

Returns

The owning project id, or nothing if it cannot be resolved (URL does not match a known pattern or an ancestor record that no longer exists).

source

REST routes

Route registration, middlewares, and helpers that turn service results into HTTP responses.

DearDiary.error_response — Function
error_response(::Type{<:ErrorCode}, message::AbstractString; status)::HTTP.Response

Build an error response with the standard {"code": ..., "message": ...} envelope.

Arguments

  • ::Type{<:ErrorCode}: The stable identifier as a type tag (see error_code).
  • message::AbstractString: A human-readable description for logs and (optionally) UI fallback.
  • status: HTTP status code (passed through to Oxygen.json).

Returns

An HTTP response with JSON body and the given status.

source
DearDiary.find — Function
find(form_data::AbstractArray{HTTP.Multipart,1}, field_name::AbstractString)::Union{HTTP.Multipart,Nothing}

Return the first part in form_data whose name equals field_name, or nothing if absent.

source
DearDiary.get_status_by_upsert_result — Function
get_status_by_upsert_result(UpsertResult)::HTTP.StatusCodes

Return the HTTP status code for a given UpsertResult.

  • Created → HTTP.StatusCodes.CREATED
  • Updated → HTTP.StatusCodes.OK
  • Duplicate → HTTP.StatusCodes.CONFLICT
  • Unprocessable → HTTP.StatusCodes.UNPROCESSABLE_ENTITY
  • Error → HTTP.StatusCodes.INTERNAL_SERVER_ERROR
source
DearDiary.issue_token — Function
issue_token(user::User)::Dict{String,Any}

Mint a fresh JWT for user and assemble the standard auth response envelope.

Arguments

  • user::User: The authenticated user the token represents.

Returns

A Dict with access_token, token_type, expires_at (Unix epoch seconds), and a sanitized user payload, matching the shape returned by POST /auth and POST /auth/refresh.

source
DearDiary.parse_pagination — Function
parse_pagination(request::HTTP.Request; default_limit::Integer=50, max_limit::Integer=200)::Pagination

Read ?limit= and ?offset= from the request's query string and produce a Pagination.

Missing parameters fall back to the defaults; non-integer or negative values are clamped to the nearest valid bound. limit is capped at max_limit so a client can't request unbounded pages.

Arguments

  • request::HTTP.Request: The incoming request.
  • default_limit::Integer: Default page size when ?limit= is not provided.
  • max_limit::Integer: Hard cap on the requested page size.

Returns

A Pagination bounded to non-negative offset and [0, max_limit] limit.

source
DearDiary.path_segments — Function
path_segments(request::HTTP.Request)::Vector{String}

Return the URL path segments of request, stripped of any query string.

Route-specific middleware runs before Oxygen binds path params to request.context, so HTTP.getparams is not yet populated. Parsing request.target directly keeps this middleware decoupled from Oxygen's request lifecycle.

Arguments

  • request::HTTP.Request: The incoming HTTP request.

Returns

The non-empty /-separated segments of the request path.

source
DearDiary.ProjectPermissionRequiredMiddleware — Function
ProjectPermissionRequiredMiddleware(::Type{T}, ::Type{A})::Function where {T, A<:PermissionAction}

Return a middleware that enforces a PermissionAction against the UserPermission row tying the current user to the Project owning an entity of type T.

T drives get_project_id via multiple dispatch to walk path params and the entity hierarchy. A drives has_permission via multiple dispatch to check the matching boolean field on UserPermission.

Admins bypass the check. When auth is disabled, the default admin user is injected, matching the fallback used by AdminRequiredMiddleware.

Arguments

  • ::Type{T}: The entity type the route operates on.
  • ::Type{A}: The required CRUD action, passed as a type tag (CreatePermission, ReadPermission, UpdatePermission, DeletePermission).

Returns

A middleware with signature (handle::Function) -> (HTTP.Request) -> response.

source
DearDiary.SameUserOrAdminRequiredMiddleware — Function
SameUserOrAdminRequiredMiddleware(handle::Function)::Function

Middleware that passes only when the authenticated user matches the target id or is an admin.

Reads the target user id from the URL path (/user/{id}) using path_segments, because Oxygen binds request.context[:params] only when the registered handler runs, after route-level middleware.

source

Configuration

DearDiary.load_config — Function
load_config(file::AbstractString)::APIConfig

Load environment variables from a file.

Arguments

  • file::AbstractString: The path to the file containing environment variables.

Returns

An APIConfig object containing the loaded environment variables.

source

HTTP client

The HTTP layer behind the Client methods.

DearDiary._json — Function
_json(response::HTTP.Response)::Dict{String,Any}

Decode an HTTP response body as JSON into a Dict{String,Any}.

source
DearDiary._paginated — Function
_paginated(::Type{T}, dict::AbstractDict)::PaginatedResponse{T}

Build a PaginatedResponse for T from the standard {data, total, limit, offset} envelope returned by paged list routes.

source
DearDiary._request — Function
_request(client, method, path; query, body, multipart)::HTTP.Response

Internal request helper. Adds the bearer token (when set), encodes the body, and translates any non-2xx response into a ClientError carrying the server's stable code/message. Successful responses are returned raw so callers can choose how to decode the body (JSON, bytes).

source

Artifact storage

DearDiary._default_s3_transport — Function
_default_s3_transport(method, url, headers, body)

Default HTTP transport that hands the request off to HTTP.request with status_exception=false so 4xx/5xx responses surface as data, not exceptions.

source
DearDiary.sigv4_sign! — Function
sigv4_sign!(headers, method, url, body, region, service, access_key, secret_key, ts)

Mutate headers so the request is AWS SigV4-signed. After this returns, headers carries the Host, X-Amz-Date, X-Amz-Content-Sha256, and Authorization headers that AWS S3 and MinIO expect.

ts must be a UTC DateTime; the timestamp is encoded as ISO 8601 basic format.

This is a minimal implementation: path-style URLs only, no query parameters signed, full payload sha256 (no UNSIGNED-PAYLOAD shortcut). That covers PUT/GET/DELETE/HEAD without pulling in the full SigV4 surface area.

source

Reproducibility

DearDiary._git_state — Function
_git_state()::Tuple{String,Bool}

Probe the working tree for git state. Walks up from pwd() looking for a .git directory via LibGit2.GitRepoExt. Returns ("", false) when no repository is reachable, when LibGit2 fails to open it, or when reading HEAD fails.

source
DearDiary._pkg_state — Function
_pkg_state()::Tuple{String,String}

Return the verbatim contents of the active Project.toml and Manifest.toml. Returns empty strings when no active project is set or the manifest has not yet been resolved, so capture stays non-fatal in environments where Pkg state is incomplete.

source

MCP server

The specs behind run_mcp. The ModelContextProtocol extension turns them into tools, resources, and prompts.

DearDiary.mcp_call — Function
mcp_call(spec::MCPToolSpec, backend::MCPBackend, args::AbstractDict)::@NamedTuple{result::Dict{String,Any}, is_error::Bool}

Answer one tool call. A refusal or failure comes back with is_error = true and an "error" message the model can act on, instead of throwing.

source
DearDiary.mcp_prompt_specs — Function
mcp_prompt_specs()::Vector{MCPPromptSpec}

The MCP prompts run_mcp serves: ready-made requests that walk the model through common analyses with the tools.

source
DearDiary.mcp_read — Function
mcp_read(spec::MCPResourceSpec, backend::MCPBackend, vars::AbstractDict)

Read one resource. Returns a JSON-ready Dict or a (bytes, mime_type) tuple, and throws MCPToolError for an unknown id.

source
DearDiary.mcp_resource_specs — Function
mcp_resource_specs()::Vector{MCPResourceSpec}

The MCP resources run_mcp serves. They expose the same records as the read tools under deardiary:// URIs, plus the raw content of artifacts and environment snapshots.

source
DearDiary.mcp_tool_specs — Function
mcp_tool_specs()::Vector{MCPToolSpec}

Every tool run_mcp serves, covering the whole tracking API: projects, experiments, iterations, parameters, metrics, artifacts, tags, the model registry, users, and permissions.

source
DearDiary.MCPPromptSpec — Type
MCPPromptSpec

A prompt served by run_mcp. arguments holds (name, description, required) for each argument, and template is the user message, with {name} placeholders.

source
DearDiary.MCPResourceSpec — Type
MCPResourceSpec

A family of MCP resources served by run_mcp under uri_template (RFC 6570 {var} placeholders). run receives the backend target and the placeholder values and returns a JSON-ready Dict, or a (bytes, mime_type) tuple for raw content.

source
DearDiary.MCPToolError — Type
MCPToolError(message::String)

A refusal the model should read, such as an unknown id. mcp_call returns it as a tool error instead of failing the request.

source
DearDiary.MCPToolSpec — Type
MCPToolSpec

A tool served by run_mcp: its name, the description shown to the model, the JSON Schema of its arguments, its effect (:read, :create, :update, or :delete, which becomes the tool annotations), and the function that answers a call. run receives the backend target (() for the local database, (client,) for a remote server) and the call arguments, and returns a JSON-ready Dict.

source

The dashboard's internals are on Dashboard implementation.