Skip to content

activerecord — Claude guide ​

Rules that bind only inside packages/activerecord. The repo-wide rules, the fidelity standard and the pre-PR checklist are in the root CLAUDE.md, which also keeps every heading below as a pointer so code citations of the form CLAUDE.md, "Section title" resolve. The alternatives tried for each decision are in docs/claude-md-decision-history.md.

Relation is evaluated by an async query (records, and the predicates it carries) ​

Ruby's Relation is an Enumerable, and every call that needs the records themselves reaches them through records (activerecord/lib/active_record/relation.rb:342-345), which calls load (:1179-1186) and runs the query synchronously; an unloaded size is count(:all) and an unloaded empty? is !exists? (:352-369), also synchronous. So a Relation is both the query and its result, and a predicate that needs a second query can run it in place.

In trails the query is awaited, and that costs four shapes Rails has no counterpart for:

  • applyThenable (relation/thenable.ts) / stripThenable (activesupport/lib/strip-thenable.ts). await rel has to evaluate the relation, so Relation.prototype carries then / catch / finally forwarding to toArray(). JS unwraps a thenable returned from an async body, so a builder returning a relation would evaluate it; stripThenable is the then-hiding Proxy view that lets a relation be returned unevaluated (and lets Object#presence answer one).
  • DeferredIdsIn / DeferredIdsNotIn (relation/predicate-builder/deferred-distinct-pk-in.ts). RelationHandler#call (relation/predicate_builder/relation_handler.rb:5-25), Relation#excluding and DisableJoinsAssociationScope#last_scope_chain (associations/disable_joins_association_scope.rb:22-34, whose records.pluck(foreign_key) is a DeferredPluck) need ids only a query can produce, from synchronous Rails bodies. trails parks an Arel::Nodes::In / NotIn subclass carrying the thunks and Relation#_materializeDeferredDistinctPkPredicates drains them on the way to SQL; the pair exists so WhereClause#invert keeps working while the ids are unresolved.
  • The synchronous eager builders behind toSql — Relation#toSql, _buildEagerOperandManager, _applyEagerJoinDependency, _materializeDeferredDistinctPkPredicates, and the ConnectionPool#withConnectionSync call toSql runs them through. Rails' Relation#to_sql (relation.rb:1210-1221) returns a String. Two constraints keep toSql(): string synchronous: _buildEagerOperandManager reads the synchronous this._model.primaryKey (§ "Schema reflection peeks at a warm cache"), so an async builder would break new Post(); and toSql is read from sync paths — relation == and the query-cache key. A synchronous with_connection seam can only serve an already-leased connection, which is exactly what withConnectionSync hands toSql. This ratifies the sync builders and toSql's sync surface only; the synchronous lease stays under the scope boundary of § "Schema reflection peeks at a warm cache".
  • Relation#[Symbol.asyncIterator] (relation.ts). Ruby iterates a relation with each (relation/delegation.rb:101-104), which reads records; for await (const record of rel) is that loop in JS. It awaits toArray() and yields each record, the same evaluation as for (const record of await rel). Kept by the operator's ruling (2026-10-08).

This is a genuine language shortcoming — JS has no synchronous await — and it is ratified repo-wide here. Those names carry @noRailsEquivalent PERMANENT receipts against this section, and toSql's omitted apply_join_dependency / with_connection calls carry @missingRailsCall … — PERMANENT; do not re-derive the decision per call site, and do not file a story to remove them or to make toSql async.

The pool monitor guards only sections that span an await (ConnectionPool's MonitorMixin) ​

Rails' ConnectionPool is a monitor (include MonitorMixin, activerecord/lib/active_record/connection_adapters/abstract/connection_pool.rb:217), and trails' takes that monitor through ruby-compat's synchronize, keyed on the receiver (synchronize.call(this, block) is Ruby's bare synchronize do). A monitor excludes other callers only while its holder is suspended, and a JS body with no await cannot be suspended, so a synchronize do whose trails body is synchronous is already atomic and wrapping it would change only its return type.

  • Ported onto the monitor: checkout's pinned branch (:550-567, awaits verify!, nests inside the pinned connection's lock, keeps the :553 re-check); disconnect (:454), discard! (:485) and clear_reloadable_connections (:507), whose bodies await each connection's close; with_exclusively_acquired_all_connections, because checkout_for_exclusive_access (:802-820) awaits checkout inside the monitor as Rails' attempt_to_checkout_all_existing_connections (:753-800) calls it.
  • Not wrapped: connections (:443) and the queue's synchronize (connection_pool/queue.rb:80-81, a bare block() in queue.ts): no await, and connections is a synchronous reader in Rails. Likewise Engine#app's @app_build_lock (railties/lib/rails/engine.rb:448,516-524): trails' app() builds with no await, so the Mutex#synchronize double-check is not ported. So are ActionCable::Server::Base#worker_pool's and #pubsub's @mutex.synchronize (actioncable/lib/action_cable/server/base.rb:92,97): the adapter file is loaded by an awaited step first, and neither constructor call has an await.
  • A bare block(): GeneratedAttributeMethods::LOCK (activerecord/lib/active_record/attribute_methods.rb:26), taken by define_attribute_methods (:108) and undefine_attribute_methods (:144). Both bodies are synchronous and are reached from new, so the awaited monitor cannot wrap them. LOCK.synchronize calls its block in line, as the queue's does, and the :109 re-check stays inside it.

This is a genuine language shortcoming, ratified repo-wide here. If one of those bodies ever gains an await, it gains the monitor in the same change.

Schema reflection peeks at a warm cache (load_schema!'s schema_cache.columns_hash) ​

Rails' ModelSchema#load_schema! (activerecord/lib/active_record/model_schema.rb:587-597) reads schema_cache.columns_hash(table_name) synchronously, and a cold cache just runs the reflection query in line. In trails a cold cache needs an awaited query and a warm cache needs nothing, so the divergence is confined to the cold path and the settled shape splits it the same way:

  • Warming is an explicit async step. SchemaCache#columnsHash, #primaryKeys and #dataSourceExists are the async ports; loadSchemaFromAdapter (model-schema.ts) warms all three inside a withConnection scope and then enters the single loadSchemaBang body. SchemaReflection#loadAllBang / BoundSchemaReflection#loadAllBang warm a whole pool up front.
  • A booted app warms before user code runs. Rails loads schema lazily on first touch and its active_record.define_attribute_methods initializer (activerecord/lib/active_record/railtie.rb:145-185) is only an eager optimisation that skips development and test (:154-168). A synchronous trails new cannot make the first-touch load, so trailties' active_record.initialize_database awaits loadAllBang (SchemaCache#add_all, schema_cache.rb:396-404) on the pool it just established, in every env but test (skipped for the reason railtie.rb:159-160 gives). Like railtie.rb:175-180, an ActiveRecordError only warns. A pool whose database does not exist yet (database_exists?) is skipped and stays cold, so booting for db:create does not connect and, for SQLite, create the file the task is about to create. The executor warms it once the database exists. Ruled by the operator on 2026-11-25.
  • Synchronous readers peek. SchemaCache#getCachedColumnsHash, #getCachedDataSourceExists, #getCachedPrimaryKeys, #setColumns and SchemaReflection#loadedCache read or seed the memo maps and never query. BoundSchemaReflection forwards the three peeks, so a sync reader spells schemaCache.… as Rails spells schema_cache.….
  • A cold peek answers undefined, never a query. loadSchemaFromCacheSync returns false and leaves the model unloaded, cachedTableExists returns undefined, and getPrimaryKey (attribute-methods/primary-key.ts) falls through to the "id" convention. The one exception is SchemaReflection#getCachedColumnsHash, which reads the columns when the adapter's columns itself answers synchronously (a fake test adapter). It seeds a loaded cache, and with none loaded it memoizes per table without seating a cache, so cache(pool) still runs load_cache; a real adapter's promise is dropped with its rejection handled, and the cold answer stands. An empty column set was rejected because it makes a cold model silently attribute-less; undefined keeps it unloaded so the async warm can still load it.

Scope boundary. This ratifies the schema-cache PEEK only. It does not bless the synchronous lease a peek may sit behind — withConnectionSync (reflectionAdapter, model-schema.ts), acquireConnectionSync (abstract/connection-pool.ts), or the promise arm in abstract/connection-pool/queue.ts's internal poll. Those stay CONVERGEABLE and are owned by their own RFC: a synchronous lease is permanent, and it trips the permanent_connection_checkout = :disallowed flag, which is why loadSchemaFromAdapter wraps its warm in withConnection. Nothing here is a receipt for a new sync lease.

This is a genuine language shortcoming, ratified repo-wide here. The sync schema-cache readers carry @noRailsEquivalent PERMANENT receipts against this section, and a cold-cache undefined at a sync reader is the designed answer, not a bug to re-derive per call site.

The adapter lock defaults to a monitor, not NullLock ​

Rails' AbstractAdapter#initialize ends with self.lock_thread = nil (activerecord/lib/active_record/connection_adapters/abstract_adapter.rb:157), and lock_thread= (:181-191) maps nil to ActiveSupport::Concurrency::NullLock; only a pinned connection gets a real monitor (connection_pool.rb:335). That is safe in Ruby because a lease is per execution context and a thread runs one statement at a time. In JS one async context holds many in-flight promises, so Promise.all([Post.count(), Post.first()]) hands one adapter to two concurrent statements, and nothing in the (faithfully keyed) lease registry serializes them.

So trails' lock field initializer is new LoadInterlockAwareMonitor() (abstract-adapter.ts), where Rails' constructor leaves NullLock, and setLockThread stays a faithful port of lock_thread= — a caller that passes null still gets NullLock; the constructor simply does not make that call.

The same gap reaches the monitor's reentrant arm. Ruby's monitor is owned by a thread, so a re-entry is always nested in the holder's own call; a Promise.all inside withinNewTransaction starts sibling calls that share the holder's async context. So ruby-compat's synchronize (monitor.ts) runs each entry under an owner of its own and serializes re-entries under one holder: a nested call re-enters at once, siblings take turns. A pinned connection's ThreadLoadInterlockAwareMonitor (concurrency/load_interlock_aware_monitor.rb:36-68) keeps Rails' @owner / @count / @mutex bodies and runs the block through that same synchronize inside Rails' Thread.handle_interrupt (:18-28). An uncontended entry runs its block before synchronize returns, as a Ruby monitor does: callers that do not await lock.synchronize depend on it. For the same reason SQLite3Adapter#disconnectBang closes the handle under lock, where Rails' disconnect! (sqlite3_adapter.rb:221-226) closes it after super releases @lock. SQLite3Adapter#active answers under lock too, where Rails' active? (sqlite3_adapter.rb:210-215) takes none, so a verify! cannot answer while a reconnect! is inside reset_transaction's block; the operator ruled that placement on 2026-10-11, in the tasks-repo story pin-connection-runs-verify-and-begin-under-an-invented-adapter-lock (RFC 0156).

This is a genuine language shortcoming, ratified repo-wide here. Stories that serialize adapter access build on the monitor default; none of them is a story to restore NullLock.

inherited is deferred to own-property memo guards (ModelSchema.inherited) ​

Eight modules under ActiveRecord::Base define inherited, and each runs at class-definition time, super first: Core (activerecord/lib/active_record/core.rb:412-430), AttributeMethods (attribute_methods.rb:265-272), PrimaryKey (attribute_methods/primary_key.rb:143-150), Persistence (persistence.rb:301-307), Inheritance (inheritance.rb:287-294), ModelSchema (model_schema.rb:574-580), Reflection (reflection.rb:142-147) and Locking::Optimistic (locking/optimistic.rb:194-199). Between them they reset a subclass's memos to nil or a default and seed two things: the find-by statement cache and the generated modules. JS has no definition-time hook, and a static read on the child walks the prototype chain to the parent's value.

The whole chain is ported as the own-property guard the root CLAUDE.md ratifies. No link is ported as a method, and nothing dispatches the chain. Ruled by the operator (2026-10-09), over a single first-read dispatch on Base that would run each ported link in Rails' order: that needs every ivar below to be an accessor that triggers it, and a reset that runs at first read clobbers what the class body already wrote.

  • An ivar a link resets is answered only when it is an own property of the class being asked. An inherited value reads as the reset one: nil, so the memo is rebuilt (_arelTable, _predicateBuilder, _inspectionFilter, _attributeNamesMemo, _finderNeedsTypeCondition, _queryConstraintsList, and through ownSchemaMemo in model-schema.ts the schema memos _schemaLoaded, _columnsHash, _columns, _attributesBuilder and _yamlEncoder), or the link's default (_lockingColumn reads DEFAULT_LOCKING_COLUMN, _hasQueryConstraints and _aliasAttributesMassGenerated read false).

  • An ivar a link leaves alone when it is set (@filter_attributes ||= nil, @generated_association_methods ||= nil) is the same own-property read, and the reader's own Rails body does the rest: filter_attributes asks the superclass (core.rb:349-355).

  • What a link seeds is seeded at the subclass's first read.cachedFindByStatement calls initializeFindByCache when the class has no own _findByStatementCache, and generatedAttributeMethods (attribute-methods.ts) calls initializeGeneratedModules when it has no own _generatedAttributeMethods. That reader is the one seed site: generatedAssociationMethods and encryption's overrideAccessorsToPreserveOriginal call it first, so the attribute module is included before the association one, as attribute_methods.rb:42-50 orders them. set_base_class is seeded the same way by baseClass, and _typeCandidatesCache by its reader.

  • A parent is seeded by its own first read, not by its child's. Rails runs each class's links once, in definition order. Here a leaf read before its parent seeds only the leaf, and the parent's later read does not disturb it. core.trails.test.ts covers a three-level hierarchy read leaf first.

  • Reflection's @__reflections is a WeakMap keyed by the class (reflection.ts), which is per-class without a guard.

  • Enum.inherited (enum.rb:289-292) is a ninth, reached through extend Enum rather than Base's own chain. It gives a subclass a defined_enums.deep_dup; _enum (enum.ts) makes that copy at the class's first enum, while it still holds its superclass's hash. A subclass that declares no enum reads its parent's hash, so it also sees an enum the parent declares after it was defined, where Rails' snapshot would not.

  • Migration.inherited (migration.rb:617-626) is outside Base's chain and resets nothing: it raises StandardError when a class whose superclass is Migration is defined. The operator ruled on trails#8789 (2026-10-11) that a direct extends Migration raises as Rails does. With no definition-time hook the raise is deferred to Migration's constructor, at the first new of such a class, with Rails' message. A direct subclass that is never constructed does not raise, and the port of test_legacy_migrations_raises_exception_when_inherited (migration/compatibility_test.rb:209-214) constructs the class where Rails' test only defines it. Migration::Current (migration.rb:579) is defined before the hook and so never raises in Rails; the constructor names Current and leaves it alone, an arm Rails gets from definition order, and every Compatibility::V* descends from it. A migration extends Migration.Current or Migration.get(x.y).

One thing Rails does at definition time reaches other classes: Core's loop that re-initializes every ancestor's find-by cache up to the base class (core.rb:409-421). A guard on the child cannot drop a parent's memo, so it runs where trails first learns of the child: DescendantsTracker.registerSubclass, on a new edge, calls the parent's ruby-compat inherited hook, and Base's is _inherited (core.ts). A parent's cached statements bake its type condition over descendants, which only that registration changes, so the reset is exactly as fresh as what the parent can see. Registration is not definition: a model is registered by trailties' _registerAutoloaded, at its own first _defaultAttributes read, or by an explicit registerSubclass, so a class X extends Firm {} nothing has touched is neither in Firm's type condition nor resets its cache, where Rails' definition does both. _inherited is the only [inherited] on Base's chain (every other link is a guard), so it has no super to call; a second link installed there must chain to it. Ruled by the operator on 2026-11-11.

The guard is the port of inherited, not a deviation to retire. Where the arms report flags a guarded read or a first-read seed in one of these readers, it carries @inventedArm … — PERMANENT against this section.

A model is seated by the loader or constSet (the class keyword's constant and its inherited) ​

A Ruby class Foo < ActiveRecord::Base does two things at the class keyword. It binds the constant Foo, which is what compute_type (activerecord/lib/active_record/inheritance.rb:242-268) and constantize later resolve a class_name: or a stored STI / polymorphic type against. And it makes Foo a subclass of its parent as Ruby sees it: inherited (inheritance.rb:287-294) fires, and Foo is in the parent's Class#subclasses, which DescendantsTracker reads.

A JS class Foo extends Base {} does neither, so each half has its own port (RFC 0213):

  • The constant. An application model is seated by Zeitwerk (root § "The application loader is Zeitwerk"). A framework class is seated on its namespace. A class no loader manages is seated with constSet(TopLevel, "Post", Post), the keyword's own rb_const_set, or constSet on its namespace. A reader asks constantize.
  • The subclass. _defaultAttributes registers a model on its first read, by own-property memo (attributes.ts). A parent's descendants cannot see a child nothing has read, so trailties' _registerAutoloaded registers each model the loader seats, and a test that needs it calls DescendantsTracker.registerSubclass.

A create path awaits its block before saving (create's &block) ​

Rails' create paths yield the caller's block synchronously while building the record and save only afterwards: Persistence::ClassMethods#create / create! (activerecord/lib/active_record/persistence.rb:33-58) call new(attributes, &block) before save, CollectionAssociation#_create_record (associations/collection_association.rb:353-373) calls build_record before opening transaction, and SingularAssociation#_create_record (associations/singular_association.rb:67-73) calls it before record.save. So a block that queries sees the pre-INSERT state (has_many_associations_test.rb:2727-2745), and a block that assigns sees its writes saved.

In trails a block that does I/O returns a promise, and the build it runs inside is synchronous, so the promise escapes it and races the save. The settled shape is the captured-and-awaited block: each async create path captures the block's return value (yielded = block(record)) and awaits it after the build and before the save — create / createBang in persistence.ts, CollectionAssociation#_createRecord and SingularAssociation#_createRecord, each typing its block (record) => void | Promise<void>. Relation#create reaches the first through currentScopeRestoringBlock, which returns the block's value as relation.rb:1344-1350 does. The synchronous builders (new, build) do not await: they have nothing to order a promise against, and a JS constructor cannot await.

A writer that must await, such as has_one_attached's setAvatar (activestorage/lib/active_storage/attached/model.rb:118-125), takes the same shape. awaitingAssignment (activemodel/lib/attribute-assignment.ts) wraps the build in each create path, and the constructor's assignAttributes hands it the writer's promise instead of raising. The caller awaits the assignment, then the block, before saving, and nothing is parked on the record. new and build still raise. The constructor hands the block and _runInitializeCallbacks to deferringToAssignment, so they run after the writer and any key following it, in Rails' order.

This is a genuine language shortcoming — JS has no synchronous await — ratified repo-wide here. This section is the wrapper's receipt: the wrapper raises no call or argument row, so no JSDoc tag applies.

Trilogy is out of scope (trilogy_adapter.rb, adapters/trilogy/) ​

Rails ships a second MySQL adapter over Trilogy, a C client library with Ruby bindings. Trilogy has no Node client and trails will not port it: a TrilogyAdapter built on the mysql2 npm driver would be a second Mysql2Adapter under a Rails name that means "not mysql2". MySQL goes through Mysql2Adapter.

  • trilogy_adapter.rb, adapters/trilogy/ and trilogy_adapter_test.rb stay in scripts/parity/unported-files/unscoped.ts, and their rows are permanent — not a burndown row, and not covered by the "a documented deviation is debt" rule.
  • Out of scope means the adapter, not the name: register_task(/trilogy/, ...) (activerecord/lib/active_record/tasks/database_tasks.rb:79) and anything that only routes the "trilogy" adapter string is ported in full.
  • A Rails body or test that needs a live Trilogy connection — branching on current_adapter?(:TrilogyAdapter), or rescuing a Trilogy:: error — ports its mysql2 arm and drops the trilogy one; this is the one adapter where dropping an adapter arm is correct.
  • There is no story to port it. Do not file one, claim one, or un-exclude the files to "measure" them.

This is an ecosystem gap rather than a TypeScript language shortcoming, and it is ratified repo-wide here (operator, trails#8579).

ActiveRecord::Promise is the native promise (promise.rb, Promise::Complete) ​

Rails' ActiveRecord::Promise (activerecord/lib/active_record/promise.rb) is a BasicObject over a thread-backed FutureResult whose value (:20-29) blocks until the query completes; Promise::Complete (:63-81) is the same surface over a value already there, returned by the async_* readers when there is no query to wait for. The native JS promise is the port.promise.rb is not ported and stays in scripts/parity/unported-files/unscoped.ts; every async_* reader returns a native promise, and so does the reader it wraps. A complete port was written and dropped on the maintainer's decision (2026-10-01): value cannot be ported, an async function unwraps any thenable it returns, and with both pluck and async_pluck awaited there is nothing left to tell apart.

As a consequence:

  • A Rails Promise.new, Promise::Complete.new or Promise.wrap call is omitted and the value returned as it is. It needs no receipt: the parity extractor drops those sites by receiver (native_promise_call?, scripts/api-compare/extract-ruby-api.rb). Do not write @missingRailsCall new or @missingRailsCall wrap for one.
  • An arm that does something else is kept: StatementCache#execute keeps its async: kwarg and dispatches to async_find_by_sql (statement_cache.rb:149-153).
  • A conditional whose arms differ only in the wrap collapses to its value: async ? Promise.wrap([]) : [] is return [].
  • Promise#pending?, #value and #inspect have no counterpart. A Rails test asserting on one ports the assertions that await the value and drops the rest, citing this section.

This is a genuine language shortcoming, ratified repo-wide here. There is no story to port ActiveRecord::Promise or Promise::Complete.

Adapter facts are prewarmed and peeked (lookup_cast_type, max_identifier_length, quote_string) ​

Some synchronous Rails bodies ask the adapter a question only the server can answer, and ask it in line:

  • PostgreSQL::Quoting#lookup_cast_type (activerecord/lib/active_record/connection_adapters/postgresql/quoting.rb:195-197) is super(query_value("SELECT #{quote(sql_type)}::regtype::oid", "SCHEMA").to_i), reached from the String-returning quote_default_expression (abstract/quoting.rb:157-164).

  • PostgreSQLAdapter#max_identifier_length (postgresql_adapter.rb:620-622) memoizes query_value("SHOW max_identifier_length", "SCHEMA"). It is PostgreSQL's table_alias_length, which JoinDependency#initialize reads inside the synchronous eager builders § "Relation is evaluated by an async query" ratifies.

  • quote_string (postgresql/quoting.rb:127-131, abstract_mysql_adapter.rb:695-699) escapes through with_raw_connection { |connection| connection.escape(s) }. It is reached from Quoting#quote, Sanitization and the Arel visitor behind to_sql.

  • InsertAll#primary_keys (insert_all.rb:61-63) reads @model.schema_cache.primary_keys(model.table_name), and InsertAll#initialize reads it and supports_insert_returning? (:39).

  • sql_for_insert (activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb:702-717) reads supports_insert_returning?, which is a database_version comparison on SQLite and MySQL, and for a nil pk runs primary_key(table_ref), a query.

  • PostgreSQL::Quoting#lookup_cast_type_from_column (postgresql/quoting.rb:189-192) runs verify! if type_map.nil?, which connects and loads the type map before the lookup.

  • AbstractMysqlAdapter#mismatched_foreign_key (abstract_mysql_adapter.rb:1001-1015), reached from translate_exception (:832-835), merges mismatched_foreign_key_details into the error, and that reads the referenced primary-key column through column_for (:995).

In trails each answer is a query or a connection round-trip, and those are awaited. The settled shape is the one § "Schema reflection peeks at a warm cache" records for the schema cache: an explicit async step warms the fact, and the synchronous body peeks at the warmed value.

  • warmMaxIdentifierLength runs the SHOW, and maxIdentifierLength reads the memo, answering PostgreSQL's default of 63 while it is cold.

  • The PostgreSQL type map and its regtype OIDs are warmed when the connection is configured and by reloadTypeMap. lookupCastType reads them, and a type created after the warm-up resolves to ValueType where Rails returns the registered type. A quote_default_expression on a ColumnDefinition (no array?, postgresql/quoting.rb:156-167) therefore runs one SCHEMA query fewer than Rails, so a PostgreSQL assert_queries_count(..., include_schema: true) over it (BulkAlterTableMigrationsTest, migration_test.rb:1404,1435) asserts Rails' count less one, keeping Rails' table; the other adapters keep Rails' exact count.

  • quoteString escapes in process. PostgreSQL doubles the quote; MySQL reads the warmed NO_BACKSLASH_ESCAPES state to choose between doubling the quote and backslash escaping, which is the arm connection.escape takes inside the client library.

  • InsertAll awaits its facts before construction, and primaryKeys returns the warmed list.

  • supportsInsertReturning reads the pool's memoized server version, which configureConnection warms through checkVersion. sqlForInsert is synchronous and peeks the schema cache for a nil pk. execInsert, its one caller, awaits databaseVersion and then Rails' own primaryKey(tableRef) query and passes the answer in, so the statements logged are the ones exec_insert (database_statements.rb:157-160) logs. Warming through schemaCache.primaryKeys was rejected: it adds a data_source_exists? query and memoizes, which SQLite3AdapterTest#test_insert_logged sees. The operator ruled that sqlForInsert returns synchronously under this section (2026-10-08, story converge-sql-for-insert-and-supports-insert-returning-to-sync), and the warm step in execInsert is the permanent consequence.

  • lookupCastTypeFromColumn keeps Rails' line and cannot await it. On a cold type map it starts verifyBang and the lookup raises TypeError off the unset map. That TypeError is the error the caller sees, where Rails raises ConnectionNotEstablished from verify!: the started verify has not settled when the lookup runs, so its failure cannot be the one raised. The started promise carries a handler that drops its rejection, so a failed connect is not also an unhandled rejection. A caller that can reach it on a connection nothing has verified warms first, awaiting verifyBang when the type map is unset, and that await is where the connection error surfaces. There are three warm steps. buildFixtureSql is the first. loadSchemaFromAdapter is the second: a schema cache loaded from a dump answers its columns with no query, so nothing has verified the connection when loadSchemaBang reaches typeForColumn. A failed verify is raised from that step, including where the step drops a failed reflection. ConnectionPool::ExecutorHooks.run, a no-op in Rails (connection_pool.rb:194-196), is the third: active_record.clear_active_connections (railtie.rb:299-311) flushes the boot connection, and a model read then peeks the warm schema cache through a fresh lease with no async step before it. So each executor run verifies a connection on every pool that holds a loaded schema cache and no connection, and a failed connect is raised from that await. A pool with no loaded cache cannot reach the peek, and stays unconnected as Rails leaves it.

  • mismatchedForeignKey has no fact to warm, because the table and column are only known once the failed statement is in hand. It is the one member here that answers a value or a promise of it: the sql arm returns a promise of the MismatchedForeignKey, and the query_parser arm returns the error itself, whose setQuery awaits the details. Both are reached only through translateExceptionClass and log, which await.

The alternative is making the callers async, which is the cascade through quote, the Arel visitor and to_sql that § "Relation is evaluated by an async query" rejects.

This is a genuine language shortcoming, ratified repo-wide here. The omitted query_value, quote, with_raw_connection and table_name calls carry @missingRailsCall … — PERMANENT, warmMaxIdentifierLength carries @noRailsEquivalent PERMANENT, and MySQL's escape-state arm carries @inventedArm if — PERMANENT, buildFixtureSql's warm step carries @inventedArm if / verifyBang — PERMANENT, and mismatchedForeignKey's promise arm carries @inventedArm then — PERMANENT, sqlForInsert's omitted primary_key carries @missingRailsCall … — PERMANENT, and execInsert's warm step carries @inventedArm if / databaseVersion / supportsInsertReturning / primaryKey — PERMANENT, all against this section. A new instance is not a new decision to argue.

Fixtures load from .ts modules as well as YAML (FixtureSet::File) ​

Rails reads a fixture file through FixtureSet::File#raw_rows (activerecord/lib/active_record/fixture_set/file.rb:51-53), which is ActiveSupport::ConfigurationFile.parse over YAML. trails also accepts a fixture as a .ts module registered through File.registerModule, and the canonical test fixtures ship that way.

The registry stays. A YAML-free ActiveRecord boot is a requirement (RFC 0170), and with the registry gone npm yaml would be the only fixture path. File.registerModule and File.modules carry @noRailsEquivalent PERMANENT against this section, and there is no story to convert the fixtures to .yml.

Call-time constant resolution (activerecord) ​

The activerecord inventory for root CLAUDE.md § "Call-time constant resolution". activerecord/lib/namespaces.ts holds the ActiveRecord, ActiveRecord::Associations, ActiveRecord::ConnectionAdapters, ActiveRecord::Encryption and ActiveRecord::Tasks namespace objects, extended with ActiveSupport::Autoload like arel's, mirroring active_record.rb:43-112, associations.rb:15,29-41 and encryption.rb:10-35. Each constant is seated by the module that defines it.

A seat below is a plain Owner.Name = Klass assignment, and the inventory is of reads that happen at module-eval time. A read inside a function or method body is a plain ES import, correct even inside a cycle, so it is not listed here and does not need a namespace — see root CLAUDE.md § "Call-time constant resolution". constSet appears only where the Rails body calls const_set, and a class's qualified Ruby path is a ruby-compat internal, read only to produce a name (root CLAUDE.md § "Constant lookup is an import or a registry"), not the seat.

The seated constants:

  • ActiveRecord.Base, .Encryption, .Associations, .ConnectionAdapters, .ConnectionHandling (DEFAULT_ENV), .ModelSchema (derive_join_table_name), .Reflection (create, read by Builder::Association.create_reflection, associations/builder/association.rb:40-51), .Migration, .Relation, .AssociationRelation and .DisableJoinsAssociationRelation (read by Delegation.delegated_classes, relation/delegation.rb:7-15), and .Fixture (Rails has no autoload :Fixture; it is defined in fixtures.rb, loaded through autoload :FixtureSet, and its FixtureError is raised at abstract/database_statements.rb:615). ActiveRecord.Point (postgresql/oid/point.rb:4) is required, not autoloaded, and is seated with no autoload call.
  • Associations: the six concrete association ctors AssociationReflection#association_class returns (reflection.rb:889-923), CollectionProxy and DisableJoinsAssociationScope (associations/association.rb:107-115).
  • Encryption: the whole encryption.rb:10-35 eager_autoload list; Configurable and Contexts are extended onto Encryption itself as encryption.rb:47-48 includes them, so readers spell Encryption.config.x; Cipher is itself extended with Autoload for Cipher.Aes256Gcm.
  • ConnectionAdapters: ConnectionPool (read by abstract/query_cache.rb:100) and the module's singleton register / resolve (connection_adapters.rb:22-50, read by database_config.rb:17).
  • Migration is extended with Autoload for Compatibility (migration.rb:573), CommandRecorder, JoinTable, ExecutionStrategy and DefaultStrategy (:572-576); command-recorder.ts reads ActiveRecord.IrreversibleMigration at call time, so it takes no edge back into migration.ts.
  • Tasks (active_record.rb:173-180): DatabaseTasks and the three adapter task classes. migration.ts reads ActiveRecord.Tasks.DatabaseTasks at call time (migration.rb:151-183,696,750,1037-1041,1361-1365), because database-tasks.ts imports migration.ts and connection-handling.ts, and a plain import back re-enters the schema-statements.ts -> migration/command-recorder.ts -> migration.ts cycle.
  • ActiveRecord registers itself with constantize, which walks each further segment through the constant seated on its namespace, as Object.const_get does (inflector/methods.rb:289-291).

The cycles these seats break: base.ts importing every self == Base reader; class SingularAssociation / CollectionAssociation extends Association reaching reflection.ts; builder/singular-association.ts -> builder/association.ts -> reflection.ts -> associations.ts -> builder/has-one.ts, whose class HasOne extends SingularAssociation reads SingularAssociation in TDZ when a builder is the entry module; class AssociationRelation extends Relation; V8_0 = Current; schema-statements.ts -> join-table.ts -> model-schema.ts -> connection-handling.ts -> … -> abstract-adapter.ts, whose module-scope include(AbstractAdapter, SchemaStatements) reads SchemaStatements in TDZ; and query-cache.ts -> connection-pool.ts -> abstract-adapter.ts, whose include(AbstractAdapter, QueryCacheMixin) reads QueryCacheMixin in TDZ.

The two guarded reads. abstract-adapter.ts reads ActiveRecord.Base?.logger ?? null in the constructor (abstract_adapter.rb:132,140) and abstract/query-cache.ts's dirties_query_cache arm reads ActiveRecord.Base?.connectionHandler (abstract/query_cache.rb:24-25). An adapter is a standalone public entry point, constructed and queried with no model layer loaded (the sqlite-drivers lane), so an unseated Base there is a legitimate configuration, not a load-order bug. A read is added to this exception only when that lane is shown to reach it. A seat on the ActiveRecord module itself (active-record.ts, where every active_record.rb:182-491 singleton config seat lives and parity:api records it; Base holds none of them) needs no guard: the module is a plain import and holds the Rails default.

No zero-import slot remains in activerecord.

An adapter file is loaded by an awaited step (ConnectionAdapters.resolve's require) ​

Rails loads an adapter inside ConnectionAdapters.resolve: a synchronous require path_to_adapter under a rescue LoadError (activerecord/lib/active_record/connection_adapters.rb:42-56). resolve is reached synchronously through DatabaseConfig#adapter_class (database_configurations/database_config.rb:17-19) by quoted_table_name (model_schema.rb:286), quoted_primary_key (attribute_methods/primary_key.rb:92) and disallow_raw_sql! (sanitization.rb:183), so it cannot be a promise.

ESM has no synchronous load of a module named by a path: import() is the only one, and it is async. The built-in adapter modules cannot be imported eagerly instead, because postgresql-adapter.ts imports pg and mysql2-adapter.ts imports mysql2/promise, optional peers an application installs one of.

The require is ConnectionAdapters.load(adapterName), an awaited step that runs before resolve. As a consequence:

  • load awaits the import() of the registered path, through ConnectionAdapters.loadPath for a built-in. It holds a failure in the module-private loadErrors, and resolve raises it as Rails' two LoadError messages, at Rails' raise site.
  • resolve is otherwise connection_adapters.rb:26-66: same guards, same order, same messages.
  • ConnectionHandler#resolvePoolConfig calls load before validate! (connection_adapters/abstract/connection_handler.rb:275-280). It is the one step every establish_connection already awaits, so DatabaseConfig#validate! stays Rails' body. Code that builds a PoolConfig without a handler (support/template-global-setup.ts) calls load itself.
  • A built-in's loadPath thunk imports a computed specifier, new URL("./connection-adapters/<file>.js", import.meta.url), so a bundler does not follow it into every optional driver. A bundled app imports the adapter module it is configured with, as a Gemfile names the driver gem; the module seats its class, and load then finds it defined.
  • connection-handler.ts does not import connection-adapters.ts, which re-exports it, as connection_handler.rb is only reached through connection_adapters.rb's autoload. That edge put the two in a cycle in which a Rollup bundle reads ConnectionHandler in TDZ. A module that calls load imports connection-adapters.ts.
  • An adapter registered by a third party is loaded the same way. Outside the handler, the template setup and the per-worker test database setup (test-setup-worker-db.ts), the only callers are tests that build a DatabaseConfig by hand, and no other require is ported as an awaited step on the strength of this section.

This is a genuine language shortcoming, ratified here by the operator (2026-10-08). load carries @noRailsEquivalent PERMANENT and resolvePoolConfig carries @inventedArm load — PERMANENT against this section. There is no story to remove the step.

ActiveRecord::Tasks::DatabaseTasks is loaded the same way. Rails autoloads it (activerecord/lib/active_record.rb:173-179), so migration.rb names it and the file loads on first use, including from MigrationContext's and Migrator's constructors and Migration#connection, which cannot await. resolvePoolConfig awaits ActiveRecord.Tasks.loadPath["active_record/tasks/database_tasks"]() beside load, so every read after establish_connection finds it seated, and no Migration entry point awaits it again. The same @inventedArm load — PERMANENT covers it. Ruled by the operator on 2026-11-26.

A migration file is loaded by Kernel#load (MigrationProxy#load_migration) ​

Rails' MigrationProxy#load_migration (activerecord/lib/active_record/migration.rb:1196-1201) is Object.send(:remove_const, name) rescue nil, load(File.expand_path(filename)), name.constantize.new(name, version). load evaluates the file every time it is called, and the file binds its class as a top-level constant.

ESM keeps one module record per URL, and a module exports its class rather than binding it anywhere. Kernel#load is rbFLoad in ruby-compat (rb_f_load, vendor/ruby/v3.3.11/load.c:903):

  • It awaits an import() of the file under a URL no earlier load used, so a changed file is evaluated again.
  • It seats every constant-named export on TopLevel, where constantize reads it. rbModRemoveConst (rb_mod_remove_const, vendor/ruby/v3.3.11/variable.c:3302) removes one.
  • loadMigration is Rails' three lines in Rails' order and is async, as every caller of MigrationProxy#migration already is.

This is a genuine language shortcoming, ratified here by the operator (2026-10-09). It covers Kernel#load of a file Rails loads by path at run time. A require is not ported this way on the strength of this section; see § "An adapter file is loaded by an awaited step".

A dumped statement wraps its trailing options in braces (SchemaDumper's parts.join(", ")) ​

Rails builds a dumped statement as a list of parts and joins it: " #{parts.join(', ')}" (activerecord/lib/active_record/connection_adapters/postgresql/schema_dumper.rb:44-62,65-82, activerecord/lib/active_record/schema_dumper.rb:290,341). The first part is the call and the rest are keyword arguments, which Ruby writes with no delimiter around them.

trails dumps a TypeScript call. Its trailing options are one object literal, so they need { } exactly when there are any, and a statement with none takes no second argument. The builder keeps one arm for that: parts.length > 0 ? ", { … }" : "". Always emitting the braces was rejected because an option-less statement would dump as t.uniqueConstraint(["a"], {}).

This is a genuine language shortcoming, ratified here by the operator (2026-10-09). The arm carries @inventedArm if — PERMANENT against this section at each builder: exclusionConstraintsInCreate and uniqueConstraintsInCreate in postgresql/schema-dumper.ts, and the base dumper's builders in schema-dumper.ts. It is the brace arm only. Any other extra branch in a builder is still a deviation to converge.

SQLite's busy handler runs between steps (busy_handler, execute_batch2) ​

sqlite3-ruby's busy_handler runs inside the native step (sqlite3 lib/sqlite3/database.rb:692-705). A JS callback there could not await, so a wait would block the event loop holding the lock's other side. retryBusy runs the handler between steps instead, and the driver's own busy_timeout is always 0: timeout waits and yields, retries retries, and a config with neither raises at once. Statements, the configured pragmas and every other driver call the adapter makes go through retryBusy. execBatch splits a batch with sqlite3_complete's state machine and steps each statement, so a retry resumes at the blocked one. SQLite skips the handler where waiting would deadlock, and no driver reports that case apart from an ordinary SQLITE_BUSY, so the adapter tracks it: a write that follows a SELECT or WITH in an open transaction raises at once, including a SELECT that took no lock. A SAVEPOINT after the read clears the tracking, and a -- comment before the SELECT hides it, so those writes wait for the deadline. This is a genuine language shortcoming, ruled permanent by the operator on 2026-11-01 (trails#9582), and @noRailsEquivalent PERMANENT on those functions points at it.

Records are not Proxies (method_missing) ​

Ruby reaches NoMethodError for an undefined name through BasicObject#method_missing, and ActiveRecord regenerates undefined attribute methods from the same hook. So topic.mumbo and topic.mumbo = 5 raise at run time (activerecord/test/cases/attribute_methods_test.rb:641-645), and a read off an existing record after undefine_attribute_methods redefines the reader (attribute_methods_test.rb:1098).

trails enforces both halves at compile time instead: ActiveModel::Model has no [key: string]: unknown index signature, so topic.mumbo does not type-check. An as any cast or a plain-JS caller still evades it, and there it reads undefined / creates an own property.

The only JS read/write hook on an arbitrary name is a Proxy trap, and the converged shape would be a Proxy returned from the constructor standing in for self. The blocker is cost, measured on every ActiveModel instance: a get trap makes an attribute read 3.7× slower and an internal _field read 64× slower, because a proxied object defeats the property-read inlining those reads get, and the internal-field number lands on every framework read, not only user code. Records are not Proxies. As a consequence:

  • An undefined name on a record is a type error, not a NoMethodError, and untyped access reads undefined or silently creates an own property.
  • A generated reader removed by undefineAttributeMethods is not regenerated by reading it off an existing record. It comes back through defineAttributeMethods (activerecord/lib/active_record/attribute_methods.rb:104), or through construction.

The Migration half. Rails' Migration#method_missing (activerecord/lib/active_record/migration.rb:1044-1059) wraps every DSL statement (create_table, add_column, …) in say_with_time and sends it to execution_strategy. trails has no such dispatch, so migration.ts declares typed forwarders, each a this.methodMissing(name, ...args) call. They stay. A Proxy would not buy back extra surface either: typing the proxied statements needs a declaration-merged interface Migration in the same file, whose members parity:api:extra counts exactly as it counts the class members.

This is a genuine language shortcoming, ratified repo-wide here. Tests mirroring the Rails NoMethodError arms port the assertions that do not depend on the hook, and there is no story to proxy records or to replace the Migration forwarders. It does not rule out a Proxy on some other non-record object whose Rails counterpart dispatches through method_missing; that is decided per class (see § "Ruby protocol methods with a different JS mechanism").

A record is built with new Klass only (Inheritance::ClassMethods#new) ​

Ruby has one way to build a record, Klass.new(attributes, &block), and Inheritance::ClassMethods#new (activerecord/lib/active_record/inheritance.rb:56-78) overrides it: it raises NotImplementedError for an abstract class or Base, resolves an STI subclass through subclass_from_attributes, and calls subclass.new or super.

JS builds an object with the new expression, and that is the only spelling trails has. There is no static Klass.new. new Klass(attributes, block) is Rails' Klass.new(attributes, &block), so the body of Inheritance::ClassMethods#new runs in Base's constructor (packages/activerecord/lib/base.ts): the abstract raise, then the three subclass_from_attributes arms in Rails' order, then new subclass(attributes, block) or the rest of the constructor, which is Class#new. A static new beside the constructor was rejected by the operator (trails#8659): it leaves two spellings for one operation, and either the bare new silently skips the abstract check and the STI dispatch, or the constructor has to re-enter the static method through a marker and run twice.

As a consequence:

  • A Rails klass.new(attributes, &block) ports as new klass(attributes, block), in source and in tests. Generated application code says new Post(params) too (trailties/lib/generators/active-model.ts).
  • inheritance.rb's new has no member in inheritance.ts. Do not add one, and do not file a story to move the body out of the constructor.
  • Persistence#becomes (persistence.rb:487-500) is klass.allocate + initialize, which skips Inheritance::ClassMethods#new. It reaches the constructor with _suppressAbstractCheck and _suppressStiNewDispatch set.
  • Relation#new and CollectionProxy#new are instance methods with no new expression to stand in for them, and stay.
  • This rule bounds root CLAUDE.md § "Every promise has an owner; async initialize is an awaited static new": a class whose initialize does async work gets a protected constructor and static async new, but a record never does. Records stay new Klass.
  • A record loaded from the database is built with new too. Rails' instantiate_instance_of is klass.allocate.init_with_attributes(attributes, &block) (persistence.rb:313), which skips initialize. The JS spelling of allocate, Object.create, also skips every class-field initializer, so a model field such as history = [] would be unset on a record find returns. That was tried on trails#8661 and reddened TransactionCallbacksTest on all three adapters. Base.allocate therefore goes through the constructor and carries @noRailsEquivalent PERMANENT, and the arm in Core's constructor that recognises an allocation carries @inventedArm if — PERMANENT.

This is ratified repo-wide here by the operator.

A ClassMethods#new that runs after super (Deduplicable) ​

A runtime fact Node does not expose (root § "Runtime facts Node does not expose").

Deduplicable::ClassMethods#new is super.deduplicate (activerecord/lib/active_record/connection_adapters/deduplicable.rb:13-15), so it runs once, after the most-derived class's whole initialize chain. JS has no hook that runs after the most-derived constructor returns, and a static Klass.new is ruled out (§ "A record is built with new Klass only"). So each includer's or subclass's constructor ends with if (new.target === X) return this.deduplicate();, and a subclass with no Rails initialize (MySQL::Column) is named in its parent's guard rather than given a constructor. Each guard carries @inventedArm if — PERMANENT where the arm gate compares the declaration. Ruled by the operator on 2026-10-27.

SQLite's double-quoted-string setting ​

A runtime fact Node does not expose (root § "Runtime facts Node does not expose").

better-sqlite3 compiles with SQLITE_DQS=0 and no option reaches SQLITE_DBCONFIG_DQS_DDL / _DML, so strict: false cannot re-enable double-quoted string literals on that driver.

method_missing definers in this package ​

Class-specific rules under root § "Ruby protocol methods with a different JS mechanism"; its cross-table rules and docs/method-missing-definers.md apply too.

  • relation/delegation.rb's Proxy sits once above Relation.prototype, so only a lookup that missed the relation's class chain reaches it. Its has trap has no receiver, so in answers neither a name the model's respond_to_missing? claims before that relation method is generated nor Symbol.iterator, which the get trap answers only once the records are loaded synchronously. rbObjRespondTo answers respond_to?. The set trap seats an undefined placeholder for each _ field a relation first writes on a private layer between Relation.prototype and the Proxy, so later writes stop short of the Proxy and a member defined on Relation.prototype later still shadows it.