ソースを参照

Let a caller say which day an entry takes effect

Every transfer was stamped with the commit clock and nothing else, so the
ledger knew when an entry was typed and never when it belongs. A period
report wants the entries valued in that period, not the ones recorded in
it, and transfer queries could only filter on the typist's clock.

created_at could not be the field to open up. It is the clock the balance
cache folds its tail against, so a backdated one would put a transfer
behind an existing cache point: the cached balance would quietly omit it
while the exact sum included it, which is the one disagreement the
projection suite exists to catch. The value date is its own field and the
commit clock keeps its single meaning.

It is a calendar day rather than an instant, because an entry valued on
the twentieth is valued on the twentieth wherever it is read, and an
instant would make that depend on the reader's timezone. The constructor
rejects a date that does not exist, so the builder method itself cannot
fail and does not repeat the mid-chain Result that deposit has.

The day is part of the content address, which keeps two entries that
differ only in it from collapsing into one and extends that protection to
the backdated deposits most likely to repeat. The price is that a value
date is corrected by reversing and reposting rather than in place, which
is the trail an auditor would ask for anyway. The preimage changed, so the
canonical version moves and earlier content addresses do not reproduce.

A reversal carries the original's day, so an entry is undone in the period
it landed in. Undoing it in a later one would leave the first period still
reporting the amount the reversal is meant to cancel.

One migration test built a schema claiming the first migration was applied
without creating the transfers table that migration defines. Nothing had
altered that table since, so the gap stayed hidden until this migration
did.
C 3 日 前
親
コミット
8d321e451f

+ 9 - 0
CHANGELOG.md

@@ -9,6 +9,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
 
 ### Added
 
+- `TransferBuilder::value_date(..)` and the `ValueDate` calendar-day type, for an
+  entry booked on a different day than it belongs to: a correction, a late
+  settlement, a future-dated order. `TransferQuery` gains `from_value_date` and
+  `to_value_date`, so a period report groups by the day an entry takes effect
+  rather than by the clock it was typed on. The value date is part of the
+  content address, so two entries differing only in that day are two transfers,
+  and `CANONICAL_VERSION` moves to 6: content addresses computed under an
+  earlier version do not reproduce. `created_at` is unchanged and still not
+  caller-supplied. Migration `013_value_date`. (ADR-0027)
 - `TransferBuilder::reference(..)`, which writes a caller-supplied reference
   under the reserved `REFERENCE_KEY` metadata key. A transfer's id is the hash
   of its content, so a transfer that consumes nothing (a deposit, an issuance)

+ 6 - 3
crates/kuatia-core/src/posting_resolution.rs

@@ -261,12 +261,15 @@ pub fn resolve_envelope(input: ResolveInput<'_>) -> Result<Envelope, ResolveErro
         }
     }
 
-    Ok(EnvelopeBuilder::new()
+    let mut envelope = EnvelopeBuilder::new()
         .consumes(consumes)
         .creates(creates)
         .book(transfer.book)
-        .metadata(transfer.metadata.clone())
-        .build())
+        .metadata(transfer.metadata.clone());
+    if let Some(value_date) = transfer.value_date {
+        envelope = envelope.value_date(value_date);
+    }
+    Ok(envelope.build())
 }
 
 #[cfg(test)]

+ 17 - 0
crates/kuatia-core/src/validate.rs

@@ -565,6 +565,7 @@ mod tests {
             ],
             book: BookId(0),
             account_snapshots: vec![],
+            value_date: None,
             metadata: BTreeMap::new(),
         }
     }
@@ -597,6 +598,7 @@ mod tests {
             creates: vec![],
             book: BookId(0),
             account_snapshots: vec![],
+            value_date: None,
             metadata: BTreeMap::new(),
         };
         let accounts = HashMap::new();
@@ -627,6 +629,7 @@ mod tests {
             }],
             book: BookId(0),
             account_snapshots: vec![],
+            value_date: None,
             metadata: BTreeMap::new(),
         };
         let accounts = accounts_map(vec![make_account(
@@ -659,6 +662,7 @@ mod tests {
             creates: vec![],
             book: BookId(0),
             account_snapshots: vec![],
+            value_date: None,
             metadata: BTreeMap::new(),
         };
         let accounts = HashMap::new();
@@ -743,6 +747,7 @@ mod tests {
             }],
             book: BookId(0),
             account_snapshots: vec![],
+            value_date: None,
             metadata: BTreeMap::new(),
         };
         let accounts = accounts_map(vec![
@@ -792,6 +797,7 @@ mod tests {
             }],
             book: BookId(0),
             account_snapshots: vec![],
+            value_date: None,
             metadata: BTreeMap::new(),
         };
         let accounts = accounts_map(vec![
@@ -838,6 +844,7 @@ mod tests {
             }],
             book: BookId(0),
             account_snapshots: vec![],
+            value_date: None,
             metadata: BTreeMap::new(),
         };
         let accounts = accounts_map(vec![
@@ -886,6 +893,7 @@ mod tests {
             }],
             book: BookId(0),
             account_snapshots: vec![],
+            value_date: None,
             metadata: BTreeMap::new(),
         };
         let accounts = accounts_map(vec![
@@ -920,6 +928,7 @@ mod tests {
             creates: vec![],
             book: BookId(0),
             account_snapshots: vec![],
+            value_date: None,
             metadata: BTreeMap::new(),
         };
         let accounts = HashMap::new();
@@ -969,6 +978,7 @@ mod tests {
             ],
             book: BookId(0),
             account_snapshots: vec![],
+            value_date: None,
             metadata: BTreeMap::new(),
         };
         let accounts = accounts_map(vec![
@@ -1027,6 +1037,7 @@ mod tests {
             ],
             book: BookId(0),
             account_snapshots: vec![],
+            value_date: None,
             metadata: BTreeMap::new(),
         };
         let accounts = accounts_map(vec![
@@ -1071,6 +1082,7 @@ mod tests {
             ],
             book: BookId(0),
             account_snapshots: vec![],
+            value_date: None,
             metadata: BTreeMap::new(),
         };
         let accounts = accounts_map(vec![
@@ -1119,6 +1131,7 @@ mod tests {
             ],
             book: BookId(0),
             account_snapshots: vec![],
+            value_date: None,
             metadata: BTreeMap::new(),
         };
         // Only external account exists, account 999 doesn't
@@ -1158,6 +1171,7 @@ mod tests {
             ],
             book: BookId(0),
             account_snapshots: vec![],
+            value_date: None,
             metadata: BTreeMap::new(),
         };
         let accounts = accounts_map(vec![make_account(
@@ -1263,6 +1277,7 @@ mod tests {
             ],
             book: BookId(0),
             account_snapshots: vec![],
+            value_date: None,
             metadata: BTreeMap::new(),
         };
 
@@ -1327,6 +1342,7 @@ mod tests {
             ],
             book: BookId(0),
             account_snapshots: vec![],
+            value_date: None,
             metadata: BTreeMap::new(),
         };
 
@@ -1374,6 +1390,7 @@ mod tests {
                 account: AccountId::new(7),
                 snapshot_id: [0; 32],
             }],
+            value_date: None,
             metadata: BTreeMap::new(),
         };
 

+ 2 - 1
crates/kuatia-storage-sql/src/commit.rs

@@ -283,12 +283,13 @@ impl CommitStore for SqlStore {
         // Store the transfer record and index it under the involved accounts.
         let transfer_json = serialize_json(&req.record.envelope)?;
         let receipt_json = serialize_json(&req.record.receipt)?;
-        sqlx::query("INSERT INTO transfers (id, transfer, receipt, created_at, book) VALUES ($1, $2, $3, $4, $5) ON CONFLICT (id) DO NOTHING")
+        sqlx::query("INSERT INTO transfers (id, transfer, receipt, created_at, book, value_date) VALUES ($1, $2, $3, $4, $5, $6) ON CONFLICT (id) DO NOTHING")
             .bind(&tid_hex)
             .bind(&transfer_json)
             .bind(&receipt_json)
             .bind(req.record.created_at)
             .bind(req.record.envelope.book().0)
+            .bind(req.record.envelope.value_date().map(|d| d.days()))
             .execute(&mut *tx)
             .await
             .map_err(internal)?;

+ 4 - 0
crates/kuatia-storage-sql/src/migrate.rs

@@ -113,6 +113,10 @@ impl SqlStore {
                 "012_drop_reservation",
                 Migration::Shared(include_str!("migrations/012_drop_reservation.sql")),
             ),
+            (
+                "013_value_date",
+                Migration::Shared(include_str!("migrations/013_value_date.sql")),
+            ),
         ];
 
         for (name, migration) in migrations {

+ 14 - 0
crates/kuatia-storage-sql/src/migrations/013_value_date.sql

@@ -0,0 +1,14 @@
+-- The day an entry takes effect, when that differs from the day it was
+-- committed (ADR-0027). Nullable because most entries are valued the day they
+-- are booked, and NULL means exactly that.
+--
+-- A filterable projection of `Envelope.value_date`, which the `transfer` JSON
+-- already carries, written at commit and never read back, so period queries can
+-- be answered by the database rather than by loading every candidate row. The
+-- `book` column is the same arrangement.
+--
+-- `created_at` is untouched and keeps its own meaning: the instant the ledger
+-- committed the entry, which is what the balance cache folds its tail against.
+ALTER TABLE transfers ADD COLUMN value_date BIGINT;
+
+CREATE INDEX IF NOT EXISTS idx_transfers_value_date ON transfers(value_date);

+ 12 - 0
crates/kuatia-storage-sql/src/transfer.rs

@@ -125,6 +125,18 @@ impl TransferStore for SqlStore {
             binds.push(to);
             p += 1;
         }
+        // A row with no value date is valued the day it was booked, so it is
+        // outside any explicit value-date window rather than inside every one.
+        if let Some(from) = query.from_value_date {
+            conds.push(format!("t.value_date >= ${p}"));
+            binds.push(from.days());
+            p += 1;
+        }
+        if let Some(to) = query.to_value_date {
+            conds.push(format!("t.value_date < ${p}"));
+            binds.push(to.days());
+            p += 1;
+        }
         if let Some(book) = query.book {
             conds.push(format!("t.book = ${p}"));
             binds.push(book.0);

+ 29 - 0
crates/kuatia-storage-sql/tests/postgres.rs

@@ -111,6 +111,35 @@ async fn amount_columns_are_numeric() {
     }
 }
 
+/// The 013 migration adds the value-date column, and an existing row gets NULL:
+/// an entry booked before the column existed was valued the day it was booked.
+#[tokio::test]
+async fn migration_013_adds_value_date_as_null_for_existing_rows() {
+    let (_store, pool) = new_store_with_pool().await;
+
+    for stmt in [
+        "ALTER TABLE transfers DROP COLUMN value_date",
+        "INSERT INTO transfers (id, transfer, receipt, created_at, book) VALUES ('aa', '{}', '{}', 5, 0)",
+        "DELETE FROM _migrations WHERE name = '013_value_date'",
+    ] {
+        sqlx::query(stmt).execute(&pool).await.unwrap();
+    }
+
+    let store = SqlStore::new(pool.clone());
+    store.migrate().await.unwrap();
+
+    let row = sqlx::query("SELECT value_date FROM transfers WHERE id = 'aa'")
+        .fetch_one(&pool)
+        .await
+        .unwrap();
+    assert!(
+        row.try_get::<Option<i64>, _>("value_date")
+            .unwrap()
+            .is_none(),
+        "an entry booked before the column existed carries no value date"
+    );
+}
+
 /// The 012 migration drops the reservation column and leaves every live row
 /// live, including one that still carried a token: it was never consumed, so it
 /// must stay spendable and keep counting toward the balance.

+ 156 - 1
crates/kuatia-storage-sql/tests/sqlite.rs

@@ -1,7 +1,11 @@
 #![allow(missing_docs)]
 #![cfg(feature = "sqlite")]
 
-use kuatia_storage::store::{AccountStore, PostingStore};
+use kuatia_storage::events::{LedgerEvent, LedgerEventKind};
+use kuatia_storage::store::{
+    AccountStore, CommitOutcome, CommitRequest, CommitStore, PostingStore, TransferQuery,
+    TransferRecord, TransferStore,
+};
 use kuatia_storage::store_tests::{seed_live, spend_live};
 use kuatia_storage_sql::SqlStore;
 use kuatia_types::*;
@@ -145,6 +149,15 @@ async fn migration_upgrades_existing_rows_to_main_account() {
     .execute(&pool)
     .await
     .unwrap();
+    // 001 is pinned as applied below, so its `transfers` table has to exist:
+    // a migration that alters it would otherwise fail against a fixture that
+    // claims 001 already ran.
+    sqlx::query(
+        "CREATE TABLE transfers (id TEXT PRIMARY KEY, transfer TEXT NOT NULL, receipt TEXT NOT NULL, created_at BIGINT NOT NULL DEFAULT 0, book BIGINT NOT NULL DEFAULT 0)",
+    )
+    .execute(&pool)
+    .await
+    .unwrap();
     sqlx::query(
         "CREATE TABLE postings (transfer_id TEXT NOT NULL, idx SMALLINT NOT NULL, owner BIGINT NOT NULL, asset INTEGER NOT NULL, value TEXT NOT NULL, status SMALLINT NOT NULL, reservation BIGINT, PRIMARY KEY (transfer_id, idx))",
     )
@@ -256,6 +269,7 @@ async fn migration_004_backfills_index_tables() {
         "010_drop_sagas",
         "011_native_amounts",
         "012_drop_reservation",
+        "013_value_date",
     ] {
         sqlx::query("INSERT INTO _migrations (name) VALUES ($1)")
             .bind(m)
@@ -350,6 +364,7 @@ async fn migration_005_backfills_account_head() {
         "010_drop_sagas",
         "011_native_amounts",
         "012_drop_reservation",
+        "013_value_date",
     ] {
         sqlx::query("INSERT INTO _migrations (name) VALUES ($1)")
             .bind(m)
@@ -424,6 +439,7 @@ async fn migration_008_merges_live_postings() {
         "010_drop_sagas",
         "011_native_amounts",
         "012_drop_reservation",
+        "013_value_date",
     ] {
         sqlx::query("INSERT INTO _migrations (name) VALUES ($1)")
             .bind(m)
@@ -692,6 +708,143 @@ async fn value_beyond_i64_round_trips() {
     );
 }
 
+/// The 013 migration adds the value-date column, and an existing row gets NULL:
+/// an entry booked before the column existed was valued the day it was booked.
+#[tokio::test]
+async fn migration_013_adds_value_date_as_null_for_existing_rows() {
+    let pool = new_pool().await;
+
+    // Post-012 shape: transfers without a value date.
+    sqlx::query("CREATE TABLE transfers (id TEXT PRIMARY KEY, transfer TEXT NOT NULL, receipt TEXT NOT NULL, created_at BIGINT NOT NULL DEFAULT 0, book BIGINT NOT NULL DEFAULT 0)")
+        .execute(&pool)
+        .await
+        .unwrap();
+    sqlx::query("INSERT INTO transfers (id, transfer, receipt, created_at, book) VALUES ('aa', '{}', '{}', 5, 0)")
+        .execute(&pool)
+        .await
+        .unwrap();
+
+    sqlx::query("CREATE TABLE _migrations (name TEXT PRIMARY KEY)")
+        .execute(&pool)
+        .await
+        .unwrap();
+    for m in [
+        "001_init",
+        "002_subaccounts",
+        "003_drop_user_data",
+        "004_index_tables",
+        "005_account_head",
+        "006_drop_policy",
+        "007_balance_projection",
+        "008_live_postings",
+        "009_saga_kind",
+        "010_drop_sagas",
+        "011_native_amounts",
+        "012_drop_reservation",
+    ] {
+        sqlx::query("INSERT INTO _migrations (name) VALUES ($1)")
+            .bind(m)
+            .execute(&pool)
+            .await
+            .unwrap();
+    }
+
+    SqlStore::new(pool.clone()).migrate().await.unwrap();
+
+    let row = sqlx::query("SELECT value_date FROM transfers WHERE id = 'aa'")
+        .fetch_one(&pool)
+        .await
+        .unwrap();
+    assert!(
+        row.try_get::<Option<i64>, _>("value_date")
+            .unwrap()
+            .is_none(),
+        "an entry booked before the column existed carries no value date"
+    );
+}
+
+/// The value-date window is a SQL predicate, not a filter applied after loading,
+/// so it has to behave the same as the in-memory backend: an entry with no value
+/// date sits outside an explicit window rather than inside every one.
+#[tokio::test]
+async fn value_date_window_filters_in_sql() {
+    let pool = new_pool().await;
+    let store = SqlStore::new(pool.clone());
+    store.migrate().await.unwrap();
+    store
+        .create_account(Account::new(AccountId::new(1)))
+        .await
+        .unwrap();
+
+    for (tag, day) in [(1u8, Some(18u32)), (2, Some(20)), (3, Some(22)), (4, None)] {
+        let tid = TransferId([tag; 32]);
+        let value_date = day.map(|d| ValueDate::new(2026, 11, d).unwrap());
+        let mut builder = EnvelopeBuilder::new().creates(vec![NewPosting {
+            owner: AccountId::new(1),
+            asset: AssetId::new(1),
+            value: Cent::from(10),
+            payer: None,
+        }]);
+        if let Some(date) = value_date {
+            builder = builder.value_date(date);
+        }
+        let envelope = builder.build();
+        let create = vec![Posting::new(
+            PostingId {
+                transfer: tid,
+                index: 0,
+            },
+            AccountId::new(1),
+            AssetId::new(1),
+            Cent::from(10),
+        )];
+        let involved = [AccountId::new(1)];
+        let outcome = store
+            .commit_envelope(CommitRequest {
+                transfer_id: tid,
+                consume: &[],
+                create: &create,
+                record: TransferRecord {
+                    envelope,
+                    receipt: Receipt { transfer_id: tid },
+                    created_at: 1000,
+                },
+                involved: &involved,
+                event: LedgerEvent {
+                    seq: 0,
+                    timestamp: 1000,
+                    kind: LedgerEventKind::TransferCommitted { transfer_id: tid },
+                },
+            })
+            .await
+            .unwrap();
+        assert!(matches!(outcome, CommitOutcome::Committed(_)));
+    }
+
+    let page = store
+        .query_transfers(&TransferQuery {
+            account: Some(1),
+            from_value_date: Some(ValueDate::new(2026, 11, 19).unwrap()),
+            to_value_date: Some(ValueDate::new(2026, 11, 22).unwrap()),
+            ..Default::default()
+        })
+        .await
+        .unwrap();
+    assert_eq!(page.total, 1, "only the entry valued on the 20th");
+    assert_eq!(
+        page.items[0].envelope.value_date(),
+        Some(ValueDate::new(2026, 11, 20).unwrap())
+    );
+
+    // The column is written at commit, so the database can answer without
+    // reading the envelope JSON back.
+    let row = sqlx::query("SELECT COUNT(*) AS n FROM transfers WHERE value_date IS NULL")
+        .fetch_one(&pool)
+        .await
+        .unwrap();
+    assert_eq!(row.try_get::<i64, _>("n").unwrap(), 1);
+}
+
 /// The 012 migration drops the reservation column and leaves every live row
 /// live, including one that still carried a token: it was never consumed, so it
 /// must stay spendable and keep counting toward the balance.
@@ -733,6 +886,7 @@ async fn migration_012_drops_reservation_and_keeps_rows_live() {
         "009_saga_kind",
         "010_drop_sagas",
         "011_native_amounts",
+        "013_value_date",
     ] {
         sqlx::query("INSERT INTO _migrations (name) VALUES ($1)")
             .bind(m)
@@ -797,6 +951,7 @@ async fn migration_011_converts_text_amounts() {
         "009_saga_kind",
         "010_drop_sagas",
         "012_drop_reservation",
+        "013_value_date",
     ] {
         sqlx::query("INSERT INTO _migrations (name) VALUES ($1)")
             .bind(m)

+ 10 - 0
crates/kuatia-storage/src/query.rs

@@ -33,6 +33,16 @@ pub fn filter_transfers(
             {
                 return false;
             }
+            if let Some(from) = query.from_value_date
+                && r.envelope.value_date().is_none_or(|d| d < from)
+            {
+                return false;
+            }
+            if let Some(to) = query.to_value_date
+                && r.envelope.value_date().is_none_or(|d| d >= to)
+            {
+                return false;
+            }
             if let Some(book) = query.book
                 && r.envelope.book() != book
             {

+ 9 - 3
crates/kuatia-storage/src/store.rs

@@ -15,7 +15,7 @@
 use async_trait::async_trait;
 use kuatia_types::{
     Account, AccountId, AssetId, Book, BookId, Cent, Envelope, Posting, PostingFilter, PostingId,
-    PostingState, Receipt, TransferId,
+    PostingState, Receipt, TransferId, ValueDate,
 };
 
 use crate::error::StoreError;
@@ -56,10 +56,16 @@ pub struct TransferQuery {
     pub account: Option<i64>,
     /// Restrict to one subaccount; `None` spans every subaccount of `account`.
     pub sub: Option<i64>,
-    /// Inclusive lower bound (unix millis).
+    /// Inclusive lower bound on commit time (unix millis).
     pub from_ts: Option<i64>,
-    /// Exclusive upper bound (unix millis).
+    /// Exclusive upper bound on commit time (unix millis).
     pub to_ts: Option<i64>,
+    /// Inclusive lower bound on the value date. Separate from `from_ts`
+    /// because an entry can be booked in one period and valued in another, and
+    /// a report asks for one or the other, never both at once.
+    pub from_value_date: Option<ValueDate>,
+    /// Exclusive upper bound on the value date.
+    pub to_value_date: Option<ValueDate>,
     /// Filter by book.
     pub book: Option<BookId>,
     /// Max results to return.

+ 13 - 1
crates/kuatia-types/src/canonical.rs

@@ -32,7 +32,9 @@ pub trait ToBytes {
 /// `Envelope` and `Account` preimages.
 /// Bumped to 5 when the `policy` field was removed from the `Account` preimage
 /// (ADR-0018): the single balance constraint now lives in `flags`.
-pub const CANONICAL_VERSION: u8 = 5;
+/// Bumped to 6 when the `Envelope` preimage gained `value_date` (ADR-0027), so
+/// two entries that differ only in the day they take effect are two transfers.
+pub const CANONICAL_VERSION: u8 = 6;
 
 /// Append a `u16` in big-endian to `buf`.
 pub fn write_u16(buf: &mut Vec<u8>, v: u16) {
@@ -166,6 +168,16 @@ impl ToBytes for Envelope {
 
         buf.extend(self.book.to_bytes());
 
+        // Tagged rather than omitted when absent, so "no value date" and "valued
+        // on day zero" cannot produce the same preimage.
+        match self.value_date {
+            None => buf.push(0),
+            Some(date) => {
+                buf.push(1);
+                buf.extend_from_slice(&date.days().to_be_bytes());
+            }
+        }
+
         write_u32(&mut buf, self.metadata.len() as u32);
         for (key, value) in &self.metadata {
             let key_bytes = key.as_bytes();

+ 14 - 0
crates/kuatia-types/src/envelope.rs

@@ -2,6 +2,7 @@
 
 use crate::ids::{AccountId, AccountSnapshotId, BookId, PostingId};
 use crate::posting::NewPosting;
+use crate::value_date::ValueDate;
 use serde::{Deserialize, Serialize};
 use std::collections::BTreeMap;
 
@@ -21,6 +22,8 @@ pub struct Envelope {
     pub account_snapshots: Vec<AccountSnapshotId>,
     /// Book this envelope belongs to.
     pub book: BookId,
+    /// Day this entry takes effect; `None` means the day it was committed.
+    pub value_date: Option<ValueDate>,
     /// Free-form key-value metadata.
     pub metadata: Metadata,
 }
@@ -46,6 +49,11 @@ impl Envelope {
         self.book
     }
 
+    /// Day this entry takes effect; `None` means the day it was committed.
+    pub fn value_date(&self) -> Option<ValueDate> {
+        self.value_date
+    }
+
     /// Free-form key-value metadata.
     pub fn metadata(&self) -> &Metadata {
         &self.metadata
@@ -95,6 +103,12 @@ impl EnvelopeBuilder {
         self
     }
 
+    /// Set the day this entry takes effect.
+    pub fn value_date(mut self, value_date: ValueDate) -> Self {
+        self.envelope.value_date = Some(value_date);
+        self
+    }
+
     /// Set the account version pins.
     pub fn account_snapshots(mut self, snapshots: Vec<AccountSnapshotId>) -> Self {
         self.envelope.account_snapshots = snapshots;

+ 2 - 0
crates/kuatia-types/src/lib.rs

@@ -15,6 +15,7 @@ mod envelope;
 mod ids;
 mod posting;
 mod transfer;
+mod value_date;
 
 pub use account_code::{
     DEFAULT_ID_SEED, ID_BITS, ParseAccountIdError, SUB_BITS, id_seed, set_id_seed,
@@ -38,3 +39,4 @@ pub use envelope::{Envelope, EnvelopeBuilder, Metadata};
 pub use ids::{AccountId, AccountSnapshotId, AssetId, BookId, DEFAULT_BOOK, PostingId, TransferId};
 pub use posting::{NewPosting, Posting, PostingFilter, PostingState};
 pub use transfer::{Movement, REFERENCE_KEY, Receipt, Transfer, TransferBuilder};
+pub use value_date::{InvalidDate, ValueDate};

+ 22 - 0
crates/kuatia-types/src/transfer.rs

@@ -3,6 +3,7 @@
 
 use crate::envelope::Metadata;
 use crate::ids::{AccountId, AssetId, BookId, TransferId};
+use crate::value_date::ValueDate;
 use kuatia_money::{Cent, OverflowError};
 use serde::{Deserialize, Serialize};
 
@@ -41,6 +42,9 @@ pub struct Transfer {
     pub movements: Vec<Movement>,
     /// Book this entity belongs to.
     pub book: BookId,
+    /// Day this entry takes effect, when that differs from the day it is
+    /// committed. `None` means the two are the same.
+    pub value_date: Option<ValueDate>,
     /// Free-form key-value metadata.
     pub metadata: Metadata,
 }
@@ -143,6 +147,24 @@ impl TransferBuilder {
         self
     }
 
+    /// Set the day this entry takes effect, for an entry booked on a different
+    /// day than it belongs to: a backdated correction, a future-dated standing
+    /// order, a trade settling later.
+    ///
+    /// The value date is part of the transfer's content address, so two
+    /// otherwise identical entries valued on different days are two transfers.
+    /// It follows that a value date cannot be corrected in place: an entry
+    /// valued wrongly is reversed and reposted, which is the trail an auditor
+    /// expects anyway.
+    ///
+    /// This does not change when the transfer commits. The commit instant stays
+    /// the ledger's own clock, because that is what balance reads are ordered
+    /// by.
+    pub fn value_date(mut self, value_date: ValueDate) -> Self {
+        self.transfer.value_date = Some(value_date);
+        self
+    }
+
     /// Set the free-form metadata, replacing the whole map including any
     /// [`reference`](Self::reference) already set.
     pub fn metadata(mut self, metadata: Metadata) -> Self {

+ 168 - 0
crates/kuatia-types/src/value_date.rs

@@ -0,0 +1,168 @@
+//! The [`ValueDate`]: the day an entry takes effect, as opposed to the instant
+//! it was committed.
+
+use std::fmt;
+
+use serde::{Deserialize, Serialize};
+
+/// The day an entry takes effect, held as days since 1970-01-01.
+///
+/// A calendar day rather than an instant, because a value date is a business
+/// fact that no timezone should be able to shift: an entry valued 20 November
+/// is valued 20 November wherever it is read.
+#[derive(Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
+pub struct ValueDate(i64);
+
+/// Why a `(year, month, day)` is not a date.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum InvalidDate {
+    /// The month was outside 1 through 12.
+    Month(u32),
+    /// The day was outside 1 through the length of that month in that year.
+    Day(u32),
+}
+
+impl fmt::Display for InvalidDate {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        match self {
+            Self::Month(m) => write!(f, "month {m} is not in 1..=12"),
+            Self::Day(d) => write!(f, "day {d} is not a day of that month"),
+        }
+    }
+}
+
+impl std::error::Error for InvalidDate {}
+
+const DAYS_IN_MONTH: [u32; 12] = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
+
+fn is_leap(year: i32) -> bool {
+    (year % 4 == 0 && year % 100 != 0) || year % 400 == 0
+}
+
+fn days_in_month(year: i32, month: u32) -> u32 {
+    if month == 2 && is_leap(year) {
+        29
+    } else {
+        DAYS_IN_MONTH[(month - 1) as usize]
+    }
+}
+
+impl ValueDate {
+    /// Build a value date from a calendar date, rejecting one that does not
+    /// exist.
+    pub fn new(year: i32, month: u32, day: u32) -> Result<Self, InvalidDate> {
+        if !(1..=12).contains(&month) {
+            return Err(InvalidDate::Month(month));
+        }
+        if day < 1 || day > days_in_month(year, month) {
+            return Err(InvalidDate::Day(day));
+        }
+        Ok(Self(days_from_civil(year, month, day)))
+    }
+
+    /// Days since 1970-01-01, negative before it. The storage form, and what
+    /// orders and compares two value dates.
+    pub const fn days(&self) -> i64 {
+        self.0
+    }
+
+    /// Rebuild from the stored day count.
+    pub const fn from_days(days: i64) -> Self {
+        Self(days)
+    }
+
+    /// The calendar date, as `(year, month, day)`.
+    pub fn civil(&self) -> (i32, u32, u32) {
+        civil_from_days(self.0)
+    }
+}
+
+impl fmt::Display for ValueDate {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        let (y, m, d) = self.civil();
+        write!(f, "{y:04}-{m:02}-{d:02}")
+    }
+}
+
+impl fmt::Debug for ValueDate {
+    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+        write!(f, "ValueDate({self})")
+    }
+}
+
+/// Days from 1970-01-01 to a calendar date, by Howard Hinnant's `days_from_civil`.
+/// Shifting the era to start in March puts the leap day last, so the month-length
+/// pattern repeats and needs no table.
+fn days_from_civil(year: i32, month: u32, day: u32) -> i64 {
+    let y = if month <= 2 { year - 1 } else { year };
+    let era = if y >= 0 { y } else { y - 399 } / 400;
+    let yoe = (y - era * 400) as i64;
+    let mp = if month > 2 { month - 3 } else { month + 9 } as i64;
+    let doy = (153 * mp + 2) / 5 + day as i64 - 1;
+    let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
+    era as i64 * 146097 + doe - 719468
+}
+
+/// The inverse of [`days_from_civil`].
+fn civil_from_days(days: i64) -> (i32, u32, u32) {
+    let z = days + 719468;
+    let era = if z >= 0 { z } else { z - 146096 } / 146097;
+    let doe = z - era * 146097;
+    let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146096) / 365;
+    let y = yoe + era * 400;
+    let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
+    let mp = (5 * doy + 2) / 153;
+    let d = (doy - (153 * mp + 2) / 5 + 1) as u32;
+    let m = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
+    ((if m <= 2 { y + 1 } else { y }) as i32, m, d)
+}
+
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn round_trips_through_days() {
+        for (y, m, d) in [
+            (1970, 1, 1),
+            (2026, 11, 20),
+            (2024, 2, 29),
+            (1999, 12, 31),
+            (1900, 3, 1),
+            (2400, 2, 29),
+        ] {
+            let date = ValueDate::new(y, m, d).unwrap();
+            assert_eq!(date.civil(), (y, m, d), "{y}-{m}-{d}");
+            assert_eq!(ValueDate::from_days(date.days()), date);
+        }
+    }
+
+    #[test]
+    fn epoch_is_day_zero_and_dates_order_by_day() {
+        assert_eq!(ValueDate::new(1970, 1, 1).unwrap().days(), 0);
+        assert_eq!(ValueDate::new(1969, 12, 31).unwrap().days(), -1);
+        assert!(ValueDate::new(2026, 11, 20).unwrap() < ValueDate::new(2026, 11, 21).unwrap());
+    }
+
+    #[test]
+    fn rejects_dates_that_do_not_exist() {
+        assert_eq!(ValueDate::new(2026, 13, 1), Err(InvalidDate::Month(13)));
+        assert_eq!(ValueDate::new(2026, 0, 1), Err(InvalidDate::Month(0)));
+        assert_eq!(ValueDate::new(2026, 2, 29), Err(InvalidDate::Day(29)));
+        assert_eq!(ValueDate::new(2026, 4, 31), Err(InvalidDate::Day(31)));
+        assert_eq!(ValueDate::new(2026, 1, 0), Err(InvalidDate::Day(0)));
+        assert!(ValueDate::new(2024, 2, 29).is_ok(), "2024 is a leap year");
+    }
+
+    #[test]
+    fn displays_as_iso() {
+        assert_eq!(
+            ValueDate::new(2026, 11, 20).unwrap().to_string(),
+            "2026-11-20"
+        );
+        assert_eq!(
+            ValueDate::new(1970, 1, 1).unwrap().to_string(),
+            "1970-01-01"
+        );
+    }
+}

+ 1 - 0
crates/kuatia/src/inflight/projection.rs

@@ -455,6 +455,7 @@ mod tests {
                 creates,
                 account_snapshots: vec![],
                 book: BookId(0),
+                value_date: None,
                 metadata: meta_map(&meta).unwrap(),
             },
             receipt: Receipt {

+ 11 - 3
crates/kuatia/src/ledger/commit.rs

@@ -290,12 +290,20 @@ impl Ledger {
             })
             .collect();
 
-        let reverse_envelope = EnvelopeBuilder::new()
+        // The reversal takes the original's value date, so the period the
+        // entry landed in is the period it is undone in. A compensating entry
+        // valued on a later day would leave the first period still reporting
+        // the amount it is meant to cancel. A caller who wants it dated
+        // otherwise builds the envelope and commits that.
+        let mut reverse_envelope = EnvelopeBuilder::new()
             .consumes(created_posting_ids)
             .creates(new_postings)
             .book(original.book())
-            .metadata(original.metadata().clone())
-            .build();
+            .metadata(original.metadata().clone());
+        if let Some(value_date) = original.value_date() {
+            reverse_envelope = reverse_envelope.value_date(value_date);
+        }
+        let reverse_envelope = reverse_envelope.build();
 
         self.commit_envelope(reverse_envelope).await
     }

+ 104 - 0
crates/kuatia/tests/integration.rs

@@ -4,6 +4,7 @@ use std::sync::Arc;
 
 use kuatia::ledger::Ledger;
 use kuatia::mem_store::InMemoryStore;
+use kuatia::store::TransferQuery;
 use kuatia_core::*;
 use std::collections::BTreeMap;
 
@@ -333,6 +334,109 @@ async fn identical_payments_are_distinct_without_a_reference() {
     );
 }
 
+/// A value date is part of the content address, so two entries that differ only
+/// in the day they take effect are two transfers. This is also what lets a
+/// backdated deposit repeat without a reference.
+#[tokio::test]
+async fn value_date_distinguishes_otherwise_identical_transfers() {
+    let ledger = setup_ledger().await;
+    let dated = |y, m, d| {
+        TransferBuilder::new()
+            .deposit(account(1), usd(), Cent::from(100), external())
+            .unwrap()
+            .value_date(ValueDate::new(y, m, d).unwrap())
+            .build()
+    };
+
+    let first = ledger.commit(dated(2026, 11, 20)).await.unwrap();
+    let second = ledger.commit(dated(2026, 11, 21)).await.unwrap();
+    assert_ne!(first.transfer_id, second.transfer_id);
+    assert_eq!(
+        ledger.balance(&account(1), &usd()).await.unwrap(),
+        Cent::from(200)
+    );
+
+    // The same day twice is still one transfer: the date distinguishes, it does
+    // not excuse a caller from a reference.
+    let replay = ledger.commit(dated(2026, 11, 20)).await.unwrap();
+    assert_eq!(replay.transfer_id, first.transfer_id);
+    assert_eq!(
+        ledger.balance(&account(1), &usd()).await.unwrap(),
+        Cent::from(200)
+    );
+}
+
+/// Transfers are queryable by the day they take effect, independently of the
+/// instant they were committed. Everything here commits now, so a window on the
+/// commit clock cannot tell these apart.
+#[tokio::test]
+async fn transfers_filter_by_value_date_not_commit_time() {
+    let ledger = setup_ledger().await;
+    for (day, amount) in [(18, 10), (20, 20), (22, 30)] {
+        ledger
+            .commit(
+                TransferBuilder::new()
+                    .deposit(account(1), usd(), Cent::from(amount), external())
+                    .unwrap()
+                    .value_date(ValueDate::new(2026, 11, day).unwrap())
+                    .build(),
+            )
+            .await
+            .unwrap();
+    }
+
+    let window = TransferQuery {
+        account: Some(1),
+        from_value_date: Some(ValueDate::new(2026, 11, 19).unwrap()),
+        to_value_date: Some(ValueDate::new(2026, 11, 22).unwrap()),
+        ..Default::default()
+    };
+    let page = ledger.query_transfers(&window).await.unwrap();
+    assert_eq!(page.total, 1, "only the entry valued on the 20th");
+
+    // An entry with no value date is valued when it was booked, so it sits
+    // outside an explicit window rather than inside every one.
+    deposit(&ledger, account(1), usd(), Cent::from(40), external()).await;
+    let page = ledger.query_transfers(&window).await.unwrap();
+    assert_eq!(page.total, 1);
+}
+
+/// A reversal carries the original's value date, so the period the entry landed
+/// in is the period it is undone in.
+#[tokio::test]
+async fn reversal_keeps_the_original_value_date() {
+    let ledger = setup_ledger().await;
+    let valued = ValueDate::new(2026, 11, 20).unwrap();
+    let receipt = ledger
+        .commit(
+            TransferBuilder::new()
+                .deposit(account(1), usd(), Cent::from(100), external())
+                .unwrap()
+                .value_date(valued)
+                .build(),
+        )
+        .await
+        .unwrap();
+
+    ledger.reverse(&receipt.transfer_id).await.unwrap();
+
+    let window = TransferQuery {
+        account: Some(1),
+        from_value_date: Some(valued),
+        to_value_date: Some(ValueDate::new(2026, 11, 21).unwrap()),
+        ..Default::default()
+    };
+    assert_eq!(
+        ledger.query_transfers(&window).await.unwrap().total,
+        2,
+        "the entry and its reversal both fall in the period"
+    );
+    assert_eq!(
+        ledger.balance(&account(1), &usd()).await.unwrap(),
+        Cent::ZERO
+    );
+}
+
 // ---------------------------------------------------------------------------
 // Overdraft prevention
 // ---------------------------------------------------------------------------

+ 1 - 0
doc/SUMMARY.md

@@ -59,4 +59,5 @@
   - [0024: Native money columns, and exact summation in the database](adr/0024-native-money-columns.md)
   - [0025: One live set: retire the reservation protocol and the saga-era store primitives](adr/0025-one-live-set-no-reservations.md)
   - [0026: Let the public API speak the caller's vocabulary](adr/0026-public-api-vocabulary.md)
+  - [0027: Value date, separate from commit time and inside the content address](adr/0027-value-date-separate-from-commit-time.md)
   - [ADR template](adr/template.md)

+ 91 - 0
doc/adr/0027-value-date-separate-from-commit-time.md

@@ -0,0 +1,91 @@
+# Value date, separate from commit time and inside the content address
+
+* Status: accepted
+* Authors: Cesar Rodas
+* Date: 2026-11-23
+* Targeted modules: `kuatia-types` (`value_date`, `transfer`, `envelope`,
+  `canonical`), `kuatia-core` (`posting_resolution`), `kuatia-storage`,
+  `kuatia-storage-sql`, `kuatia` (`ledger`)
+* Associated tickets/PRs: N/A
+
+## Context and Problem Statement
+
+Every transfer was stamped with `now_millis()` at commit and nothing else, so the ledger knew when an entry was recorded and never when it takes effect. Banks and fintechs need both: an entry booked today can be valued last week (a correction, a late settlement) or next week (a future-dated standing order), and a period report asks for the entries *valued* in that period, not the ones typed in it. Transfer queries filtered only on the commit clock, so period-correct reporting was not expressible.
+
+The obvious shape, letting a caller set `created_at`, is unsafe here. `created_at` is the clock the balance cache folds its tail against: `balance` reads the closest cache point and adds every transfer committed after its watermark. A backdated `created_at` would place a transfer behind an existing watermark, so the cached `balance` would silently omit it while `balance_exact` included it, breaking the invariant the projection suite exists to assert.
+
+## Decision Drivers
+
+* A period report is worth nothing if the date it groups by is the typist's clock.
+* The balance cache's correctness depends on one clock meaning one thing.
+* A value date is a business fact that a timezone must not be able to shift.
+* The duplicate-transfer trap (ADR-0026) should not reopen on backdated entries.
+
+## Considered Options
+
+#### Let the caller set `created_at`
+
+**Pros:**
+
+* Good, because it adds no field, no column and no migration.
+
+**Cons:**
+
+* Bad, because it breaks cached balances, as above. The failure is silent and the two balance reads disagree.
+* Bad, because one column would then mean two things, and no later reader could tell which.
+
+#### A separate `value_date`, outside the content address
+
+**Pros:**
+
+* Good, because a value date entered wrongly could be corrected in place.
+
+**Cons:**
+
+* Bad, because two backdated deposits of the same amount to the same account would still collapse into one transfer unless the caller also set a reference, so ADR-0026's trap stays open on exactly the path where a correction is most likely.
+* Bad, because a mutable field on an otherwise immutable record invites a second one.
+
+#### A separate `value_date`, inside the content address (chosen)
+
+**Pros:**
+
+* Good, because the commit clock keeps its single meaning and the balance cache is untouched.
+* Good, because two entries differing only in the day they take effect are two transfers, which closes the duplicate trap for dated entries without a reference.
+* Good, because the date is covered by the same tamper evidence as the rest of the entry.
+
+**Cons:**
+
+* Bad, because a value date cannot be corrected in place: an entry valued wrongly is reversed and reposted.
+* Bad, because the preimage changed, so `CANONICAL_VERSION` is bumped and content addresses computed under an earlier version do not reproduce.
+
+## Decision Outcome
+
+Chosen option: a separate `ValueDate` on `Transfer` and `Envelope`, inside the content address.
+
+`ValueDate` is a calendar day held as days since 1970-01-01, not an instant, because a value date is a business fact: an entry valued 20 November is valued 20 November wherever it is read, and an instant would make that depend on a reader's timezone. `ValueDate::new` rejects a date that does not exist, so `TransferBuilder::value_date` stays infallible and does not repeat the mid-chain `Result` that `deposit` has.
+
+`None` means the entry takes effect the day it was committed, and is tagged in the preimage rather than omitted, so "no value date" and "valued on day zero" cannot encode identically.
+
+A reversal carries the original's value date, so the period an entry landed in is the period it is undone in. A compensating entry valued later would leave the first period still reporting the amount it is meant to cancel. A caller who wants it dated otherwise builds the envelope and commits that.
+
+`TransferQuery` gains `from_value_date` and `to_value_date`, kept apart from `from_ts` and `to_ts` because a report asks for one clock or the other, never both at once. An entry with no value date falls outside an explicit window rather than inside every one.
+
+Migration 013 adds a nullable `transfers.value_date` column with an index. It is a filterable projection of the envelope's field, written at commit and never read back, so the database can answer a period query without loading every candidate row. The `book` column is the same arrangement.
+
+### Positive Consequences
+
+* Period-correct reporting is expressible, and the as-of balance and trial balance on the roadmap now have a date to group by.
+* A backdated deposit repeats safely without a reference, because the date distinguishes it.
+* The balance projection is untouched: `created_at` still means the instant the ledger committed the entry.
+
+### Negative Consequences
+
+* `CANONICAL_VERSION` moves to 6, so every content address changes. Acceptable in an unreleased cycle that has already changed them once, and the version byte exists to gate exactly this.
+* Correcting a value date means reverse and repost, which is more ceremony than an update and is also the trail an auditor expects.
+* The value date is stored twice, in the envelope JSON and in its own column. The column is derived and never read back, the same compromise `book` already makes for the same reason.
+
+## Links
+
+* Follows [ADR-0026](0026-public-api-vocabulary.md), whose `reference` closed the duplicate-transfer trap this extends to dated entries.
+* Constrained by [ADR-0019](0019-cached-balance-projection.md): the cache folds its tail by commit time, which is why the value date had to be a new field.
+* Extends [ADR-0010](0010-event-stream-vs-transfer-log.md)'s transfer log with the second date a reporting caller needs.

+ 1 - 0
doc/adr/README.md

@@ -36,6 +36,7 @@ to reverse a decision. Instead, a new ADR supersedes it.
 | [0024](0024-native-money-columns.md) | Native money columns, and exact summation in the database | accepted | Amount columns become `NUMERIC(39,0)` on PostgreSQL and a 16-byte order-preserving `BLOB` on SQLite, stored at full i128 width whatever the backing. The database may now sum them, exactly: plain `SUM()` on Postgres, a registered `kuatia_i128_sum` aggregate on SQLite. Supersedes 0011's text storage; amends 0009 and 0023. |
 | [0025](0025-one-live-set-no-reservations.md) | One live set: retire the reservation protocol and the saga-era store primitives | accepted | A posting is live or spent, with nothing in between: `PostingState` loses `Reserved`, `PostingFilter` loses `Active`, and `ReservationId`/`TransitionId` go. The six single-update write primitives are removed, leaving the atomic commit as the store's only posting write, and migration 012 drops `live_postings.reservation`. Follows 0023; supersedes 0006; amends 0008. |
 | [0026](0026-public-api-vocabulary.md) | Let the public API speak the caller's vocabulary | accepted | Four shapes left over from earlier designs leave the surface: the `Arc<Ledger>` every commit required and never used, `TransferBuilder`'s duplicate `_ref` methods, the `Envelope` spelling in `EnvelopeId`/`EnvelopeRecord` (now `TransferId`/`TransferRecord`), and the four-way balance surface (`compute_balance` becomes `balance_exact`; cache maintenance moves to `Ledger::projection()`). Nothing stored changes. Follows 0025; supersedes 0012's builder clause. |
+| [0027](0027-value-date-separate-from-commit-time.md) | Value date, separate from commit time and inside the content address | accepted | An entry can be booked one day and take effect another. `ValueDate` is a calendar day on `Transfer` and `Envelope`, inside the content address, so two entries differing only in the day they take effect are two transfers. `created_at` keeps its single meaning as the commit clock the balance cache folds against; migration 013 adds a filterable column and `TransferQuery` gains its own window. Bumps `CANONICAL_VERSION`. Follows 0026; constrained by 0019. |
 
 ## Recommended future ADRs
 

+ 1 - 0
doc/crates.md

@@ -33,6 +33,7 @@ dependencies (`sha2`, `serde`, `bitflags`).
 | `Transfer` | Atomic unit: consumes postings + creates postings + metadata |
 | `EnvelopeBuilder` | Fluent builder for `Envelope` construction (the resolved form; `TransferBuilder` builds the intent) |
 | `REFERENCE_KEY` | Reserved metadata key for a caller's transfer reference, set via `TransferBuilder::reference` |
+| `ValueDate` | The day an entry takes effect, as days since 1970-01-01. A calendar day rather than an instant, so no timezone shifts it. `ValueDate::new(y, m, d)` rejects a date that does not exist |
 | `Account` | Versioned entity with flags, book, metadata. `Account::new(id)` allows overdraft by default; `Account::debit_must_not_exceed_credit(id)` forbids it; `Account::forbids_overdraft()` queries the constraint |
 | `AccountFlags` | Bitflags: `FROZEN`, `CLOSED`, `DEBIT_MUST_NOT_EXCEED_CREDIT` (when set, the account's debits may not exceed its credits: balance stays `>= 0`, no negative postings) |
 | `Metadata` | `BTreeMap<String, Vec<u8>>` for free-form key-value data |

+ 5 - 3
doc/storage-schema.md

@@ -3,7 +3,7 @@
 Reference for the tables `kuatia-storage-sql` creates. This is the composed
 end-state after replaying every migration in
 `crates/kuatia-storage-sql/src/migrations/` (`001_init` through
-`012_drop_reservation`) plus the `_migrations` bookkeeping table created in
+`013_value_date`) plus the `_migrations` bookkeeping table created in
 `crates/kuatia-storage-sql/src/migrate.rs`. It is a living reference: update it
 when a migration lands. For *why* the schema looks this way, see the ADRs it
 links to, not this file.
@@ -81,6 +81,7 @@ erDiagram
         TEXT receipt
         BIGINT created_at
         BIGINT book
+        BIGINT value_date
     }
     transfer_accounts {
         TEXT transfer_id PK
@@ -236,11 +237,12 @@ Committed envelope records and the account index that finds them. Owned by
 | `id` | `TEXT` | PK | Content-addressed envelope id (hex). |
 | `transfer` | `TEXT` | | The `Envelope` as JSON. |
 | `receipt` | `TEXT` | | The `Receipt` as JSON. |
-| `created_at` | `BIGINT` | | Unix millis when stored (default `0`). |
+| `created_at` | `BIGINT` | | Unix millis when the ledger committed this entry (default `0`). Never caller-supplied: the balance cache folds its tail against it (ADR-0019). |
 | `book` | `BIGINT` | | Owning book id (default `0`). |
+| `value_date` | `BIGINT` | | Days since 1970-01-01 for the day this entry takes effect; `NULL` means the day it was committed. A filterable projection of `Envelope.value_date`, written at commit and never read back (ADR-0027). |
 
 - **Primary key**: `id`.
-- **Indexes**: `idx_transfers_created_at (created_at)`, `idx_transfers_book (book)`.
+- **Indexes**: `idx_transfers_created_at (created_at)`, `idx_transfers_book (book)`, `idx_transfers_value_date (value_date)`.
 
 ### `transfer_accounts`
 

+ 39 - 0
doc/transfers.md

@@ -194,6 +194,45 @@ the behaviour you want from a retry. One rule covers both. The reference is
 stored under the reserved `REFERENCE_KEY` metadata key, so it is part of the
 content address and part of the audit record.
 
+## Booking date and value date
+
+Two dates, and they answer different questions:
+
+| | Set by | Means | Query with |
+|---|---|---|---|
+| `created_at` | the ledger, at commit | the instant this entry was recorded | `from_ts` / `to_ts` |
+| `value_date` | the caller, optional | the day this entry takes effect | `from_value_date` / `to_value_date` |
+
+A caller cannot set `created_at`, and that is deliberate: it is the clock the
+balance cache folds its tail against (ADR-0019), so a backdated one would hide a
+transfer behind an existing cache point and silently wrong the cached balance.
+
+Set a value date on an entry that belongs to a different day than the one it is
+booked on, which is a correction, a late settlement or a future-dated order:
+
+```rust
+let correction = TransferBuilder::new()
+    .pay(alice, bob, usd, amount)
+    .value_date(ValueDate::new(2026, 11, 20)?)
+    .build();
+```
+
+`ValueDate` is a calendar day, not an instant, so no timezone can shift it.
+`ValueDate::new` rejects a date that does not exist, which keeps the builder
+method itself infallible.
+
+The value date is part of the content address, so two entries that differ only
+in the day they take effect are two transfers. That closes the duplicate trap
+above for dated entries: a backdated deposit repeats safely without a reference.
+It also means a value date cannot be corrected in place. An entry valued wrongly
+is reversed and reposted, and a reversal carries the original's value date, so
+the period the entry landed in is the period it is undone in.
+
+An entry with no value date takes effect the day it was committed, and falls
+outside an explicit value-date window rather than inside every one.
+
+See [ADR-0027](adr/0027-value-date-separate-from-commit-time.md).
+
 ## Transfer Builder
 
 The `TransferBuilder` provides a fluent API for constructing transfers: