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 relhas to evaluate the relation, soRelation.prototypecarriesthen/catch/finallyforwarding totoArray(). JS unwraps a thenable returned from anasyncbody, so a builder returning a relation would evaluate it;stripThenableis thethen-hiding Proxy view that lets a relation be returned unevaluated (and letsObject#presenceanswer one).DeferredIdsIn/DeferredIdsNotIn(relation/predicate-builder/deferred-distinct-pk-in.ts).RelationHandler#call(relation/predicate_builder/relation_handler.rb:5-25),Relation#excludingandDisableJoinsAssociationScope#last_scope_chain(associations/disable_joins_association_scope.rb:22-34, whoserecords.pluck(foreign_key)is aDeferredPluck) need ids only a query can produce, from synchronous Rails bodies. trails parks anArel::Nodes::In/NotInsubclass carrying the thunks andRelation#_materializeDeferredDistinctPkPredicatesdrains them on the way to SQL; the pair exists soWhereClause#invertkeeps working while the ids are unresolved.- The synchronous eager builders behind
toSql—Relation#toSql,_buildEagerOperandManager,_applyEagerJoinDependency,_materializeDeferredDistinctPkPredicates, and theConnectionPool#withConnectionSynccalltoSqlruns them through. Rails'Relation#to_sql(relation.rb:1210-1221) returns a String. Two constraints keeptoSql(): stringsynchronous:_buildEagerOperandManagerreads the synchronousthis._model.primaryKey(§ "Schema reflection peeks at a warm cache"), so an async builder would breaknew Post(); andtoSqlis read from sync paths — relation==and the query-cache key. A synchronouswith_connectionseam can only serve an already-leased connection, which is exactly whatwithConnectionSynchandstoSql. This ratifies the sync builders andtoSql'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 witheach(relation/delegation.rb:101-104), which readsrecords;for await (const record of rel)is that loop in JS. It awaitstoArray()and yields each record, the same evaluation asfor (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, awaitsverify!, nests inside the pinned connection'slock, keeps the:553re-check);disconnect(:454),discard!(:485) andclear_reloadable_connections(:507), whose bodies await each connection's close;with_exclusively_acquired_all_connections, becausecheckout_for_exclusive_access(:802-820) awaitscheckoutinside the monitor as Rails'attempt_to_checkout_all_existing_connections(:753-800) calls it. - Not wrapped:
connections(:443) and the queue'ssynchronize(connection_pool/queue.rb:80-81, a bareblock()inqueue.ts): noawait, andconnectionsis a synchronous reader in Rails. LikewiseEngine#app's@app_build_lock(railties/lib/rails/engine.rb:448,516-524): trails'app()builds with noawait, so theMutex#synchronizedouble-check is not ported. So areActionCable::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 anawait. - A bare
block():GeneratedAttributeMethods::LOCK(activerecord/lib/active_record/attribute_methods.rb:26), taken bydefine_attribute_methods(:108) andundefine_attribute_methods(:144). Both bodies are synchronous and are reached fromnew, so the awaited monitor cannot wrap them.LOCK.synchronizecalls its block in line, as the queue's does, and the:109re-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,#primaryKeysand#dataSourceExistsare the async ports;loadSchemaFromAdapter(model-schema.ts) warms all three inside awithConnectionscope and then enters the singleloadSchemaBangbody.SchemaReflection#loadAllBang/BoundSchemaReflection#loadAllBangwarm 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_methodsinitializer (activerecord/lib/active_record/railtie.rb:145-185) is only an eager optimisation that skips development and test (:154-168). A synchronous trailsnewcannot make the first-touch load, so trailties'active_record.initialize_databaseawaitsloadAllBang(SchemaCache#add_all,schema_cache.rb:396-404) on the pool it just established, in every env but test (skipped for the reasonrailtie.rb:159-160gives). Likerailtie.rb:175-180, anActiveRecordErroronly warns. A pool whose database does not exist yet (database_exists?) is skipped and stays cold, so booting fordb:createdoes 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,#setColumnsandSchemaReflection#loadedCacheread or seed the memo maps and never query.BoundSchemaReflectionforwards the three peeks, so a sync reader spellsschemaCache.…as Rails spellsschema_cache.…. - A cold peek answers
undefined, never a query.loadSchemaFromCacheSyncreturnsfalseand leaves the model unloaded,cachedTableExistsreturnsundefined, andgetPrimaryKey(attribute-methods/primary-key.ts) falls through to the"id"convention. The one exception isSchemaReflection#getCachedColumnsHash, which reads the columns when the adapter'scolumnsitself answers synchronously (a fake test adapter). It seeds a loaded cache, and with none loaded it memoizes per table without seating a cache, socache(pool)still runsload_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;undefinedkeeps 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 throughownSchemaMemoinmodel-schema.tsthe schema memos_schemaLoaded,_columnsHash,_columns,_attributesBuilderand_yamlEncoder), or the link's default (_lockingColumnreadsDEFAULT_LOCKING_COLUMN,_hasQueryConstraintsand_aliasAttributesMassGeneratedreadfalse).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_attributesasks the superclass (core.rb:349-355).What a link seeds is seeded at the subclass's first read.
cachedFindByStatementcallsinitializeFindByCachewhen the class has no own_findByStatementCache, andgeneratedAttributeMethods(attribute-methods.ts) callsinitializeGeneratedModuleswhen it has no own_generatedAttributeMethods. That reader is the one seed site:generatedAssociationMethodsand encryption'soverrideAccessorsToPreserveOriginalcall it first, so the attribute module is included before the association one, asattribute_methods.rb:42-50orders them.set_base_classis seeded the same way bybaseClass, and_typeCandidatesCacheby 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.tscovers a three-level hierarchy read leaf first.Reflection's@__reflectionsis aWeakMapkeyed by the class (reflection.ts), which is per-class without a guard.Enum.inherited(enum.rb:289-292) is a ninth, reached throughextend Enumrather thanBase's own chain. It gives a subclass adefined_enums.deep_dup;_enum(enum.ts) makes that copy at the class's firstenum, 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 outsideBase's chain and resets nothing: it raisesStandardErrorwhen a class whose superclass isMigrationis defined. The operator ruled on trails#8789 (2026-10-11) that a directextends Migrationraises as Rails does. With no definition-time hook the raise is deferred toMigration's constructor, at the firstnewof such a class, with Rails' message. A direct subclass that is never constructed does not raise, and the port oftest_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 namesCurrentand leaves it alone, an arm Rails gets from definition order, and everyCompatibility::V*descends from it. A migration extendsMigration.CurrentorMigration.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 ownrb_const_set, orconstSeton its namespace. A reader asksconstantize. - The subclass.
_defaultAttributesregisters a model on its first read, by own-property memo (attributes.ts). A parent'sdescendantscannot see a child nothing has read, so trailties'_registerAutoloadedregisters each model the loader seats, and a test that needs it callsDescendantsTracker.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/andtrilogy_adapter_test.rbstay inscripts/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 aTrilogy::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.neworPromise.wrapcall 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 newor@missingRailsCall wrapfor one. - An arm that does something else is kept:
StatementCache#executekeeps itsasync:kwarg and dispatches toasync_find_by_sql(statement_cache.rb:149-153). - A conditional whose arms differ only in the wrap collapses to its value:
async ? Promise.wrap([]) : []isreturn []. Promise#pending?,#valueand#inspecthave 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) issuper(query_value("SELECT #{quote(sql_type)}::regtype::oid", "SCHEMA").to_i), reached from the String-returningquote_default_expression(abstract/quoting.rb:157-164).PostgreSQLAdapter#max_identifier_length(postgresql_adapter.rb:620-622) memoizesquery_value("SHOW max_identifier_length", "SCHEMA"). It is PostgreSQL'stable_alias_length, whichJoinDependency#initializereads inside the synchronous eager builders § "Relationis evaluated by an async query" ratifies.quote_string(postgresql/quoting.rb:127-131,abstract_mysql_adapter.rb:695-699) escapes throughwith_raw_connection { |connection| connection.escape(s) }. It is reached fromQuoting#quote, Sanitization and the Arel visitor behindto_sql.InsertAll#primary_keys(insert_all.rb:61-63) reads@model.schema_cache.primary_keys(model.table_name), andInsertAll#initializereads it andsupports_insert_returning?(:39).sql_for_insert(activerecord/lib/active_record/connection_adapters/abstract/database_statements.rb:702-717) readssupports_insert_returning?, which is adatabase_versioncomparison on SQLite and MySQL, and for a nilpkrunsprimary_key(table_ref), a query.PostgreSQL::Quoting#lookup_cast_type_from_column(postgresql/quoting.rb:189-192) runsverify! 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 fromtranslate_exception(:832-835), mergesmismatched_foreign_key_detailsinto the error, and that reads the referenced primary-key column throughcolumn_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.
warmMaxIdentifierLengthruns theSHOW, andmaxIdentifierLengthreads 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.lookupCastTypereads them, and a type created after the warm-up resolves toValueTypewhere Rails returns the registered type. Aquote_default_expressionon aColumnDefinition(noarray?,postgresql/quoting.rb:156-167) therefore runs one SCHEMA query fewer than Rails, so a PostgreSQLassert_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.quoteStringescapes in process. PostgreSQL doubles the quote; MySQL reads the warmedNO_BACKSLASH_ESCAPESstate to choose between doubling the quote and backslash escaping, which is the armconnection.escapetakes inside the client library.InsertAllawaits its facts before construction, andprimaryKeysreturns the warmed list.supportsInsertReturningreads the pool's memoized server version, whichconfigureConnectionwarms throughcheckVersion.sqlForInsertis synchronous and peeks the schema cache for a nilpk.execInsert, its one caller, awaitsdatabaseVersionand then Rails' ownprimaryKey(tableRef)query and passes the answer in, so the statements logged are the onesexec_insert(database_statements.rb:157-160) logs. Warming throughschemaCache.primaryKeyswas rejected: it adds adata_source_exists?query and memoizes, whichSQLite3AdapterTest#test_insert_loggedsees. The operator ruled thatsqlForInsertreturns synchronously under this section (2026-10-08, storyconverge-sql-for-insert-and-supports-insert-returning-to-sync), and the warm step inexecInsertis the permanent consequence.lookupCastTypeFromColumnkeeps Rails' line and cannot await it. On a cold type map it startsverifyBangand the lookup raisesTypeErroroff the unset map. ThatTypeErroris the error the caller sees, where Rails raisesConnectionNotEstablishedfromverify!: 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, awaitingverifyBangwhen the type map is unset, and that await is where the connection error surfaces. There are three warm steps.buildFixtureSqlis the first.loadSchemaFromAdapteris the second: a schema cache loaded from a dump answers its columns with no query, so nothing has verified the connection whenloadSchemaBangreachestypeForColumn. 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.mismatchedForeignKeyhas 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: thesqlarm returns a promise of theMismatchedForeignKey, and thequery_parserarm returns the error itself, whosesetQueryawaits the details. Both are reached only throughtranslateExceptionClassandlog, 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 byBuilder::Association.create_reflection,associations/builder/association.rb:40-51),.Migration,.Relation,.AssociationRelationand.DisableJoinsAssociationRelation(read byDelegation.delegated_classes,relation/delegation.rb:7-15), and.Fixture(Rails has noautoload :Fixture; it is defined infixtures.rb, loaded throughautoload :FixtureSet, and itsFixtureErroris raised atabstract/database_statements.rb:615).ActiveRecord.Point(postgresql/oid/point.rb:4) is required, not autoloaded, and is seated with noautoloadcall.Associations: the six concrete association ctorsAssociationReflection#association_classreturns (reflection.rb:889-923),CollectionProxyandDisableJoinsAssociationScope(associations/association.rb:107-115).Encryption: the wholeencryption.rb:10-35eager_autoloadlist;ConfigurableandContextsareextended ontoEncryptionitself asencryption.rb:47-48includes them, so readers spellEncryption.config.x;Cipheris itselfextended withAutoloadforCipher.Aes256Gcm.ConnectionAdapters:ConnectionPool(read byabstract/query_cache.rb:100) and the module's singletonregister/resolve(connection_adapters.rb:22-50, read bydatabase_config.rb:17).Migrationisextended withAutoloadforCompatibility(migration.rb:573),CommandRecorder,JoinTable,ExecutionStrategyandDefaultStrategy(:572-576); command-recorder.ts readsActiveRecord.IrreversibleMigrationat call time, so it takes no edge back into migration.ts.Tasks(active_record.rb:173-180):DatabaseTasksand the three adapter task classes.migration.tsreadsActiveRecord.Tasks.DatabaseTasksat call time (migration.rb:151-183,696,750,1037-1041,1361-1365), becausedatabase-tasks.tsimportsmigration.tsandconnection-handling.ts, and a plain import back re-enters theschema-statements.ts -> migration/command-recorder.ts -> migration.tscycle.ActiveRecordregisters itself withconstantize, which walks each further segment through the constant seated on its namespace, asObject.const_getdoes (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:
loadawaits theimport()of the registered path, throughConnectionAdapters.loadPathfor a built-in. It holds a failure in the module-privateloadErrors, andresolveraises it as Rails' twoLoadErrormessages, at Rails' raise site.resolveis otherwiseconnection_adapters.rb:26-66: same guards, same order, same messages.ConnectionHandler#resolvePoolConfigcallsloadbeforevalidate!(connection_adapters/abstract/connection_handler.rb:275-280). It is the one step everyestablish_connectionalready awaits, soDatabaseConfig#validate!stays Rails' body. Code that builds aPoolConfigwithout a handler (support/template-global-setup.ts) callsloaditself.- A built-in's
loadPaththunk 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, andloadthen finds it defined. connection-handler.tsdoes not importconnection-adapters.ts, which re-exports it, asconnection_handler.rbis only reached throughconnection_adapters.rb's autoload. That edge put the two in a cycle in which a Rollup bundle readsConnectionHandlerin TDZ. A module that callsloadimportsconnection-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 aDatabaseConfigby hand, and no otherrequireis 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, whereconstantizereads it.rbModRemoveConst(rb_mod_remove_const,vendor/ruby/v3.3.11/variable.c:3302) removes one. loadMigrationis Rails' three lines in Rails' order and is async, as every caller ofMigrationProxy#migrationalready 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 readsundefinedor silently creates an own property. - A generated reader removed by
undefineAttributeMethodsis not regenerated by reading it off an existing record. It comes back throughdefineAttributeMethods(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 asnew klass(attributes, block), in source and in tests. Generated application code saysnew Post(params)too (trailties/lib/generators/active-model.ts). inheritance.rb'snewhas no member ininheritance.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) isklass.allocate+initialize, which skipsInheritance::ClassMethods#new. It reaches the constructor with_suppressAbstractCheckand_suppressStiNewDispatchset.Relation#newandCollectionProxy#neware instance methods with nonewexpression to stand in for them, and stay.- This rule bounds root
CLAUDE.md§ "Every promise has an owner; asyncinitializeis an awaitedstatic new": a class whoseinitializedoes async work gets a protected constructor andstatic async new, but a record never does. Records staynew Klass. - A record loaded from the database is built with
newtoo. Rails'instantiate_instance_ofisklass.allocate.init_with_attributes(attributes, &block)(persistence.rb:313), which skipsinitialize. The JS spelling ofallocate,Object.create, also skips every class-field initializer, so a model field such ashistory = []would be unset on a recordfindreturns. That was tried on trails#8661 and reddenedTransactionCallbacksTeston all three adapters.Base.allocatetherefore goes through the constructor and carries@noRailsEquivalent PERMANENT, and the arm inCore'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 aboveRelation.prototype, so only a lookup that missed the relation's class chain reaches it. Itshastrap has no receiver, soinanswers neither a name the model'srespond_to_missing?claims before that relation method is generated norSymbol.iterator, which thegettrap answers only once the records are loaded synchronously.rbObjRespondToanswersrespond_to?. Thesettrap seats anundefinedplaceholder for each_field a relation first writes on a private layer betweenRelation.prototypeand the Proxy, so later writes stop short of the Proxy and a member defined onRelation.prototypelater still shadows it.