Skip to Content
Motoko

@chia1104/motoko-store-mysql

Motoko's MySQL storage and lease on Drizzle: many agent instances in one database, on pi-durable's Storage contract.

Motoko's store on MySQL 8.0.24 or later: storage and a single-writer lease, built on Drizzle. Many agent instances share one fixed set of agent_runtime_* tables in the database the app's pool connects to; each instance (a scope of { kind, name }) gets its own pi-durable Storage, and opening a new one is a row, never DDL.

pnpm add @chia1104/motoko-core @chia1104/motoko-store-mysql mysql2

drizzle-orm is this package's own dependency, so it works whatever Drizzle version the app uses. The app hands over a mysql2 pool (mysql2/promise's, or a callback pool's .promise()) created for Motoko alone with multipleStatements: true (see A pool of its own), with a utf8mb4 connection character set, mysql2's default.

It is a shared-database store of @chia1104/motoko-core/store, like @chia1104/motoko-store-postgres: the lease, the commit protocol and the store's rules are the core's, and this package writes their MySQL statements, the storage's reads, the schema and the migrations. Its error classes are the core's, so instanceof holds across every such store.

Use

import { createAgentRuntime, processHost } from "@chia1104/motoko-core";
import { createMysqlStore } from "@chia1104/motoko-store-mysql";
import mysql from "mysql2/promise";

// Motoko's own pool: see "A pool of its own".
const pool = mysql.createPool({ uri: process.env.DATABASE_URL, multipleStatements: true });
const store = createMysqlStore(pool);

const runtime = createAgentRuntime({ agents, host: processHost(store), models, ports, closeIdleAfterMs: 60_000 });
// Take over what a previous process left; again every lease TTL or so, for one that crashed.
await runtime.recover();

examples/server.ts is a whole server. store behaves as the Postgres store does, and its README describes lease, storage, release(wake), unfinished, erase and deleteScope. What differs on MySQL:

  • MySQL has no RETURNING and no data-modifying CTEs, so a commit's write is a transaction rather than one statement, sent as one multi-statement query: one round trip, as on Postgres. Its first statement is the guard: an UPDATE of the scope's row that advances its counters only while the lease's token is current and unexpired by the database clock and next_seq is unchanged, and stamps a fresh nonce on the row. The plan's rows follow, one multi-row statement per table, each writing only where the row holds that nonce, then a read of the row that says how the write ended. So a refused guard writes nothing, even when another storage under the same lease moved next_seq to the value this write would have left, and a held one locks the scope's row until COMMIT.
  • A statement that fails in the middle of a transaction leaves it open on its connection, so that connection is destroyed, never returned to the pool: the server rolls the transaction back, and the failure is the commit's as any statement's is, an unknown outcome when it is transient.
  • Acquiring a lease is one transaction: an upsert that inserts the scope's row with the lease, or takes the free lease of the row that exists, stamping a nonce of its own on it, then a read of the row, which holds that nonce exactly when the lease is the acquirer's.
  • A writer stalled in the middle of its commit's transaction holds the scope's row, so another holder's takeover waits for that transaction to end (or for innodb_lock_wait_timeout) instead of overtaking it.
  • store.erase() reads what each conversation owns, then deletes it in one transaction, fenced as a commit is and only if no commit changed the scope since the read (its next_seq); after one, it reads again. It takes two round trips, not one: MySQL refuses a DELETE whose subqueries read the table it deletes from, so the deletes cannot find the conversations by themselves.

Round trips, which is what a database across a network charges for, as the tests count them:

OperationRound trips
store.lease()1, held or not: the upsert and the read (with the schema check), as one transaction
store.storage()1
release(wake)1, recording the wake
store.unfinished()1 schema check, then 1 per 500 scopes listed
store.erase()per conversation, 2: the read, then the fence and up to 4 deletes as one transaction (1 when it skips)
store.deleteScope()1 schema check, then 1: the delete and a read that names the holder, as one transaction
a commit2: the read, then the write: the guard, 1 statement per table written and the outcome, as a transaction
a commit whose guard refusesthe same 2: the write's last statement says why
loading a document (findDocument, then document)1: the find reads the content too
lease renewal1 per store per renewIntervalMs; 2 when a lease was not extended, to learn why

A group of batches costs two round trips, however many batches and tables it holds: a streamed chunk (a document delta and the task's checkpoint) is the read, then a write of the guard, two inserts and the outcome. A document copy adds two, since the copy's source is read after the batches before it are written. One question and answer through pi-durable's Harness takes 5 commits and 10 round trips here, as on Postgres.

A renewal reads the leases' rows only when it extended fewer than all of them: reading them in every renewal would cost that read at every interval, to save a round trip only when a lease is lost.

What the statements assume of the server, besides the version: a sql_mode without NO_BACKSLASH_ESCAPES (see below), and, when it writes a binary log, binlog_format ROW (the default) or MIXED. The rows of a commit and the lease's upsert are INSERT ... SELECT ... ON DUPLICATE KEY UPDATE, which MySQL marks unsafe for statement-based logging (note 1592) and MIXED logs as rows.

On this page