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.
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.
DearDiary.IterationSnapshotPayload — Type
IterationSnapshotPayload <: UpsertTypeWire 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.
DearDiary.MetricBatchItem — Type
MetricBatchItem <: UpsertTypeA single (key, value) pair carried in a MetricBatchPayload.
Fields
key::String: The metric key.value::Float64: The recorded value.
DearDiary.MetricBatchPayload — Type
MetricBatchPayload <: UpsertTypePayload 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. Whennothing, eachkeygets its ownmax(step)+1.recorded_at::Optional{DateTime}: Shared timestamp. Whennothing, the server usesnow().metrics::Array{MetricBatchItem,1}: The items to insert.
DearDiary.ResultType — Type
ResultTypeA marker abstract type for result types.
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.
DearDiary.UpsertType — Type
UpsertTypeA marker abstract type for upsert types.
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)::BoolDemote 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.
DearDiary.delete — Function
delete(query::AbstractString, id::AbstractString)::BoolExecute a DELETE for the row identified by id. Returns true on success, false on error.
DearDiary.delete_all — Function
delete_all(::Type{<:ModelVersion}, model_id::AbstractString)::BoolDelete every ModelVersion under model_id in a single statement. Used by the service-layer cascade when a Model is deleted.
DearDiary.duckdbify — Function
duckdbify(query::AbstractString)::StringRewrite :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.
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.
DearDiary.execute_statement — Function
execute_statement(query::AbstractString, parameters::NamedTuple=(;))::Nothing
execute_statement(db::DuckDB.DB, query::AbstractString, parameters::NamedTuple=(;))::NothingRun a statement whose rows are not needed, such as an UPDATE, a DELETE, or DDL, through execute_query.
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.
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.
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.
DearDiary.fetch_count — Function
fetch_count(query::AbstractString; parameters::NamedTuple=(;))::Int64Run a SELECT COUNT(*) AS count FROM ... query and return the count, or 0 if the query returns no rows.
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 withoutLIMIT/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).
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 useRETURNING 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.
DearDiary.next_metric_step — Function
next_metric_step(iteration_id::AbstractString, key::AbstractString)::Int64Return 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.
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.
DearDiary.seed_default_user — Function
seed_default_user(db::DuckDB.DB)::NothingInsert 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.
DearDiary.SQL_CREATE_SCHEMA_MIGRATIONS — Constant
SQL_CREATE_SCHEMA_MIGRATIONSBootstrap table that records which Migrations have already run against a database. Created on demand by apply_migrations so a fresh DB can be initialised without manual setup.
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:idbind.object::Optional{<:ResultType}: The record to update (provides the:idbind value).parameters: Fields to update;nothingvalues are skipped.
Returns
Updated on success, Unprocessable on constraint violation, or Error on any other failure.
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.
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.
DearDiary.compare_object_fields — Function
compare_object_fields(object::ResultType; kwargs...)::BoolChecks 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.
DearDiary.delete_metrics — Function
delete_metrics(iteration::Iteration)::BoolDelete 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.
DearDiary.delete_parameters — Function
delete_parameters(iteration::Iteration)::BoolDelete 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.
DearDiary.get_project_id — Function
get_project_id(experiment::Experiment)::StringReturn the Project id that owns the given Experiment.
Arguments
experiment::Experiment: The experiment to inspect.
Returns
The owning project id.
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.
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.
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.
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.
get_project_id(model::Model)::StringReturn the Project id that owns the given Model.
Arguments
model::Model: The model to inspect.
Returns
The owning project id.
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.
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, orUserPermission).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).
REST routes
Route registration, middlewares, and helpers that turn service results into HTTP responses.
Core.String — Method
Base.String(::Type{<:UpsertResult})::StringReturn the uppercase string name of an UpsertResult type.
DearDiary.AdminRequiredMiddleware — Function
AdminRequiredMiddleware(handle::Function)::FunctionMiddleware that rejects requests from non-admin users with 403 ADMIN_REQUIRED.
DearDiary.error_response — Function
error_response(::Type{<:ErrorCode}, message::AbstractString; status)::HTTP.ResponseBuild an error response with the standard {"code": ..., "message": ...} envelope.
Arguments
::Type{<:ErrorCode}: The stable identifier as a type tag (seeerror_code).message::AbstractString: A human-readable description for logs and (optionally) UI fallback.status: HTTP status code (passed through toOxygen.json).
Returns
An HTTP response with JSON body and the given status.
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.
DearDiary.get_status_by_upsert_result — Function
get_status_by_upsert_result(UpsertResult)::HTTP.StatusCodesReturn the HTTP status code for a given UpsertResult.
Created→HTTP.StatusCodes.CREATEDUpdated→HTTP.StatusCodes.OKDuplicate→HTTP.StatusCodes.CONFLICTUnprocessable→HTTP.StatusCodes.UNPROCESSABLE_ENTITYError→HTTP.StatusCodes.INTERNAL_SERVER_ERROR
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.
DearDiary.parse_pagination — Function
parse_pagination(request::HTTP.Request; default_limit::Integer=50, max_limit::Integer=200)::PaginationRead ?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.
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.
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.
DearDiary.SameUserOrAdminRequiredMiddleware — Function
SameUserOrAdminRequiredMiddleware(handle::Function)::FunctionMiddleware 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.
DearDiary.setup_auth_routes — Function
setup_auth_routes()Register authentication routes (/auth). Internal use only.
DearDiary.setup_experiment_routes — Function
setup_experiment_routes()Register experiment routes (/experiment). Internal use only.
DearDiary.setup_iteration_routes — Function
setup_iteration_routes()Register iteration routes (/iteration). Internal use only.
DearDiary.setup_metric_routes — Function
setup_metric_routes()Register metric routes (/metric). Internal use only.
DearDiary.setup_model_routes — Function
setup_model_routes()Register model-registry routes (/model). Internal use only.
DearDiary.setup_modelversion_routes — Function
setup_modelversion_routes()Register model-version routes (/modelversion). Internal use only.
DearDiary.setup_parameter_routes — Function
setup_parameter_routes()Register parameter routes (/parameter). Internal use only.
DearDiary.setup_project_routes — Function
setup_project_routes()Register project routes (/project). Internal use only.
DearDiary.setup_resource_routes — Function
setup_resource_routes()Register resource routes (/resource). Internal use only.
DearDiary.setup_tag_routes — Function
setup_tag_routes()Register tag routes (/tag). Internal use only.
DearDiary.setup_user_routes — Function
setup_user_routes()Register user routes (/user). Internal use only.
DearDiary.setup_userpermission_routes — Function
setup_userpermission_routes()Register user-permission routes (/userpermission). Internal use only.
DearDiary.upsert_to_error_code — Function
upsert_to_error_code(result::UpsertResult)::Type{<:ErrorCode}Map a non-success UpsertResult to the matching ErrorCode type so write-outcome failures surface a stable code in the response body.
Passing a successful result (Created or Updated) is a programmer error; the function falls through to ServerError.
Configuration
DearDiary.load_config — Function
load_config(file::AbstractString)::APIConfigLoad 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.
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}.
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.
DearDiary._request — Function
_request(client, method, path; query, body, multipart)::HTTP.ResponseInternal 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).
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.
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.
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.
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.
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.
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.
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.
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.
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.
DearDiary.MCPPromptSpec — Type
MCPPromptSpecA prompt served by run_mcp. arguments holds (name, description, required) for each argument, and template is the user message, with {name} placeholders.
DearDiary.MCPResourceSpec — Type
MCPResourceSpecA 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.
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.
DearDiary.MCPToolSpec — Type
MCPToolSpecA 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.
The dashboard's internals are on Dashboard implementation.