From b219cd748edf8509471221bf78e87aa2390a85d4 Mon Sep 17 00:00:00 2001 From: Raynor Elgie Date: Tue, 24 Nov 2026 03:43:57 +0000 Subject: [PATCH 1/2] Harden CDC permissions, transactional ACLs, recovery, replication, and group/storage safety --- codec/src/records.rs | 29 + docs/architecture.md | 15 +- docs/configuration.md | 4 +- docs/producing.md | 21 +- extension/src/cdc.rs | 200 ++++++- extension/src/group.rs | 29 +- extension/src/handlers/coordinator.rs | 12 +- extension/src/handlers/init_producer_id.rs | 24 +- extension/src/handlers/produce.rs | 10 + extension/src/handlers/share_group.rs | 24 +- extension/src/handlers/topics.rs | 5 +- extension/src/handlers/txn.rs | 521 +++++++++++++++--- extension/src/init220.rs | 49 ++ extension/src/lib.rs | 2 + extension/src/meta.rs | 24 +- extension/src/producer.rs | 43 +- extension/src/replication.rs | 7 +- extension/src/server/dispatch.rs | 10 +- extension/src/server/mod.rs | 28 +- extension/src/storage/cursor.rs | 2 + extension/src/storage/mod.rs | 73 +++ extension/src/storage/pmeta.rs | 25 +- extension/src/storage/segment.rs | 261 +++++++-- extension/src/storage/table.rs | 60 +- tests/integration/test_safety_and_security.py | 381 +++++++++++++ 25 files changed, 1663 insertions(+), 196 deletions(-) create mode 100644 extension/src/init220.rs create mode 100644 tests/integration/test_safety_and_security.py diff --git a/codec/src/records.rs b/codec/src/records.rs index ff6d892..9aaf2de 100644 --- a/codec/src/records.rs +++ b/codec/src/records.rs @@ -1267,6 +1267,35 @@ pub fn build_batch_as(records: &[NewRecord], producer_id: i64) -> bytes::Bytes { build_batch_full(records, producer_id, false) } +/// Control record marker kind in a Kafka control batch (`0` = ABORT, `1` = COMMIT). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum ControlBatchType { + Abort, + Commit, +} + +impl RecordBatch { + /// For a control batch, decode its first record's key to determine whether it is a + /// COMMIT (1) or ABORT (0) marker. + pub fn control_type(&self) -> Option { + if !self.is_control() { + return None; + } + let mut recs = self.records().ok()?; + let rec = recs.next()?.ok()?; + let key = rec.key.as_ref()?; + if key.len() < 4 { + return None; + } + let kind = i16::from_be_bytes([key[2], key[3]]); + match kind { + 0 => Some(ControlBatchType::Abort), + 1 => Some(ControlBatchType::Commit), + _ => None, + } + } +} + /// Bit 5 of the batch attributes: `isControl`. pub const CONTROL_BATCH_FLAG: i16 = 0x20; diff --git a/docs/architecture.md b/docs/architecture.md index 6977b15..95c8bd9 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -21,7 +21,9 @@ is direct: There, a produce with `acks=all` is durable once the transaction's commit has reached the standbys `synchronous_commit` asks for, and there is no separate replication -mechanism to configure or run. +mechanism to configure or run. With `synchronous_commit = off`, even a Postgres process +crash (`kill -9`) — not only a host crash — can lose acknowledged `acks=all` writes and +reuse their offsets. The segment engine keeps the log in files, outside the WAL. By default `acks=all` returns once the records are fsynced (`kafgres.fsync_before_ack`). With that off it @@ -29,7 +31,9 @@ returns once they are in the page cache, as Kafka does with its default flush se they survive a crash of Postgres but not of the host. A standby's copy is pulled out of band (see below) and is always asynchronous, since `synchronous_standby_names` does not cover files outside the WAL; a failover can lose the newest records, and the -leader epochs described next make that visible to consumers rather than silent. +leader epochs described next make that visible rather than silent to live consumers and to +clients that validate committed epochs on resume (such as the Java client; librdkafka 2.16 +and kafka-python do not validate a group's committed epoch when resuming). On the primary, `kafgres_produce()` still commits the row and the event together. The loss is in replication: its row and commit marker travel in the WAL, which can be @@ -139,8 +143,11 @@ The log stream and the WAL advance independently, so after a failover their tail disagree. The log is the source of truth for the high watermark; Postgres keeps only the slowly-changing metadata (topic configs, group offsets, producer state, transaction state). A committed consumer offset that ends up ahead of the log tail after a failover -surfaces as `OFFSET_OUT_OF_RANGE`, a condition Kafka clients already handle through -`auto.offset.reset`. +surfaces as `OFFSET_OUT_OF_RANGE` while the new log remains below that offset, a condition +Kafka clients handle through `auto.offset.reset`. Once new writes grow the log past the +committed offset, clients that validate committed epochs (such as the Java client) detect +the truncation via `OffsetForLeaderEpoch`, whereas clients that do not (librdkafka, +kafka-python) resume at the offset silently. ## Process topology diff --git a/docs/configuration.md b/docs/configuration.md index 07c622f..cb55a5e 100644 --- a/docs/configuration.md +++ b/docs/configuration.md @@ -52,7 +52,7 @@ covers. | Setting | Reload | Default | Description | |---|---|---|---| -| `kafgres.retention_check_interval_ms` | reload | `60000` | How often the broker applies retention and compaction, as Kafka's `log.retention.check.interval.ms`. | +| `kafgres.retention_check_interval_ms` | reload | `60000` | How often the broker applies retention and compaction, as Kafka's `log.retention.check.interval.ms`. (Stale transaction expiry runs on its own ~10 s timer.) | | `kafgres.compaction_pass_bytes` | reload | `32 MiB` | Bytes compaction reads in the broker per retention check, across all partitions; a larger plan resumes at the next check. With the defaults the broker cleans up to about 0.5 MiB/s in total. Raising it lengthens the pause each check takes from serving clients. | ## CDC @@ -73,7 +73,7 @@ covers. | `kafgres.tls_ca_file` | reload | empty | PEM CA bundle that client certificates are verified against; enables mTLS. | | `kafgres.tls_client_cert_required` | reload | off | Refuse the TLS handshake unless the client presents a certificate valid against `kafgres.tls_ca_file`. | | `kafgres.sasl_required` | reload | off | Require SASL/SCRAM-SHA-256 authentication against `pg_authid` roles. | -| `kafgres.acls_enabled` | reload | off | Enforce the `kafgres_acls` table, for Kafka clients and for `kafgres_produce()` callers (as `User:`). Off by default: with it on and no matching rule, the answer is refusal. | +| `kafgres.acls_enabled` | reload | off | Enforce the `kafgres_acls` table, for Kafka clients and for `kafgres_produce()` / `kafgres_read()` callers (as `User:`). Off by default: with it on and no matching rule, the answer is refusal. ACL changes take up to ~1 s to apply due to the in-process ACL cache. | | `kafgres.superusers` | reload | empty | Semicolon-separated principals that bypass every ACL check, for example `User:admin`. | ## Producers and limits diff --git a/docs/producing.md b/docs/producing.md index e11d3c7..bacd9a6 100644 --- a/docs/producing.md +++ b/docs/producing.md @@ -92,19 +92,22 @@ checks, replication), so each needs an explicit `GRANT EXECUTE`. The exceptions `kafgres_follower_lag()`. On an install upgraded from 0.2.0 this takes effect at `ALTER EXTENSION kafgres UPDATE`. -`kafgres_add_mapping` runs with the caller's privileges: it reads `kafgres_topics` and the -source table, and writes `kafgres_cdc_mappings`, so a role needs those grants as well as -`EXECUTE`. It also creates the CDC slot, which Postgres allows only to a superuser or a role -with the `REPLICATION` attribute. A role without that still saves its mapping, with a -warning, and the CDC worker creates the slot (see [CDC mappings](#cdc-mappings)). Use -`ALTER ROLE ... REPLICATION` for a role that should create it. `kafgres_slot_ready()` and -`kafgres_cdc_create_slot()` are administrative like the rest. +`kafgres_add_mapping` validates the expressions with the caller's privileges and records +the caller as the mapping's owner. The CDC worker renders each mapping (and any snapshot +of it) under that owner's privileges in a security-restricted context, so revoking +`SELECT` on a source or enrichment table stops rendering via `on_error`. Do not grant +direct `INSERT`, `UPDATE`, or `DELETE` on `kafgres_cdc_mappings`; `kafgres_add_mapping` +and `kafgres_remove_mapping` manage the table on the caller's behalf. Creating the CDC +slot still requires a superuser or a role with the `REPLICATION` attribute. A role without +that still saves its mapping, with a warning, and the CDC worker creates the slot (see +[CDC mappings](#cdc-mappings)). Use `ALTER ROLE ... REPLICATION` for a role that should +create it. `kafgres_slot_ready()` and `kafgres_cdc_create_slot()` are administrative like +the rest. ```sql GRANT EXECUTE ON FUNCTION kafgres_add_mapping(text, text, text, text, text, text) TO cdc_admin; GRANT SELECT ON kafgres_topics TO cdc_admin; -GRANT SELECT, INSERT, UPDATE ON kafgres_cdc_mappings TO cdc_admin; -GRANT SELECT ON public.orders TO cdc_admin; -- each source table it maps +GRANT SELECT ON public.orders TO cdc_admin; -- each source table it maps (and any enrichment tables) ALTER ROLE cdc_admin REPLICATION; -- optional: lets kafgres_add_mapping create the slot itself ``` diff --git a/extension/src/cdc.rs b/extension/src/cdc.rs index 18e0a58..5e83f0f 100644 --- a/extension/src/cdc.rs +++ b/extension/src/cdc.rs @@ -55,6 +55,9 @@ fn kafgres_add_mapping( render_check(source_table, value_expr, key_expr, filter_expr); + let caller = current_role_name().unwrap_or_else(|e| error!("kafgres: {e}")); + let caller_is_super = unsafe { pg_sys::superuser() }; + // Created here, before this transaction writes, unless that would wait on a long // transaction. Otherwise the worker creates it once the mapping commits; not an error, // but changes before the slot is ready are not captured. @@ -74,34 +77,76 @@ fn kafgres_add_mapping( } } - Spi::run_with_args( - "INSERT INTO kafgres_cdc_mappings - (mapping_name, source_table, topic, key_expr, value_expr, filter_expr) - VALUES ($1, $2, $3, $4, $5, $6) - ON CONFLICT (mapping_name) DO UPDATE SET - source_table = EXCLUDED.source_table, - topic = EXCLUDED.topic, - key_expr = EXCLUDED.key_expr, - value_expr = EXCLUDED.value_expr, - filter_expr = EXCLUDED.filter_expr, - -- A new definition renders whatever the slot replays, not only what follows it. - delivered_lsn = NULL, - delivered_seq = NULL", - &[ - mapping_name.into(), - source_table.into(), - topic.into(), - key_expr.into(), - value_expr.into(), - filter_expr.into(), - ], - ) - .unwrap_or_else(|e| error!("kafgres: {e}")); + // Write under the bootstrap superuser so callers only need EXECUTE on this function + // (not direct DML on kafgres_cdc_mappings), while recording `caller` as the owner. + { + let _owner_ctx = crate::acl::AsBootstrapSuperuser::enter(); + if !caller_is_super { + let existing_owner: Option = read_one( + "SELECT (SELECT owner FROM kafgres_cdc_mappings WHERE mapping_name = $1)", + &[mapping_name.into()], + ) + .unwrap_or_else(|e| error!("kafgres: {e}")); + if let Some(owner) = existing_owner { + if owner != caller { + pgrx::ereport!( + pgrx::PgLogLevel::ERROR, + pgrx::PgSqlErrorCode::ERRCODE_INSUFFICIENT_PRIVILEGE, + format!("kafgres: permission denied: mapping {mapping_name:?} is owned by {owner:?}") + ); + } + } + } + Spi::run_with_args( + "INSERT INTO kafgres_cdc_mappings + (mapping_name, source_table, topic, key_expr, value_expr, filter_expr, owner) + VALUES ($1, $2, $3, $4, $5, $6, $7) + ON CONFLICT (mapping_name) DO UPDATE SET + source_table = EXCLUDED.source_table, + topic = EXCLUDED.topic, + key_expr = EXCLUDED.key_expr, + value_expr = EXCLUDED.value_expr, + filter_expr = EXCLUDED.filter_expr, + owner = EXCLUDED.owner, + -- A new definition renders whatever the slot replays, not only what follows it. + delivered_lsn = NULL, + delivered_seq = NULL", + &[ + mapping_name.into(), + source_table.into(), + topic.into(), + key_expr.into(), + value_expr.into(), + filter_expr.into(), + caller.as_str().into(), + ], + ) + .unwrap_or_else(|e| error!("kafgres: {e}")); + } true } #[pg_extern] fn kafgres_remove_mapping(mapping_name: &str) -> bool { + let caller = current_role_name().unwrap_or_else(|e| error!("kafgres: {e}")); + let caller_is_super = unsafe { pg_sys::superuser() }; + let _owner_ctx = crate::acl::AsBootstrapSuperuser::enter(); + if !caller_is_super { + let existing_owner: Option = read_one( + "SELECT (SELECT owner FROM kafgres_cdc_mappings WHERE mapping_name = $1)", + &[mapping_name.into()], + ) + .unwrap_or_else(|e| error!("kafgres: {e}")); + if let Some(owner) = existing_owner { + if owner != caller { + pgrx::ereport!( + pgrx::PgLogLevel::ERROR, + pgrx::PgSqlErrorCode::ERRCODE_INSUFFICIENT_PRIVILEGE, + format!("kafgres: permission denied: mapping {mapping_name:?} is owned by {owner:?}") + ); + } + } + } Spi::run_with_args( "DELETE FROM kafgres_cdc_mappings WHERE mapping_name = $1", &[mapping_name.into()], @@ -1271,6 +1316,7 @@ struct Mapping { key_expr: Option, filter_expr: Option, on_error: String, + owner: String, /// The last change this mapping rendered, so a replay held for another mapping skips it. delivered: Option, } @@ -1278,11 +1324,53 @@ struct Mapping { fn same_definitions(a: &[Mapping], b: &[Mapping]) -> bool { a.len() == b.len() && a.iter().zip(b).all(|(x, y)| { - (&x.name, &x.source, &x.topic, &x.value_expr, &x.key_expr, &x.filter_expr, &x.on_error) - == (&y.name, &y.source, &y.topic, &y.value_expr, &y.key_expr, &y.filter_expr, &y.on_error) + (&x.name, &x.source, &x.topic, &x.value_expr, &x.key_expr, &x.filter_expr, &x.on_error, &x.owner) + == (&y.name, &y.source, &y.topic, &y.value_expr, &y.key_expr, &y.filter_expr, &y.on_error, &y.owner) }) } +/// Switches the current user to a mapping's owner in a security-restricted context. +struct AsRole { + user: pg_sys::Oid, + context: std::os::raw::c_int, +} + +impl AsRole { + fn enter(role_oid: pg_sys::Oid) -> Self { + let mut user = pg_sys::InvalidOid; + let mut context = 0; + unsafe { + pg_sys::GetUserIdAndSecContext(&mut user, &mut context); + pg_sys::SetUserIdAndSecContext( + role_oid, + context + | pg_sys::SECURITY_LOCAL_USERID_CHANGE as std::os::raw::c_int + | pg_sys::SECURITY_RESTRICTED_OPERATION as std::os::raw::c_int, + ); + } + AsRole { user, context } + } +} + +impl Drop for AsRole { + fn drop(&mut self) { + unsafe { pg_sys::SetUserIdAndSecContext(self.user, self.context) }; + } +} + +fn current_role_name() -> Result { + read_one::("SELECT current_user::text", &[])? + .ok_or_else(|| "could not determine current_user".to_string()) +} + +fn role_oid(role_name: &str) -> Result { + let oid: Option = read_one( + "SELECT (SELECT oid FROM pg_catalog.pg_roles WHERE rolname = $1)", + &[ServerText(role_name).into()], + )?; + oid.ok_or_else(|| format!("mapping owner role {role_name:?} does not exist")) +} + /// A read-only SPI query uses the active snapshot, which in a worker step predates commits /// since the step began; this makes it see them. fn with_latest_snapshot(f: impl FnOnce() -> T) -> T { @@ -1296,7 +1384,7 @@ fn load_mappings() -> Result, String> { Spi::connect(|client| { let rows = client.select( "SELECT mapping_name, source_table, topic, value_expr, key_expr, filter_expr, - on_error, delivered_lsn::text, delivered_seq + on_error, owner, delivered_lsn::text, delivered_seq FROM kafgres_cdc_mappings WHERE enabled ORDER BY mapping_name", None, &[], @@ -1311,7 +1399,8 @@ fn load_mappings() -> Result, String> { key_expr: utf8(r.get::(5)?), filter_expr: utf8(r.get::(6)?), on_error: utf8(r.get::(7)?).unwrap_or_else(|| "skip".into()), - delivered: match (r.get::(8)?, r.get::(9)?) { + owner: utf8(r.get::(8)?).unwrap_or_default(), + delivered: match (r.get::(9)?, r.get::(10)?) { (Some(lsn), Some(seq)) => parse_lsn(&lsn).map(|end| (end, seq)), _ => None, }, @@ -1350,10 +1439,36 @@ fn render( m.key_expr.as_deref(), m.filter_expr.as_deref(), ); + let owner_oid = role_oid(&m.owner)?; + let qualified_source = if m.source != TRANSACTION_SOURCE { + let (schema, table) = split_source(&m.source); + Some(format!("{}.{}", quote_ident(&schema), quote_ident(&table))) + } else { + None + }; + + // Save/restore user & security context around `atomically` because a Postgres ERROR + // longjmp inside the savepoint skips Rust Drop and subtransaction rollback does not + // restore SetUserIdAndSecContext. + let mut saved_user = pg_sys::InvalidOid; + let mut saved_ctx = 0; + unsafe { pg_sys::GetUserIdAndSecContext(&mut saved_user, &mut saved_ctx) }; + // In a savepoint: uncontained, one bad row aborts the whole worker transaction. let rendered = crate::dbtx::atomically( || { Spi::run("SET LOCAL statement_timeout = '30s'").map_err(|e| e.to_string())?; + let _as_owner = AsRole::enter(owner_oid); + if let Some(ref src) = qualified_source { + let has_priv = read_one::( + "SELECT pg_catalog.has_table_privilege($1::regclass, 'SELECT')", + &[ServerText(src).into()], + )? + .unwrap_or(false); + if !has_priv { + return Err(format!("permission denied for table {}", m.source)); + } + } Spi::connect(|client| { let rows = client.select(&sql, None, &[ServerText(changes).into()])?; let mut out = Vec::new(); @@ -1365,7 +1480,9 @@ fn render( .map_err(|e| e.to_string()) }, |caught| caught.to_string(), - )?; + ); + unsafe { pg_sys::SetUserIdAndSecContext(saved_user, saved_ctx) }; + let rendered = rendered?; // Checked here, so an oversize record fails as a render and takes the per-change retry. let mut total = 0usize; @@ -1856,9 +1973,21 @@ fn snapshot_page( fn snapshot_step(st: &SnapshotState, limit: i32) -> Result { let m = load_mapping(&st.name)? .ok_or_else(|| format!("mapping {:?} disappeared mid-snapshot", st.name))?; + let owner_oid = role_oid(&m.owner)?; let pk = primary_key_of(&st.source)?; let shape = shape_of(&st.source)?; - let (changes, last, n) = snapshot_page(&st.source, &pk, &shape, st.cursor.as_deref(), limit)?; + let mut saved_user = pg_sys::InvalidOid; + let mut saved_ctx = 0; + unsafe { pg_sys::GetUserIdAndSecContext(&mut saved_user, &mut saved_ctx) }; + let page = crate::dbtx::atomically( + || { + let _as_owner = AsRole::enter(owner_oid); + snapshot_page(&st.source, &pk, &shape, st.cursor.as_deref(), limit) + }, + |caught| caught.to_string(), + ); + unsafe { pg_sys::SetUserIdAndSecContext(saved_user, saved_ctx) }; + let (changes, last, n) = page?; let appended = if n > 0 { render_and_produce(&m, &shape, &changes)?.1 } else { Appended::new() }; @@ -1889,7 +2018,7 @@ fn snapshot_step(st: &SnapshotState, limit: i32) -> Result { fn load_mapping(name: &str) -> Result, String> { Spi::connect(|client| { let rows = client.select( - "SELECT mapping_name, source_table, topic, value_expr, key_expr, filter_expr, on_error + "SELECT mapping_name, source_table, topic, value_expr, key_expr, filter_expr, on_error, owner FROM kafgres_cdc_mappings WHERE mapping_name = $1", Some(1), &[ServerText(name).into()], @@ -1903,6 +2032,7 @@ fn load_mapping(name: &str) -> Result, String> { key_expr: utf8(r.get::(5)?), filter_expr: utf8(r.get::(6)?), on_error: utf8(r.get::(7)?).unwrap_or_else(|| "skip".into()), + owner: utf8(r.get::(8)?).unwrap_or_default(), delivered: None, })); } @@ -1953,9 +2083,19 @@ pub fn snapshot_worker() -> Result { #[pg_extern] fn kafgres_snapshot_mapping(mapping_name: &str) -> bool { + let caller = current_role_name().unwrap_or_else(|e| error!("kafgres: {e}")); + let caller_is_super = unsafe { pg_sys::superuser() }; + let _owner_ctx = crate::acl::AsBootstrapSuperuser::enter(); let Some(m) = load_mapping(mapping_name).unwrap_or_else(|e| error!("kafgres: {e}")) else { error!("kafgres: no such mapping {mapping_name:?}"); }; + if !caller_is_super && m.owner != caller { + pgrx::ereport!( + pgrx::PgLogLevel::ERROR, + pgrx::PgSqlErrorCode::ERRCODE_INSUFFICIENT_PRIVILEGE, + format!("kafgres: permission denied: mapping {mapping_name:?} is owned by {:?}", m.owner) + ); + } primary_key_of(&m.source).unwrap_or_else(|e| error!("kafgres: {e}")); Spi::run_with_args( diff --git a/extension/src/group.rs b/extension/src/group.rs index 1131a8b..627c166 100644 --- a/extension/src/group.rs +++ b/extension/src/group.rs @@ -443,7 +443,9 @@ pub fn delete(group_id: &str) -> Result { } let members = Spi::get_one_with_args::( - "SELECT (SELECT count(*) FROM kafgres_group_members WHERE group_id = $1)", + "SELECT (SELECT count(*) FROM kafgres_group_members WHERE group_id = $1) + + (SELECT count(*) FROM kafgres_consumer_group_members WHERE group_id = $1) + + (SELECT count(*) FROM kafgres_share_members WHERE group_id = $1)", &[group_id.into()], )? .unwrap_or(0); @@ -460,6 +462,22 @@ pub fn delete(group_id: &str) -> Result { "DELETE FROM kafgres_groups WHERE group_id = $1", &[group_id.into()], )?; + Spi::run_with_args( + "DELETE FROM kafgres_consumer_groups WHERE group_id = $1", + &[group_id.into()], + )?; + Spi::run_with_args( + "DELETE FROM kafgres_share_inflight WHERE group_id = $1", + &[group_id.into()], + )?; + Spi::run_with_args( + "DELETE FROM kafgres_share_offsets WHERE group_id = $1", + &[group_id.into()], + )?; + Spi::run_with_args( + "DELETE FROM kafgres_share_groups WHERE group_id = $1", + &[group_id.into()], + )?; Ok(DeleteOutcome::Deleted) } @@ -468,8 +486,13 @@ pub fn existence(group_id: &str) -> Result<(bool, bool), spi::Error> { let rows = client.select( // One row of scalars, not `FROM kafgres_groups`: SPI raises on an empty result set "SELECT EXISTS(SELECT 1 FROM kafgres_groups WHERE group_id = $1) - OR EXISTS(SELECT 1 FROM kafgres_offsets WHERE group_id = $1), - EXISTS(SELECT 1 FROM kafgres_group_members WHERE group_id = $1)", + OR EXISTS(SELECT 1 FROM kafgres_offsets WHERE group_id = $1) + OR EXISTS(SELECT 1 FROM kafgres_consumer_groups WHERE group_id = $1) + OR EXISTS(SELECT 1 FROM kafgres_share_groups WHERE group_id = $1) + OR EXISTS(SELECT 1 FROM kafgres_share_offsets WHERE group_id = $1), + EXISTS(SELECT 1 FROM kafgres_group_members WHERE group_id = $1) + OR EXISTS(SELECT 1 FROM kafgres_consumer_group_members WHERE group_id = $1) + OR EXISTS(SELECT 1 FROM kafgres_share_members WHERE group_id = $1)", Some(1), &[group_id.into()], )?; diff --git a/extension/src/handlers/coordinator.rs b/extension/src/handlers/coordinator.rs index b5dd582..203ba27 100644 --- a/extension/src/handlers/coordinator.rs +++ b/extension/src/handlers/coordinator.rs @@ -24,10 +24,18 @@ pub fn find_coordinator( vec![req.key.clone()] }; + // key_type 1 is transactional coordinator (TRANSACTIONAL_ID Describe); 0 (group) and + // 2 (share group) authorize against GROUP Describe. + let resource = if req.key_type == 1 { + crate::acl::ResourceType::TransactionalId + } else { + crate::acl::ResourceType::Group + }; + // Below v4 the top-level fields are the only channel: there is no `coordinators` array. let legacy_denied = if version < BATCHED_FROM { keys.first() - .and_then(|k| authz.check(crate::acl::Operation::Describe, crate::acl::ResourceType::Group, k).err()) + .and_then(|k| authz.check(crate::acl::Operation::Describe, resource, k).err()) } else { None }; @@ -44,7 +52,7 @@ pub fn find_coordinator( coordinators: keys .into_iter() .map(|key| { - let denied = authz.check(crate::acl::Operation::Describe, crate::acl::ResourceType::Group, &key).err(); + let denied = authz.check(crate::acl::Operation::Describe, resource, &key).err(); Coordinator { key, node_id: if denied.is_some() { -1 } else { cfg.node_id }, diff --git a/extension/src/handlers/init_producer_id.rs b/extension/src/handlers/init_producer_id.rs index eea36a4..2ecd472 100644 --- a/extension/src/handlers/init_producer_id.rs +++ b/extension/src/handlers/init_producer_id.rs @@ -13,12 +13,23 @@ pub fn handle( req: &InitProducerIdRequest, authz: &crate::acl::Authz, ) -> Result { - // IDEMPOTENT_WRITE on the cluster, as Kafka requires to take a producer id. - if let Err(code) = authz.check( - crate::acl::Operation::IdempotentWrite, - crate::acl::ResourceType::Cluster, - "kafka-cluster", - ) { + let txn_id = req.transactional_id.as_deref().filter(|s| !s.is_empty()); + // Transactional producers need WRITE on TRANSACTIONAL_ID; plain idempotent producers + // need IDEMPOTENT_WRITE on the cluster, matching Kafka. + let auth_res = if let Some(id) = txn_id { + authz.check( + crate::acl::Operation::Write, + crate::acl::ResourceType::TransactionalId, + id, + ) + } else { + authz.check( + crate::acl::Operation::IdempotentWrite, + crate::acl::ResourceType::Cluster, + "kafka-cluster", + ) + }; + if let Err(code) = auth_res { return Ok(InitProducerIdResponse { throttle_time_ms: 0, error_code: code.code(), @@ -27,7 +38,6 @@ pub fn handle( ..Default::default() }); } - let txn_id = req.transactional_id.as_deref().filter(|s| !s.is_empty()); // Before the epoch moves: the abort is performed at the epoch the transaction ran under. if let Some(id) = txn_id { // Serialised with the instance being fenced, or its transaction could begin unseen diff --git a/extension/src/handlers/produce.rs b/extension/src/handlers/produce.rs index 617135d..18bb097 100644 --- a/extension/src/handlers/produce.rs +++ b/extension/src/handlers/produce.rs @@ -734,6 +734,16 @@ fn write_partition( Decision::Append(idem) => Some(idem), Decision::Duplicate { base_offset } => { base.get_or_insert(*base_offset); + // If a crash left `first_offset = -1` on an ongoing transaction for this + // partition, stamp it from the duplicate's offset before returning success. + if view.is_transactional() && view.producer_id() >= 0 { + crate::storage::pmeta::stamp_txn_partition( + view.producer_id(), + plan.tid, + plan.index, + *base_offset, + )?; + } continue; } Decision::DuplicateOf(j) => { diff --git a/extension/src/handlers/share_group.rs b/extension/src/handlers/share_group.rs index ef730a5..f959c39 100644 --- a/extension/src/handlers/share_group.rs +++ b/extension/src/handlers/share_group.rs @@ -1142,7 +1142,29 @@ fn acquire_and_read( let hwm = store .high_watermark(topic, partition) .map_err(|e| HandlerError::Internal(e.to_string()))?; - let from = start_offset(group, topic, partition)?; + let log_start = store + .log_start_offset(topic, partition) + .map_err(|e| HandlerError::Internal(e.to_string()))?; + let mut from = start_offset(group, topic, partition)?; + // If retention or DeleteRecords moved log_start past the share group's start offset, + // advance the share group to log_start instead of failing forever on OffsetOutOfRange. + if from < log_start { + from = log_start; + Spi::run_with_args( + "INSERT INTO kafgres_share_offsets (group_id, topic_id, partition, start_offset) + VALUES ($1, $2::oid, $3, $4) + ON CONFLICT (group_id, topic_id, partition) DO UPDATE + SET start_offset = GREATEST(kafgres_share_offsets.start_offset, EXCLUDED.start_offset)", + &[group.into(), (topic as i32).into(), partition.into(), log_start.into()], + ) + .map_err(|e| HandlerError::Internal(e.to_string()))?; + Spi::run_with_args( + "DELETE FROM kafgres_share_inflight + WHERE group_id = $1 AND topic_id = $2::oid AND partition = $3 AND record_offset < $4", + &[group.into(), (topic as i32).into(), partition.into(), log_start.into()], + ) + .map_err(|e| HandlerError::Internal(e.to_string()))?; + } if hwm <= from { return Ok((Vec::new(), Vec::new())); } diff --git a/extension/src/handlers/topics.rs b/extension/src/handlers/topics.rs index 85bfd87..2e56ae8 100644 --- a/extension/src/handlers/topics.rs +++ b/extension/src/handlers/topics.rs @@ -161,7 +161,10 @@ pub fn delete_topics( Some("unknown topic".to_string()), name.clone(), ), - Some((_, real_name)) => match meta::delete_topic(&real_name) { + Some((_, real_name)) => match crate::dbtx::atomically( + || meta::delete_topic(&real_name), + |message| TopicError::Internal(format!("delete aborted: {message}")), + ) { Ok(true) => (ErrorCode::None, None, Some(real_name)), Ok(false) => ( ErrorCode::UnknownTopicOrPartition, diff --git a/extension/src/handlers/txn.rs b/extension/src/handlers/txn.rs index c88d41a..6295a63 100644 --- a/extension/src/handlers/txn.rs +++ b/extension/src/handlers/txn.rs @@ -214,6 +214,7 @@ pub fn hold_for_produce(transactional_id: &str, producer_id: i64) -> Result<(), pub fn handle_add_partitions( req: &AddPartitionsToTxnRequest, version: i16, + authz: &crate::acl::Authz, ) -> Result { // v4+ is the broker-to-broker batched shape, and this cluster has no peers. An empty // `results_by_transaction` would read as "all partitions verified", so refuse the request whole. @@ -236,13 +237,57 @@ pub fn handle_add_partitions( ) }; + if let Err(auth_code) = authz.check( + crate::acl::Operation::Write, + crate::acl::ResourceType::TransactionalId, + &txn_id, + ) { + let results: Vec = topics + .iter() + .map(|t| AddPartitionsToTxnTopicResult { + name: t.name.clone(), + results_by_partition: t + .partitions + .iter() + .map(|p| AddPartitionsToTxnPartitionResult { + partition_index: *p, + partition_error_code: auth_code.code(), + ..Default::default() + }) + .collect(), + ..Default::default() + }) + .collect(); + return Ok(AddPartitionsToTxnResponse { + throttle_time_ms: 0, + error_code: 0, + results_by_topic_v3_and_below: results, + results_by_transaction: Vec::new(), + ..Default::default() + }); + } + let admitted = verdict(&txn_id, producer_id, epoch)?; let code = admitted.err().map_or(ErrorCode::None, |v| v.code(version)); + let mut topic_codes: Vec = Vec::with_capacity(topics.len()); if let Ok(admitted) = admitted { - begin_or_continue(admitted, &txn_id).map_err(|e| HandlerError::Internal(e.to_string()))?; - + let mut begun = false; for topic in &topics { + if let Err(tc) = authz.check( + crate::acl::Operation::Write, + crate::acl::ResourceType::Topic, + &topic.name, + ) { + topic_codes.push(tc); + continue; + } + topic_codes.push(ErrorCode::None); + if !begun { + begin_or_continue(admitted, &txn_id) + .map_err(|e| HandlerError::Internal(e.to_string()))?; + begun = true; + } let topic_id = crate::meta::topic_id_by_name(&topic.name) .map_err(|e| HandlerError::Internal(e.to_string()))?; let Some(topic_id) = topic_id else { continue }; @@ -257,18 +302,21 @@ pub fn handle_add_partitions( .map_err(|e| HandlerError::Internal(e.to_string()))?; } } + } else { + topic_codes.resize(topics.len(), code); } let results: Vec = topics .iter() - .map(|t| AddPartitionsToTxnTopicResult { + .zip(topic_codes.iter()) + .map(|(t, &tc)| AddPartitionsToTxnTopicResult { name: t.name.clone(), results_by_partition: t .partitions .iter() .map(|p| AddPartitionsToTxnPartitionResult { partition_index: *p, - partition_error_code: code.code(), + partition_error_code: tc.code(), ..Default::default() }) .collect(), @@ -440,7 +488,11 @@ fn produce_verdict( /// /// At v5 the epoch also rotates (KIP-890 part two): the response carries a fresh epoch so /// the producer's next transaction starts without an `InitProducerId` round trip. -pub fn handle_end_txn(req: &EndTxnRequest, version: i16) -> Result { +pub fn handle_end_txn( + req: &EndTxnRequest, + version: i16, + authz: &crate::acl::Authz, +) -> Result { // The v5 fields are ignorable and default to -1, which a client may read as an epoch, // so every early return below carries the caller's own pair. let unchanged = |code: ErrorCode| EndTxnResponse { @@ -455,6 +507,13 @@ pub fn handle_end_txn(req: &EndTxnRequest, version: i16) -> Result Result { retired_producer_id = NULL, retired_epoch = NULL, retired_committed = NULL - WHERE producer_id = $1 + WHERE producer_id = $1 AND producer_epoch < $2 RETURNING producer_epoch) SELECT (SELECT producer_epoch FROM up)", - &[producer_id.into()], + &[producer_id.into(), (i16::MAX as i32).into()], ) .map_err(|e| HandlerError::Internal(e.to_string()))?; - Ok(epoch.unwrap_or(-1)) + if let Some(e) = epoch { + return Ok(e); + } + // Either the row is already gone, or it hit the smallint epoch ceiling (i16::MAX). + // At the ceiling, retire the old producer_id and allocate a fresh one at epoch 0 so + // the old instance is fenced without overflowing smallint. + let at_ceiling: Option = Spi::get_one_with_args( + "WITH gone AS ( + DELETE FROM kafgres_producers + WHERE producer_id = $1 AND producer_epoch >= $2 + RETURNING COALESCE(transactional_id, '') AS tid) + SELECT (SELECT tid FROM gone)", + &[producer_id.into(), (i16::MAX as i32).into()], + ) + .map_err(|e| HandlerError::Internal(e.to_string()))?; + if let Some(tid) = at_ceiling { + Spi::run_with_args( + "DELETE FROM kafgres_producer_batches WHERE producer_id = $1", + &[producer_id.into()], + ) + .map_err(|e| HandlerError::Internal(e.to_string()))?; + if !tid.is_empty() { + let _ = crate::producer::init_producer_id(Some(&tid)) + .map_err(|e| HandlerError::Internal(e.to_string()))?; + } + return Ok(0); + } + Ok(-1) } /// `25 AddOffsetsToTxn` — the transaction will also commit consumer offsets. Committed pub fn handle_add_offsets( req: &AddOffsetsToTxnRequest, version: i16, + authz: &crate::acl::Authz, ) -> Result { + if let Err(code) = authz.check( + crate::acl::Operation::Write, + crate::acl::ResourceType::TransactionalId, + &req.transactional_id, + ) { + return Ok(AddOffsetsToTxnResponse { + throttle_time_ms: 0, + error_code: code.code(), + ..Default::default() + }); + } + if let Err(code) = authz.check( + crate::acl::Operation::Read, + crate::acl::ResourceType::Group, + &req.group_id, + ) { + return Ok(AddOffsetsToTxnResponse { + throttle_time_ms: 0, + error_code: code.code(), + ..Default::default() + }); + } let code = match verdict(&req.transactional_id, req.producer_id, req.producer_epoch)? { Err(v) => v.code(version), Ok(admitted) => { @@ -825,7 +942,48 @@ pub fn handle_add_offsets( pub fn handle_txn_offset_commit( req: &TxnOffsetCommitRequest, version: i16, + authz: &crate::acl::Authz, ) -> Result { + let auth_err = authz + .check( + crate::acl::Operation::Write, + crate::acl::ResourceType::TransactionalId, + &req.transactional_id, + ) + .err() + .or_else(|| { + authz + .check( + crate::acl::Operation::Read, + crate::acl::ResourceType::Group, + &req.group_id, + ) + .err() + }); + if let Some(auth_code) = auth_err { + let topics = req + .topics + .iter() + .map(|t| TxnOffsetCommitResponseTopic { + name: t.name.clone(), + partitions: t + .partitions + .iter() + .map(|p| TxnOffsetCommitResponsePartition { + partition_index: p.partition_index, + error_code: auth_code.code(), + ..Default::default() + }) + .collect(), + ..Default::default() + }) + .collect(); + return Ok(TxnOffsetCommitResponse { + throttle_time_ms: 0, + topics, + ..Default::default() + }); + } // Reported per partition, and a stale epoch is INVALID_PRODUCER_EPOCH at every // version, as Kafka answers it; the other coordinator APIs answer PRODUCER_FENCED. let admitted = verdict(&req.transactional_id, req.producer_id, req.producer_epoch)?; @@ -953,73 +1111,95 @@ pub fn handle_txn_offset_commit( /// Abort transactions whose producer stopped talking to us. Without this, the LSO held by pub fn expire_stale_transactions() -> Result { - let now = now_millis(); - // Bounded: ending thousands in one pass would hold the worker off Fetch, and the next + use std::time::{Duration, Instant}; + + // Bounded per sweep with a time budget so a backlog clears quickly without stalling Fetch. const MAX_PER_SWEEP: i64 = 64; - let mut stale: Vec<(i64, i16)> = Spi::connect(|client| { - let rows = client.select( - "SELECT producer_id, producer_epoch FROM kafgres_txns - WHERE state = 'ongoing' AND $1 - started_at > timeout_ms - ORDER BY started_at - LIMIT $2", - None, - &[now.into(), MAX_PER_SWEEP.into()], - )?; - let mut out = Vec::new(); - for row in rows { - if let (Some(p), Some(e)) = (row.get::(1)?, row.get::(2)?) { - out.push((p, e as i16)); + const BUDGET: Duration = Duration::from_millis(200); + let started = Instant::now(); + let mut total_done = 0usize; + + loop { + let now = now_millis(); + let mut stale: Vec<(i64, i16)> = Spi::connect(|client| { + let rows = client.select( + "SELECT producer_id, producer_epoch FROM kafgres_txns + WHERE state = 'ongoing' AND $1 - started_at > timeout_ms + ORDER BY started_at + LIMIT $2", + None, + &[now.into(), MAX_PER_SWEEP.into()], + )?; + let mut out = Vec::new(); + for row in rows { + if let (Some(p), Some(e)) = (row.get::(1)?, row.get::(2)?) { + out.push((p, e as i16)); + } } - } - Ok::<_, pgrx::spi::Error>(out) - }) - .map_err(|e| HandlerError::Internal(e.to_string()))?; - - // Locked one at a time in ascending producer id, the order a Produce request takes them - // in (`hold_for_produce`): locking the whole batch oldest-first could deadlock with a - // request carrying several transactional producers. Staleness is re-checked under the lock. - stale.sort_unstable_by_key(|&(producer_id, _)| producer_id); - let mut done = 0; - for (producer_id, _) in stale { - let locked: Option = Spi::get_one_with_args( - "SELECT (SELECT producer_epoch FROM kafgres_txns - WHERE producer_id = $1 AND state = 'ongoing' - AND $2 - started_at > timeout_ms - FOR UPDATE)", - &[producer_id.into(), now.into()], - ) + Ok::<_, pgrx::spi::Error>(out) + }) .map_err(|e| HandlerError::Internal(e.to_string()))?; - let Some(epoch) = locked.map(|e| e as i16) else { continue }; - // Abort, then fence — both in this one Postgres transaction: inside it the fence - match finish_transaction(producer_id, epoch, false)? { - // Ended underneath us between the SELECT and here, or never begun (state - // `empty`): nothing to abort and nothing to fence. - Finish::NotOurs | Finish::NotOpen { .. } => continue, - // Already forced by an operator; `finish_transaction` fenced on its way out. - Finish::Overridden => { - done += 1; - continue; - } - Finish::Ended => {} - } - // The fence makes expiry safe: the producer may just be slow, and unfenced it keeps - let fenced_epoch = fence(producer_id)?; + let fetched = stale.len(); + if fetched == 0 { + break; + } - if fenced_epoch < 0 { - log!( - "kafgres: aborted transaction for producer {producer_id} — no EndTxn within \ - its transaction timeout; its producer state was already gone" - ); - } else { - log!( - "kafgres: aborted transaction for producer {producer_id} — no EndTxn within \ - its transaction timeout; fenced at epoch {fenced_epoch}" + // Locked one at a time in ascending producer id, the order a Produce request takes them + // in (`hold_for_produce`): locking the whole batch oldest-first could deadlock with a + // request carrying several transactional producers. Each expiry runs in its own + // subtransaction so one failing producer cannot roll back or stall the rest. + stale.sort_unstable_by_key(|&(producer_id, _)| producer_id); + let mut batch_done = 0usize; + for (producer_id, _) in stale { + let res: Result = crate::dbtx::atomically( + || { + let locked: Option = Spi::get_one_with_args( + "SELECT (SELECT producer_epoch FROM kafgres_txns + WHERE producer_id = $1 AND state = 'ongoing' + AND $2 - started_at > timeout_ms + FOR UPDATE)", + &[producer_id.into(), now.into()], + ) + .map_err(|e| HandlerError::Internal(e.to_string()))?; + let Some(epoch) = locked.map(|e| e as i16) else { + return Ok(false); + }; + match finish_transaction(producer_id, epoch, false)? { + Finish::NotOurs | Finish::NotOpen { .. } => return Ok(false), + Finish::Overridden => return Ok(true), + Finish::Ended => {} + } + let fenced_epoch = fence(producer_id)?; + if fenced_epoch < 0 { + log!( + "kafgres: aborted transaction for producer {producer_id} — no EndTxn within \ + its transaction timeout; its producer state was already gone" + ); + } else { + log!( + "kafgres: aborted transaction for producer {producer_id} — no EndTxn within \ + its transaction timeout; fenced at epoch {fenced_epoch}" + ); + } + Ok(true) + }, + |msg| HandlerError::Internal(msg.to_string()), ); + match res { + Ok(true) => batch_done += 1, + Ok(false) => {} + Err(e) => { + log!("kafgres: failed to expire stale transaction for producer {producer_id}: {e}"); + } + } + } + total_done += batch_done; + if (fetched as i64) < MAX_PER_SWEEP || batch_done == 0 || started.elapsed() >= BUDGET { + break; } - done += 1; } - Ok(done) + Ok(total_done) } /// Append one partition's control batch and, on an abort, record the range it covers. @@ -1065,6 +1245,210 @@ fn append_marker( Ok(()) } +/// Reconcile `kafgres_txn_aborted` and `kafgres_txn_partitions` against the recovered log end +/// at startup or promotion. +/// +/// Handles both directions of WAL/segment skew: +/// 1. WAL ahead of segment (power cut or lagging follower): +/// - Abort-index rows wholly past `end` are deleted so reused offsets are not hidden. +/// - Abort-index rows whose data survived (`first_offset < end`) but whose ABORT marker +/// was lost (`last_offset >= end`) get a fresh ABORT control batch appended and fsynced +/// so `read_committed` consumers terminate the abort instead of hiding later commits. +/// 2. Segment ahead of WAL (failover when WAL lags the segment): +/// - Scans the recent tail for ABORT control batches missing from `kafgres_txn_aborted` +/// and inserts the missing abort-index rows so aborted data is never exposed. +pub fn reconcile_transactions( + store: &mut dyn crate::storage::LogStore, + topic_id: u32, + partition: i32, + end: i64, +) -> Result<(), HandlerError> { + use kafgres_codec::records::{ControlBatchType, LENGTH_OFFSET}; + use std::collections::HashMap; + + // Reset first_offset for any ongoing transaction whose data did not survive. + Spi::run_with_args( + "UPDATE kafgres_txn_partitions SET first_offset = -1 + WHERE topic_id = $1::oid AND partition = $2 AND first_offset >= $3", + &[(topic_id as i32).into(), partition.into(), end.into()], + ) + .map_err(|e| HandlerError::Internal(e.to_string()))?; + + // Drop abort-index rows whose entire range (data + marker) is past the recovered log end. + Spi::run_with_args( + "DELETE FROM kafgres_txn_aborted + WHERE topic_id = $1::oid AND partition = $2 AND first_offset >= $3", + &[(topic_id as i32).into(), partition.into(), end.into()], + ) + .map_err(|e| HandlerError::Internal(e.to_string()))?; + + // Re-append missing ABORT markers for rows whose data survived but marker was lost. + let missing_markers: Vec<(i64, i64, i16)> = Spi::connect(|client| { + let rows = client.select( + "SELECT a.producer_id, a.first_offset, + COALESCE(p.producer_epoch, t.producer_epoch, 0)::int + FROM kafgres_txn_aborted a + LEFT JOIN kafgres_producers p ON p.producer_id = a.producer_id + LEFT JOIN kafgres_txns t ON t.producer_id = a.producer_id + WHERE a.topic_id = $1::oid AND a.partition = $2 + AND a.first_offset < $3 AND a.last_offset >= $3 + ORDER BY a.first_offset", + None, + &[(topic_id as i32).into(), partition.into(), end.into()], + )?; + let mut out = Vec::new(); + for row in rows { + if let (Some(pid), Some(first), Some(epoch)) = + (row.get::(1)?, row.get::(2)?, row.get::(3)?) + { + out.push((pid, first, epoch as i16)); + } + } + Ok::<_, pgrx::spi::Error>(out) + }) + .map_err(|e| HandlerError::Internal(e.to_string()))?; + + let mut need_sync = false; + for (producer_id, first_offset, epoch) in missing_markers { + let bytes = build_control_batch(producer_id, epoch, false); + let view = RecordBatch::new(bytes.clone()) + .map_err(|e| HandlerError::Internal(format!("control batch: {e:?}")))?; + let batch = RawBatch { + bytes: bytes.to_vec(), + record_count: view.record_count(), + last_offset_delta: view.last_offset_delta(), + max_timestamp: view.max_timestamp(), + producer_id, + producer_epoch: epoch, + base_sequence: -1, + is_transactional: true, + is_control: true, + }; + let marker_offset = store + .append(topic_id, partition, batch, None) + .map_err(|e| HandlerError::Internal(format!("re-appending ABORT marker: {e}")))?; + crate::storage::pmeta::record_aborted_txn( + topic_id, + partition, + producer_id, + first_offset, + marker_offset, + ) + .map_err(|e| HandlerError::Internal(format!("updating aborted range: {e}")))?; + need_sync = true; + log!( + "kafgres: re-appended missing ABORT marker for producer {producer_id} on \ + topic {topic_id} partition {partition} at offset {marker_offset} \ + (aborted range [{first_offset}, {marker_offset}])" + ); + } + if need_sync { + store + .sync_partition(topic_id, partition) + .map_err(|e| HandlerError::Internal(format!("syncing reconciled markers: {e}")))?; + } + + // Segment ahead of WAL (e.g. async failover where WAL lagged segment replication): + // scan the tail after window_checkpoint for ABORT control batches missing from the index. + let log_start = store + .log_start_offset(topic_id, partition) + .map_err(|e| HandlerError::Internal(e.to_string()))?; + if end <= log_start { + return Ok(()); + } + let checkpoint: Option = Spi::get_one_with_args( + "SELECT (SELECT window_checkpoint FROM kafgres_partitions + WHERE topic_id = $1::oid AND partition = $2)", + &[(topic_id as i32).into(), partition.into()], + ) + .map_err(|e| HandlerError::Internal(e.to_string()))?; + let scan_from = checkpoint + .unwrap_or_else(|| end.saturating_sub(100_000)) + .max(log_start) + .min(end); + let mut at = scan_from; + let mut first_seen: HashMap = HashMap::new(); + while at < end { + let slice = store + .read( + topic_id, + partition, + at, + 4 << 20, + crate::storage::IsolationLevel::ReadUncommitted, + ) + .map_err(|e| HandlerError::Internal(e.to_string()))?; + if slice.bytes.is_empty() { + break; + } + let mut pos = 0usize; + let mut advanced_to = at; + while pos + LENGTH_OFFSET + 4 <= slice.bytes.len() { + let len = i32::from_be_bytes( + slice.bytes[pos + LENGTH_OFFSET..pos + LENGTH_OFFSET + 4] + .try_into() + .expect("4 bytes"), + ); + let total = LENGTH_OFFSET + 4 + len.max(0) as usize; + if len <= 0 || pos + total > slice.bytes.len() { + break; + } + let bytes = kafgres_codec::bytes::Bytes::copy_from_slice(&slice.bytes[pos..pos + total]); + pos += total; + let Ok(batch) = RecordBatch::new(bytes) else { continue }; + let batch_base = batch.base_offset(); + if batch_base >= end { + advanced_to = end; + break; + } + advanced_to = (batch_base + batch.last_offset_delta() as i64 + 1).max(advanced_to); + let pid = batch.producer_id(); + if pid < 0 || !batch.is_transactional() { + continue; + } + if !batch.is_control() { + first_seen.entry(pid).or_insert(batch_base); + continue; + } + match batch.control_type() { + Some(ControlBatchType::Commit) => { + first_seen.remove(&pid); + } + Some(ControlBatchType::Abort) => { + let first = first_seen.remove(&pid).unwrap_or(scan_from); + let already = crate::storage::pmeta::aborted_at( + topic_id, + partition, + pid, + batch_base, + ) + .map_err(|e| HandlerError::Internal(e.to_string()))?; + if !already { + crate::storage::pmeta::record_aborted_txn( + topic_id, + partition, + pid, + first, + batch_base, + ) + .map_err(|e| HandlerError::Internal(e.to_string()))?; + log!( + "kafgres: reconstructed missing abort-index row for producer {pid} \ + on topic {topic_id} partition {partition} [{first}, {batch_base}]" + ); + } + } + _ => {} + } + } + if advanced_to <= at { + break; + } + at = advanced_to; + } + Ok(()) +} + /// End **one partition** of a transaction — the protocol's own granularity, since Kafka fn finish_partition( producer_id: i64, @@ -1105,6 +1489,9 @@ fn finish_partition( first_offset, committed, )?; + store + .sync_partition(topic_id, partition) + .map_err(|e| HandlerError::Internal(format!("syncing transaction marker: {e}")))?; Spi::run_with_args( "DELETE FROM kafgres_txn_partitions diff --git a/extension/src/init220.rs b/extension/src/init220.rs new file mode 100644 index 0000000..583ddcd --- /dev/null +++ b/extension/src/init220.rs @@ -0,0 +1,49 @@ +//! Record the owning role of each CDC mapping so the CDC worker renders mappings under +//! the owner's privileges rather than as the bootstrap superuser. + +use crate::ddl::run_ddl; + +pub fn init_220() { + run_ddl( + "ALTER TABLE kafgres_cdc_mappings + ADD COLUMN IF NOT EXISTS owner text NOT NULL DEFAULT current_user", + "add cdc mapping owner column", + ); + + // Defence in depth: even if an operator grants direct INSERT/UPDATE on + // kafgres_cdc_mappings, a non-superuser cannot claim another role's ownership or + // modify another role's mapping. + run_ddl( + "CREATE OR REPLACE FUNCTION kafgres_cdc_mappings_enforce_owner() + RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN + IF NOT (SELECT rolsuper FROM pg_catalog.pg_roles WHERE rolname = current_user) THEN + IF TG_OP = 'INSERT' THEN + IF NEW.owner IS DISTINCT FROM current_user THEN + RAISE EXCEPTION 'permission denied: cannot create CDC mapping owned by %', NEW.owner + USING ERRCODE = 'insufficient_privilege'; + END IF; + ELSIF TG_OP = 'UPDATE' THEN + IF OLD.owner IS DISTINCT FROM current_user OR NEW.owner IS DISTINCT FROM current_user THEN + RAISE EXCEPTION 'permission denied: cannot modify CDC mapping owned by %', OLD.owner + USING ERRCODE = 'insufficient_privilege'; + END IF; + END IF; + END IF; + RETURN NEW; + END; + $$", + "create cdc mapping owner enforcement function", + ); + + run_ddl( + "DROP TRIGGER IF EXISTS kafgres_cdc_mappings_owner_guard ON kafgres_cdc_mappings", + "drop old cdc mapping owner guard trigger", + ); + run_ddl( + "CREATE TRIGGER kafgres_cdc_mappings_owner_guard + BEFORE INSERT OR UPDATE ON kafgres_cdc_mappings + FOR EACH ROW EXECUTE FUNCTION kafgres_cdc_mappings_enforce_owner()", + "create cdc mapping owner guard trigger", + ); +} diff --git a/extension/src/lib.rs b/extension/src/lib.rs index 2751b9c..2d0aa99 100644 --- a/extension/src/lib.rs +++ b/extension/src/lib.rs @@ -40,6 +40,7 @@ mod init180; mod init190; mod init200; mod init210; +mod init220; pub mod quota; pub mod meta; pub mod plan; @@ -943,6 +944,7 @@ pub(crate) fn ensure_tables_exist() { init190::init_190(); init200::init_200(); init210::init_210(); + init220::init_220(); } pgrx::extension_sql!( diff --git a/extension/src/meta.rs b/extension/src/meta.rs index ee4d13e..7da2357 100644 --- a/extension/src/meta.rs +++ b/extension/src/meta.rs @@ -358,6 +358,14 @@ pub fn delete_topic(name: &str) -> Result { None => return Ok(false), }; + // Take every lock before mutating anything: a lock_timeout here rolls back cleanly + // without touching partition files or shared memory. + // Serialise against the archiver: otherwise the DELETE can miss a row it wrote but not committed, orphaning it on the dropped id. + Spi::run_with_args( + "SELECT pg_advisory_xact_lock($1)", + &[crate::archive::ARCHIVE_LOCK_KEY.into()], + )?; + let mut store = crate::storage::open(); let parts: Vec = Spi::connect(|client| { let rows = client.select( @@ -374,11 +382,6 @@ pub fn delete_topic(name: &str) -> Result { Ok::<_, spi::Error>(out) })?; - for p in parts { - crate::storage::LogStore::drop_partition(&mut *store, topic_id, p) - .map_err(|e| TopicError::Internal(e.to_string()))?; - } - Spi::run_with_args( "DELETE FROM kafgres_producer_batches WHERE topic_id = $1::oid", &[(topic_id as i32).into()], @@ -397,11 +400,6 @@ pub fn delete_topic(name: &str) -> Result { "DELETE FROM kafgres_txn_offsets WHERE topic_id = $1::oid", &[(topic_id as i32).into()], )?; - // Serialise against the archiver: otherwise the DELETE can miss a row it wrote but not committed, orphaning it on the dropped id. - Spi::run_with_args( - "SELECT pg_advisory_xact_lock($1)", - &[crate::archive::ARCHIVE_LOCK_KEY.into()], - )?; // The archived *files* are not ours to remove; the rows go because a reused topic id would inherit a false "archived" claim. let orphaned: i64 = Spi::get_one_with_args( @@ -420,6 +418,12 @@ pub fn delete_topic(name: &str) -> Result { "DELETE FROM kafgres_segment_archive WHERE topic_id = $1::oid", &[(topic_id as i32).into()], )?; + + for p in parts { + crate::storage::LogStore::drop_partition(&mut *store, topic_id, p) + .map_err(|e| TopicError::Internal(e.to_string()))?; + } + Spi::run_with_args( "DELETE FROM kafgres_topics WHERE topic_id = $1::oid", &[(topic_id as i32).into()], diff --git a/extension/src/producer.rs b/extension/src/producer.rs index 39d7fc9..ce045c8 100644 --- a/extension/src/producer.rs +++ b/extension/src/producer.rs @@ -49,6 +49,22 @@ pub fn init_producer_id(transactional_id: Option<&str>) -> Result<(i64, i16), sp // Bump the epoch so any older instance of the same transactional id is fenced. The // retired pair goes with it: a retried EndTxn from that instance must be fenced too, // not answered NONE with the epoch this new instance now owns. + // At `i16::MAX` (`smallint` ceiling), rotate to a fresh producer_id at epoch 0, as Kafka does. + let at_ceiling: Option = Spi::get_one_with_args( + "SELECT (SELECT producer_id FROM kafgres_producers + WHERE transactional_id = $1 AND producer_epoch >= $2)", + &[txn_id.into(), (i16::MAX as i32).into()], + )?; + if let Some(old_id) = at_ceiling { + Spi::run_with_args( + "DELETE FROM kafgres_producer_batches WHERE producer_id = $1", + &[old_id.into()], + )?; + Spi::run_with_args( + "DELETE FROM kafgres_producers WHERE producer_id = $1", + &[old_id.into()], + )?; + } let row: Option = Spi::get_one_with_args( "WITH up AS ( INSERT INTO kafgres_producers (producer_id, producer_epoch, transactional_id) @@ -59,9 +75,10 @@ pub fn init_producer_id(transactional_id: Option<&str>) -> Result<(i64, i16), sp retired_epoch = NULL, retired_committed = NULL, last_ts = now() + WHERE kafgres_producers.producer_epoch < $2 RETURNING producer_id, producer_epoch) SELECT (SELECT producer_id || '|' || producer_epoch FROM up)", - &[txn_id.into()], + &[txn_id.into(), (i16::MAX as i32).into()], )?; if let Some(s) = row { let mut it = s.split('|'); @@ -304,13 +321,21 @@ pub fn record( ], )?; - // Keep `last_ts` roughly current without an UPDATE per batch: writes at most once per + // Keep `last_ts` roughly current without an UPDATE per batch. Scale refresh granularity + // to a quarter of `producer_id_expiration_ms` so active producers are never expired when + // the operator configures a short expiration window. + let exp_ms = crate::producer_retention().expiration_ms; + let granularity = if exp_ms > 0 { + ((exp_ms as f64) / 1000.0 / 4.0).clamp(1.0, LAST_TS_GRANULARITY_SECS) + } else { + LAST_TS_GRANULARITY_SECS + }; crate::plan::run( "UPDATE kafgres_producers SET last_ts = now() WHERE producer_id = $1 AND last_ts < now() - make_interval(secs => $2)", - &[producer_id.into(), LAST_TS_GRANULARITY_SECS.into()], + &[producer_id.into(), granularity.into()], )?; Ok(()) } @@ -580,6 +605,18 @@ pub fn rebuild_window( if pid < 0 || epoch < 0 || first < 0 || batch.is_control() { continue; } + // If a crash occurred between appending a transactional batch and stamping + // `kafgres_txn_partitions.first_offset`, restore `first_offset` now so the batch + // is held below the LSO and recorded if the transaction aborts. + if batch.is_transactional() { + crate::storage::pmeta::stamp_txn_partition( + pid, + topic_id, + partition, + batch.base_offset(), + ) + .map_err(|e| e.to_string())?; + } let last = increment_sequence(first, batch.last_offset_delta()); let state = match newest.get(&pid) { Some(s) => *s, diff --git a/extension/src/replication.rs b/extension/src/replication.rs index 625858b..d423cd8 100644 --- a/extension/src/replication.rs +++ b/extension/src/replication.rs @@ -455,7 +455,11 @@ fn partitions_to_follow(store: &mut dyn crate::storage::LogStore) -> Want { .unwrap_or_default() .into_iter() .filter_map(|(id, name, part, epoch)| { - store.high_watermark(id, part).ok().map(|end| (id, name, part, end, epoch)) + let end = store.high_watermark(id, part).ok()?; + // Report the epoch of our actual local tail, not the WAL-replicated leader_epoch, + // so a rejoined old primary detects and truncates its divergent tail. + let local_epoch = store.last_batch_epoch(id, part).ok().flatten().unwrap_or(epoch); + Some((id, name, part, end, local_epoch)) }) .collect() } @@ -517,6 +521,7 @@ impl Follower { if pulled.is_empty() { break; } + still_following()?; applied += apply(&mut *store, &pulled)?; still_following()?; if started.elapsed() >= ROUND_BUDGET { diff --git a/extension/src/server/dispatch.rs b/extension/src/server/dispatch.rs index b4f4784..bad129b 100644 --- a/extension/src/server/dispatch.rs +++ b/extension/src/server/dispatch.rs @@ -315,21 +315,23 @@ pub(super) fn dispatch( } add_partitions_to_txn_request::AddPartitionsToTxnRequest::API_KEY => { c.tx(|r: &add_partitions_to_txn_request::AddPartitionsToTxnRequest, e| { - handlers::txn::handle_add_partitions(r, e.version) + handlers::txn::handle_add_partitions(r, e.version, &e.authz) }) } add_offsets_to_txn_request::AddOffsetsToTxnRequest::API_KEY => { c.tx(|r: &add_offsets_to_txn_request::AddOffsetsToTxnRequest, e| { - handlers::txn::handle_add_offsets(r, e.version) + handlers::txn::handle_add_offsets(r, e.version, &e.authz) }) } txn_offset_commit_request::TxnOffsetCommitRequest::API_KEY => { c.tx(|r: &txn_offset_commit_request::TxnOffsetCommitRequest, e| { - handlers::txn::handle_txn_offset_commit(r, e.version) + handlers::txn::handle_txn_offset_commit(r, e.version, &e.authz) }) } end_txn_request::EndTxnRequest::API_KEY => { - c.tx(|r: &end_txn_request::EndTxnRequest, e| handlers::txn::handle_end_txn(r, e.version)) + c.tx(|r: &end_txn_request::EndTxnRequest, e| { + handlers::txn::handle_end_txn(r, e.version, &e.authz) + }) } write_txn_markers_request::WriteTxnMarkersRequest::API_KEY => { c.tx(|r: &write_txn_markers_request::WriteTxnMarkersRequest, e| { diff --git a/extension/src/server/mod.rs b/extension/src/server/mod.rs index 30cef0a..819a248 100644 --- a/extension/src/server/mod.rs +++ b/extension/src/server/mod.rs @@ -437,6 +437,7 @@ pub fn run(cfg: ClusterConfig, bind_host: &str, port: u16, tick: Duration) { checkpoint_producer_windows(&mut srv); expire_consumer_group_members(&srv); expire_share_group_state(&srv); + expire_stale_transactions_tick(&srv); expire_quota_windows(&mut srv); refresh_quotas(&mut srv); enforce_retention(&mut srv); @@ -1445,6 +1446,22 @@ fn raise_leader_epochs() -> bool { crate::producer::forget_past(topic_id, partition, end) .map_err(|e| HandlerError::Internal(e.to_string()))?; crate::producer::note_startup_end(topic_id, partition, end); + crate::handlers::txn::reconcile_transactions( + &mut *store, topic_id, partition, end, + )?; + // Clamp share-group offsets to the recovered log end so a power cut or + // failover truncation does not skip records refilled into the lost range. + pgrx::Spi::run_with_args( + "UPDATE kafgres_share_offsets + SET start_offset = $3 + WHERE topic_id = $1::oid AND partition = $2 AND start_offset > $3", + &[(topic_id as i32).into(), partition.into(), end.into()], + )?; + pgrx::Spi::run_with_args( + "DELETE FROM kafgres_share_inflight + WHERE topic_id = $1::oid AND partition = $2 AND record_offset >= $3", + &[(topic_id as i32).into(), partition.into(), end.into()], + )?; } Ok((highest, raised, boot)) }) @@ -1618,8 +1635,9 @@ fn expire_consumer_group_members(srv: &Server) { } } -fn enforce_retention(srv: &mut Server) { - if !srv.due(crate::retention_check_ticks()) { +fn expire_stale_transactions_tick(srv: &Server) { + const EVERY_N_TICKS: u64 = 2_000; // ~10s at the default 5ms tick, matching Kafka + if !srv.due(EVERY_N_TICKS) { return; } if let Err(e) = BackgroundWorker::transaction(|| { @@ -1627,6 +1645,12 @@ fn enforce_retention(srv: &mut Server) { }) { log!("kafgres: could not expire stale transactions: {e}"); } +} + +fn enforce_retention(srv: &mut Server) { + if !srv.due(crate::retention_check_ticks()) { + return; + } if crate::storage_engine_guc() == "segment" { match BackgroundWorker::transaction(|| { diff --git a/extension/src/storage/cursor.rs b/extension/src/storage/cursor.rs index d53f454..10896f1 100644 --- a/extension/src/storage/cursor.rs +++ b/extension/src/storage/cursor.rs @@ -143,6 +143,8 @@ impl RecordCursor { let batch = batch.map_err(|e| { StoreError::Io(format!("undecodable batch after offset {advanced}: {e}")) })?; + kafgres_codec::records::RecordBatch::validated(batch.as_bytes().clone()) + .map_err(|_| StoreError::CorruptBatch)?; if batch.base_offset() >= self.range.end { advanced = self.range.end; break; diff --git a/extension/src/storage/mod.rs b/extension/src/storage/mod.rs index 2d8a8d2..ec502fb 100644 --- a/extension/src/storage/mod.rs +++ b/extension/src/storage/mod.rs @@ -613,6 +613,79 @@ pub trait LogStore: Send { partition: i32, epoch: i32, ) -> StoreResult; + + /// The `partitionLeaderEpoch` of the last batch currently stored in this partition's + /// local log, if any. Used by standby replication so a rejoined old primary reports + /// the epoch of its actual local tail rather than the new leader's WAL-replicated epoch. + fn last_batch_epoch(&self, _topic: TopicId, _partition: i32) -> StoreResult> { + Ok(None) + } +} + +/// Like [`first_at_or_after`], but ignores records below `min_offset` (e.g. `log_start_offset`). +pub(crate) fn first_at_or_after_from( + bytes: kafgres_codec::bytes::Bytes, + timestamp: i64, + min_offset: i64, +) -> Option<(i64, i64)> { + let batch = kafgres_codec::records::RecordBatch::new(bytes).ok()?; + let base_offset = batch.base_offset(); + let base_ts = batch.base_timestamp(); + for rec in batch.records().ok()? { + let rec = rec.ok()?; + let off = base_offset + rec.offset_delta as i64; + if off < min_offset { + continue; + } + let ts = base_ts + rec.timestamp_delta; + if ts >= timestamp { + return Some((off, ts)); + } + } + None +} + +/// Truncate `bytes` before the first batch whose `last_offset >= cut`, returning the new +/// `next_offset` (`last_offset + 1` of the last kept batch, or `fallback_next` if none kept). +/// Used when `pmeta::aborted_txns` hits `MAX_ABORTED_PER_FETCH` so Fetch never returns batches +/// whose aborted status was omitted by the cap. +pub(crate) fn truncate_batches_at(bytes: &mut Vec, cut: i64, fallback_next: i64) -> i64 { + use kafgres_codec::records::{BASE_OFFSET_OFFSET, LAST_OFFSET_DELTA_OFFSET, LENGTH_OFFSET, RECORD_BATCH_OVERHEAD}; + + let mut pos = 0usize; + let mut new_next = fallback_next; + while pos + RECORD_BATCH_OVERHEAD <= bytes.len() { + let len = i32::from_be_bytes( + bytes[pos + LENGTH_OFFSET..pos + LENGTH_OFFSET + 4] + .try_into() + .expect("4 bytes"), + ); + if len <= 0 { + break; + } + let total = LENGTH_OFFSET + 4 + len as usize; + if pos + total > bytes.len() { + break; + } + let batch_base = i64::from_be_bytes( + bytes[pos + BASE_OFFSET_OFFSET..pos + BASE_OFFSET_OFFSET + 8] + .try_into() + .expect("8 bytes"), + ); + let last_delta = i32::from_be_bytes( + bytes[pos + LAST_OFFSET_DELTA_OFFSET..pos + LAST_OFFSET_DELTA_OFFSET + 4] + .try_into() + .expect("4 bytes"), + ); + let batch_last = batch_base + last_delta as i64; + if batch_last >= cut { + bytes.truncate(pos); + return new_next; + } + new_next = batch_last + 1; + pos += total; + } + new_next } #[cfg(test)] diff --git a/extension/src/storage/pmeta.rs b/extension/src/storage/pmeta.rs index 31a6164..2af5189 100644 --- a/extension/src/storage/pmeta.rs +++ b/extension/src/storage/pmeta.rs @@ -161,12 +161,27 @@ pub fn epoch_end_offset( let matched = match matched { Some(e) => e, - // Nothing at or below it: `-1` makes the client reset rather than truncate, so + // All epochs at or below `epoch` were collapsed by truncation (e.g. a power cut + // removed everything written in `epoch`). Answer with `epoch` and the next known + // epoch's start offset so clients truncate cleanly rather than falling back to + // `auto.offset.reset`. None => { - return Ok(EpochEnd { - leader_epoch: -1, - end_offset: log_start_offset(topic, partition)?, - }) + let next_start: Option = Spi::get_one_with_args( + "SELECT (SELECT min(start_offset) FROM kafgres_leader_epochs + WHERE topic_id = $1::oid AND partition = $2 AND leader_epoch > $3)", + &[(topic as i32).into(), partition.into(), epoch.into()], + ) + .map_err(spi_err)?; + return match next_start { + Some(s) => Ok(EpochEnd { + leader_epoch: epoch, + end_offset: s, + }), + None => Ok(EpochEnd { + leader_epoch: -1, + end_offset: log_start_offset(topic, partition)?, + }), + }; } }; diff --git a/extension/src/storage/segment.rs b/extension/src/storage/segment.rs index 489c5b3..be572ac 100644 --- a/extension/src/storage/segment.rs +++ b/extension/src/storage/segment.rs @@ -19,6 +19,71 @@ use super::{ TopicId, TxnContext, }; +// Deferred physical partition drops for the current Postgres transaction. +// `(topic, partition, subxid)` so a rolled-back subtransaction only cancels its own drops. +thread_local! { + static PENDING_DROPS: std::cell::RefCell>> = + const { std::cell::RefCell::new(None) }; +} + +fn defer_partition_drop(topic: TopicId, partition: i32) { + let subid = unsafe { pg_sys::GetCurrentSubTransactionId() }; + let first = PENDING_DROPS.with(|p| { + let mut p = p.borrow_mut(); + let first = p.is_none(); + p.get_or_insert_with(Vec::new).push((topic, partition, subid)); + first + }); + if first { + pgrx::register_xact_callback(pgrx::PgXactCallbackEvent::Commit, || { + let drops = PENDING_DROPS.with(|p| p.borrow_mut().take()); + if let Some(drops) = drops { + for (t, part, _) in drops { + execute_partition_drop(t, part); + } + } + }); + pgrx::register_xact_callback(pgrx::PgXactCallbackEvent::Abort, || { + PENDING_DROPS.with(|p| p.borrow_mut().take()); + }); + pgrx::register_subxact_callback(pgrx::PgSubXactCallbackEvent::AbortSub, |aborted, _| { + PENDING_DROPS.with(|p| { + if let Some(list) = p.borrow_mut().as_mut() { + list.retain(|&(_, _, s)| s != aborted); + } + }); + }); + } +} + +fn execute_partition_drop(topic: TopicId, partition: i32) { + let dir = data_path(&partition_dir(topic, partition)); + if let Err(e) = std::fs::remove_dir_all(&dir) { + if e.kind() != std::io::ErrorKind::NotFound { + log!("kafgres: failed to remove dropped partition {}: {e}", dir.display()); + } + } + let _ = std::fs::remove_dir(log_root().join(topic.to_string())); + + if let Some(plans) = PLANS.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { + plans.remove(&(topic, partition)); + } + super::forget_cleaned(topic, partition); + + { + let mut slots = SHARDS[shard_of(topic, partition)].exclusive(); + for slot in slots.iter_mut() { + if slot.topic == topic && slot.partition == partition { + *slot = Slot::default(); + } + } + } + if let Some(map) = HINTS.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { + map.remove(&(topic, partition)); + } + evict_active(topic, partition); +} + /// Under `$PGDATA` unless `kafgres.log_directory` says otherwise. const LOG_DIR: &str = "kafgres"; @@ -1411,6 +1476,39 @@ impl SegmentStore { last } + /// Truncate `.index` so no entry points at or past `valid_end` (or is out of order). + /// Called whenever recovery truncates the active `.log`. + fn truncate_index(topic: TopicId, partition: i32, base: i64, valid_end: u64) { + let path = data_path(&segment_path(topic, partition, base, "index")); + let Ok(vfd) = Vfd::open(&path, false) else { + return; + }; + let size = vfd.size().unwrap_or(0); + let mut buf = [0u8; INDEX_ENTRY]; + let mut at = 0u64; + let mut prev: Option<(i64, u64)> = None; + while at + INDEX_ENTRY as u64 <= size { + if vfd.read_at(&mut buf, at).unwrap_or(0) != INDEX_ENTRY { + break; + } + let rel = u32::from_be_bytes(buf[..4].try_into().expect("4 bytes")) as i64; + let pos = u32::from_be_bytes(buf[4..].try_into().expect("4 bytes")) as u64; + if pos >= valid_end { + break; + } + if let Some((pr, pp)) = prev { + if rel <= pr || pos <= pp { + break; + } + } + prev = Some((rel, pos)); + at += INDEX_ENTRY as u64; + } + if at < size { + let _ = vfd.truncate(at); + } + } + fn read_index( topic: TopicId, partition: i32, @@ -1426,6 +1524,7 @@ impl SegmentStore { let mut out = Vec::new(); let mut buf = [0u8; INDEX_ENTRY]; let mut at = 0u64; + let mut prev: Option<(i64, u64)> = None; while at + INDEX_ENTRY as u64 <= size { if vfd.read_at(&mut buf, at).unwrap_or(0) != INDEX_ENTRY { break; @@ -1435,6 +1534,12 @@ impl SegmentStore { if pos >= data_end { break; } + if let Some((pr, pp)) = prev { + if rel <= pr || pos <= pp { + break; + } + } + prev = Some((rel, pos)); out.push((base + rel, pos)); at += INDEX_ENTRY as u64; } @@ -1472,6 +1577,7 @@ impl SegmentStore { .get(base) .and_then(|entries| entries.iter().rev().find(|(b, _)| *b <= from).map(|(_, p)| *p)) .unwrap_or(0); + let mut used_hint = pos > 0; let mut header = [0u8; records::RECORD_BATCH_OVERHEAD]; while pos + header.len() as u64 <= data_end { if vfd.read_at(&mut header, pos)? != header.len() { @@ -1480,8 +1586,14 @@ impl SegmentStore { let Some(BatchSpan { total, base: batch_base, last: batch_last }) = batch_span(&header, pos, data_end) else { + if used_hint { + used_hint = false; + pos = 0; + continue; + } break; }; + used_hint = false; if batch_base >= ceiling { return Ok(None); } @@ -1604,6 +1716,9 @@ impl SegmentStore { ); vfd.truncate(pos)?; } + // Keep `.index` consistent with the recovered `.log` length so stale entries cannot + // survive past the cut and misdirect Fetch after the segment rolls. + Self::truncate_index(topic, partition, base, pos); Ok((index, pos, next_offset, max_timestamp)) } @@ -1667,6 +1782,9 @@ impl SegmentStore { let closing_base = st.active_base; let closing_bytes = st.active_bytes; with_active(topic, partition, closing_base, generation, |a| { + // Trim any trailing garbage from a previous failed write (e.g. ENOSPC) + // before sealing the segment so compaction and readers see clean EOF. + let _ = a.log.truncate(closing_bytes); a.log .writeback(a.writeback_from, closing_bytes.saturating_sub(a.writeback_from)); a.log.sync()?; @@ -1704,7 +1822,12 @@ impl SegmentStore { }; with_active(topic, partition, active_base, generation, |a| { - a.log.write_all_at(bytes, pos)?; + if let Err(e) = a.log.write_all_at(bytes, pos) { + // Trim any partial bytes written before ENOSPC/EIO so the active segment + // does not carry trailing garbage past `st.active_bytes`. + let _ = a.log.truncate(pos); + return Err(e); + } let end = pos + bytes.len() as u64; if end.saturating_sub(a.writeback_from) >= WRITEBACK_BYTES { a.log.writeback(a.writeback_from, end - a.writeback_from); @@ -2140,6 +2263,7 @@ impl LogStore for SegmentStore { entries.iter().rev().find(|(b, _)| *b <= next).map(|(_, p)| *p) }) .unwrap_or(0); + let mut used_hint = pos > 0; let mut header = [0u8; records::RECORD_BATCH_OVERHEAD]; while pos + header.len() as u64 <= data_end { @@ -2149,8 +2273,28 @@ impl LogStore for SegmentStore { let Some(BatchSpan { total, base: batch_base, last: batch_last }) = batch_span(&header, pos, data_end) else { + if used_hint { + // A stale or misaligned index hint must not skip the segment; + // fall back to a linear scan from offset 0. + log!( + "kafgres: ignoring bad index hint at pos {pos} in {}; \ + falling back to linear scan", + path.display() + ); + used_hint = false; + pos = 0; + continue; + } + if *base != st.active_base { + log!( + "kafgres: corrupt batch header at pos {pos} in sealed segment {}", + path.display() + ); + return Err(StoreError::CorruptBatch); + } break; }; + used_hint = false; // Wholly below the request; the batch containing `offset` is kept whole (the consumer if batch_last < offset { @@ -2244,6 +2388,9 @@ impl LogStore for SegmentStore { pmeta::aborted_txns(topic, partition, offset, next.max(offset + 1))?; aborted.extend(listed); aborted_cut_at = cut; + if let Some(cut) = aborted_cut_at { + next = super::truncate_batches_at(&mut out, cut, offset); + } } } @@ -2272,6 +2419,7 @@ impl LogStore for SegmentStore { } // The earliest offset whose timestamp is at or after `timestamp` — what `offsetsForTimes` + let log_start = self.log_start_offset(topic, partition)?; let bases_on_disk = Self::segment_bases(topic, partition)?; Self::with_slot(topic, partition, |st, hints| { let mut bases = bases_on_disk; @@ -2307,6 +2455,16 @@ impl LogStore for SegmentStore { { break; } + let batch_base = i64::from_be_bytes( + header[records::BASE_OFFSET_OFFSET..records::BASE_OFFSET_OFFSET + 8] + .try_into() + .expect("8 bytes"), + ); + let batch_last = batch_base + last_offset_delta_of(&header); + if batch_last < log_start { + pos += records::LENGTH_OFFSET as u64 + 4 + length as u64; + continue; + } let max_ts = i64::from_be_bytes( header[records::MAX_TIMESTAMP_OFFSET..records::MAX_TIMESTAMP_OFFSET + 8] .try_into() @@ -2320,10 +2478,13 @@ impl LogStore for SegmentStore { path.display() ))); } - return Ok(super::first_at_or_after( + if let Some(found) = super::first_at_or_after_from( kafgres_codec::bytes::Bytes::from(body), timestamp, - )); + log_start, + ) { + return Ok(Some(found)); + } } pos += records::LENGTH_OFFSET as u64 + 4 + length as u64; } @@ -2537,33 +2698,10 @@ impl LogStore for SegmentStore { fn drop_partition(&mut self, topic: TopicId, partition: i32) -> StoreResult<()> { pmeta::drop_partition(topic, partition)?; - let dir = data_path(&partition_dir(topic, partition)); - if let Err(e) = std::fs::remove_dir_all(&dir) { - if e.kind() != std::io::ErrorKind::NotFound { - return Err(StoreError::Io(format!("remove {}: {e}", dir.display()))); - } - } - // And the topic directory once its last partition is gone; `remove_dir` failing with - let _ = std::fs::remove_dir(log_root().join(topic.to_string())); - - if let Some(plans) = PLANS.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { - plans.remove(&(topic, partition)); - } - super::forget_cleaned(topic, partition); - - // Free the shared slot, or the partition keeps its append position across a - { - let mut slots = SHARDS[shard_of(topic, partition)].exclusive(); - for slot in slots.iter_mut() { - if slot.topic == topic && slot.partition == partition { - *slot = Slot::default(); - } - } - } - if let Some(map) = HINTS.lock().unwrap_or_else(|e| e.into_inner()).as_mut() { - map.remove(&(topic, partition)); - } - evict_active(topic, partition); + // Defer filesystem removal and shared-memory eviction until the surrounding Postgres + // transaction commits. If the transaction rolls back (e.g. a lock timeout on + // DeleteTopics), the partition directory and shared-memory slot stay intact. + defer_partition_drop(topic, partition); Ok(()) } @@ -2779,8 +2917,12 @@ impl LogStore for SegmentStore { Ok(removed) })?; - // The archive's record is now false: a row saying base N was archived vouches for bytes - crate::archive::forget_from(topic, partition, offset).map_err(StoreError::Io)?; + // The archive's record is now false: a row saying base N was archived vouches for bytes. + // On a standby in recovery, Postgres forbids assigning TransactionIds; skip the catalog + // write there (the primary owns the archive table). + if !unsafe { pgrx::pg_sys::RecoveryInProgress() } { + crate::archive::forget_from(topic, partition, offset).map_err(StoreError::Io)?; + } Ok(removed) } @@ -2799,6 +2941,13 @@ impl LogStore for SegmentStore { drop(view); Self::with_slot(topic, partition, |st, hints| { + // Re-check recovery state under the shard lock so a late in-flight follower reply + // cannot splice old-epoch batches into a newly promoted primary's log. + if !unsafe { pgrx::pg_sys::RecoveryInProgress() } { + return Err(StoreError::Io( + "cannot apply replicated batch: node is no longer in recovery".to_string(), + )); + } if st.next_offset != expected_base { return Err(StoreError::Io(format!( "replication position moved: caller expected log end {expected_base}, \ @@ -2821,6 +2970,54 @@ impl LogStore for SegmentStore { }) } + fn last_batch_epoch(&self, topic: TopicId, partition: i32) -> StoreResult> { + let bases = Self::segment_bases(topic, partition)?; + if bases.is_empty() { + return Ok(None); + } + Self::with_slot(topic, partition, |st, _| { + for base in bases.iter().rev() { + let path = data_path(&segment_path(topic, partition, *base, "log")); + let Ok(vfd) = Vfd::open(&path, false) else { + continue; + }; + let data_end = if *base == st.active_base { + st.active_bytes + } else { + vfd.size()? + }; + if data_end == 0 { + continue; + } + let mut pos = 0u64; + let mut last_epoch = None; + let mut header = [0u8; records::RECORD_BATCH_OVERHEAD]; + while pos + header.len() as u64 <= data_end { + if vfd.read_at(&mut header, pos)? != header.len() { + break; + } + let Some(BatchSpan { total, .. }) = batch_span(&header, pos, data_end) else { + break; + }; + let ep = i32::from_be_bytes( + header[records::PARTITION_LEADER_EPOCH_OFFSET + ..records::PARTITION_LEADER_EPOCH_OFFSET + 4] + .try_into() + .expect("4 bytes"), + ); + if ep >= 0 { + last_epoch = Some(ep); + } + pos += total; + } + if last_epoch.is_some() { + return Ok(last_epoch); + } + } + Ok(None) + }) + } + fn last_stable_offset(&self, topic: TopicId, partition: i32) -> StoreResult { self.last_stable_offset_impl(topic, partition) } diff --git a/extension/src/storage/table.rs b/extension/src/storage/table.rs index 7947764..bcfa445 100644 --- a/extension/src/storage/table.rs +++ b/extension/src/storage/table.rs @@ -497,6 +497,9 @@ impl LogStore for TableStore { if matches!(isolation, IsolationLevel::ReadCommitted) { (aborted, aborted_cut_at) = pmeta::aborted_txns(topic, partition, offset, next_offset.max(offset + 1))?; + if let Some(cut) = aborted_cut_at { + next_offset = super::truncate_batches_at(&mut bytes, cut, offset); + } } } @@ -517,17 +520,36 @@ impl LogStore for TableStore { partition: i32, timestamp: i64, ) -> StoreResult> { - let blob = crate::fresh::one::>( - "SELECT (SELECT batch FROM kafgres_log - WHERE topic_id = $1::oid AND partition = $2 AND max_timestamp >= $3 + let log_start = self.log_start_offset(topic, partition)?; + crate::fresh::rows( + "SELECT batch FROM kafgres_log + WHERE topic_id = $1::oid AND partition = $2 + AND last_offset >= $4 AND max_timestamp >= $3 ORDER BY base_offset - LIMIT 1)", - &[(topic as i32).into(), partition.into(), timestamp.into()], + LIMIT 100", + &[ + (topic as i32).into(), + partition.into(), + timestamp.into(), + log_start.into(), + ], + |rows| { + for row in rows { + let Some(blob) = row.get::>(1)? else { + continue; + }; + if let Some(found) = super::first_at_or_after_from( + kafgres_codec::bytes::Bytes::from(blob), + timestamp, + log_start, + ) { + return Ok(Some(found)); + } + } + Ok(None) + }, ) - .map_err(spi_err)?; - Ok(blob.and_then(|b| { - super::first_at_or_after(kafgres_codec::bytes::Bytes::from(b), timestamp) - })) + .map_err(spi_err) } fn max_timestamp_offset( @@ -979,10 +1001,22 @@ impl LogStore for TableStore { let matched = match matched { Some(e) => e, None => { - return Ok(EpochEnd { - leader_epoch: -1, - end_offset: self.log_start_offset(topic, partition)?, - }) + let next_start: Option = Spi::get_one_with_args( + "SELECT (SELECT min(start_offset) FROM kafgres_leader_epochs + WHERE topic_id = $1::oid AND partition = $2 AND leader_epoch > $3)", + &[(topic as i32).into(), partition.into(), epoch.into()], + ) + .map_err(spi_err)?; + return match next_start { + Some(s) => Ok(EpochEnd { + leader_epoch: epoch, + end_offset: s, + }), + None => Ok(EpochEnd { + leader_epoch: -1, + end_offset: self.log_start_offset(topic, partition)?, + }), + }; } }; diff --git a/tests/integration/test_safety_and_security.py b/tests/integration/test_safety_and_security.py new file mode 100644 index 0000000..08e0ee2 --- /dev/null +++ b/tests/integration/test_safety_and_security.py @@ -0,0 +1,381 @@ +"""Safety and security invariants across CDC, ACLs, transactions, groups, and storage.""" + +import socket +import struct +import subprocess +import time + +from conftest import ( + ADD_OFFSETS_TO_TXN, + ADD_PARTITIONS_TO_TXN, + BROKER_HOST, + BROKER_PORT, + DELETE_GROUPS, + DELETE_RECORDS, + DELETE_TOPICS, + END_TXN, + FIND_COORDINATOR, + INIT_PRODUCER_ID, + LIST_OFFSETS, + OFFSET_FOR_LEADER_EPOCH, + TXN_OFFSET_COMMIT, + sql, +) + +ERR_NONE = 0 +ERR_TRANSACTIONAL_ID_AUTH_FAILED = 53 +ERR_GROUP_AUTH_FAILED = 30 +ERR_NON_EMPTY_GROUP = 68 + +ARCHIVE_LOCK_KEY = 0x7047_4B41_0000_0006 + + +def psql_as(role, statement): + return subprocess.run( + [ + "docker", "compose", "exec", "-T", "postgres", + "psql", "-U", role, "-d", "postgres", "-v", "ON_ERROR_STOP=1", "-tAc", statement, + ], + capture_output=True, text=True, + ) + + +def _read_exact(sock, n): + buf = bytearray() + while len(buf) < n: + chunk = sock.recv(n - len(buf)) + if not chunk: + raise EOFError("broker closed connection") + buf.extend(chunk) + return bytes(buf) + + +def send_frame(sock, api_key, api_version, corr_id, body): + client_id = b"pytest" + header = struct.pack(">hhih", api_key, api_version, corr_id, len(client_id)) + client_id + frame = header + body + sock.sendall(struct.pack(">i", len(frame)) + frame) + (size,) = struct.unpack(">i", _read_exact(sock, 4)) + resp = _read_exact(sock, size) + (resp_corr,) = struct.unpack_from(">i", resp, 0) + assert resp_corr == corr_id + return resp[4:] + + +def _s(text): + b = text.encode("utf-8") + return struct.pack(">h", len(b)) + b + + +def _ns(text): + if text is None: + return struct.pack(">h", -1) + return _s(text) + + +def test_cdc_mapping_runs_under_owner_privileges(): + role = "cdc_unpriv_owner" + topic = "cdc-owner-priv-topic" + sql("DELETE FROM kafgres_cdc_mappings WHERE mapping_name LIKE 'owner_priv_%'") + sql("DELETE FROM kafgres_cdc_errors WHERE mapping_name LIKE 'owner_priv_%'") + sql("DROP TABLE IF EXISTS public.owner_priv_src, public.owner_priv_secret CASCADE") + sql(f"DROP ROLE IF EXISTS {role}") + sql(f"SELECT kafgres_drop_topic('{topic}')") + sql(f"SELECT kafgres_create_topic('{topic}', 1)") + sql("CREATE TABLE public.owner_priv_src (id int primary key, val text)") + sql("CREATE TABLE public.owner_priv_secret (s text)") + sql("INSERT INTO public.owner_priv_secret VALUES ('top-secret-value')") + sql(f"CREATE ROLE {role} LOGIN") + sql(f"GRANT EXECUTE ON FUNCTION kafgres_add_mapping(text, text, text, text, text, text) TO {role}") + sql(f"GRANT SELECT ON kafgres_topics, public.owner_priv_src TO {role}") + try: + # Adding a mapping that references an inaccessible table fails at definition time. + r = psql_as( + role, + f"SELECT kafgres_add_mapping('owner_priv_bad', 'public.owner_priv_src', '{topic}', " + f"$$(SELECT string_agg(s, ',') FROM public.owner_priv_secret)$$, $$new.id::text$$, NULL)", + ) + assert r.returncode != 0 + assert "permission denied" in r.stderr.lower(), r.stderr + + # Direct DML without table grants is refused. + r = psql_as( + role, + f"INSERT INTO kafgres_cdc_mappings (mapping_name, source_table, topic, key_expr, value_expr) " + f"VALUES ('owner_priv_dml', 'public.owner_priv_src', '{topic}', 'new.id::text', " + f"$$(SELECT string_agg(s, ',') FROM public.owner_priv_secret)$$)", + ) + assert r.returncode != 0 + assert "permission denied" in r.stderr.lower(), r.stderr + + # Even with direct table DML granted, owner spoofing is refused by the trigger and + # expressions render under the mapping owner's privileges rather than superuser. + sql(f"GRANT SELECT, INSERT, UPDATE ON kafgres_cdc_mappings TO {role}") + r = psql_as( + role, + f"INSERT INTO kafgres_cdc_mappings (mapping_name, source_table, topic, key_expr, value_expr, owner) " + f"VALUES ('owner_priv_spoof', 'public.owner_priv_src', '{topic}', 'new.id::text', 'new.val', 'postgres')", + ) + assert r.returncode != 0 + assert "permission denied" in r.stderr.lower(), r.stderr + + r = psql_as( + role, + f"INSERT INTO kafgres_cdc_mappings (mapping_name, source_table, topic, key_expr, value_expr) " + f"VALUES ('owner_priv_dml', 'public.owner_priv_src', '{topic}', 'new.id::text', " + f"$$(SELECT string_agg(s, ',') FROM public.owner_priv_secret)$$)", + ) + assert r.returncode == 0, r.stderr + + sql("SELECT kafgres_cdc_create_slot()") + sql("INSERT INTO public.owner_priv_src VALUES (1, 'hello')") + sql("SELECT kafgres_cdc_drain(100)") + + span = int(sql(f"SELECT coalesce(sum(offset_span), 0) FROM kafgres_partition_offsets('{topic}')")) + assert span == 0, f"secret data leaked into topic ({span} records)" + err_msg = sql("SELECT error FROM kafgres_cdc_errors WHERE mapping_name = 'owner_priv_dml' LIMIT 1") + assert "permission denied" in err_msg.lower(), f"expected permission denied in dead letters, got: {err_msg!r}" + + # Revoking SELECT on the source table stops rendering via the on_error path. + sql("DELETE FROM kafgres_cdc_mappings WHERE mapping_name = 'owner_priv_dml'") + sql("DELETE FROM kafgres_cdc_errors WHERE mapping_name = 'owner_priv_dml'") + r = psql_as( + role, + f"SELECT kafgres_add_mapping('owner_priv_ok', 'public.owner_priv_src', '{topic}', " + f"$$new.val$$, $$new.id::text$$, NULL)", + ) + assert r.returncode == 0, r.stderr + sql("INSERT INTO public.owner_priv_src VALUES (2, 'allowed')") + sql("SELECT kafgres_cdc_drain(100)") + span = int(sql(f"SELECT coalesce(sum(offset_span), 0) FROM kafgres_partition_offsets('{topic}')")) + assert span == 1, f"expected 1 allowed record, got {span}" + + sql(f"REVOKE SELECT ON public.owner_priv_src FROM {role}") + sql("INSERT INTO public.owner_priv_src VALUES (3, 'after-revoke')") + sql("SELECT kafgres_cdc_drain(100)") + span = int(sql(f"SELECT coalesce(sum(offset_span), 0) FROM kafgres_partition_offsets('{topic}')")) + assert span == 1, f"record rendered after SELECT was revoked ({span})" + err_msg = sql("SELECT error FROM kafgres_cdc_errors WHERE mapping_name = 'owner_priv_ok' LIMIT 1") + assert "permission denied" in err_msg.lower(), f"expected permission denied after revoke, got: {err_msg!r}" + finally: + sql("DELETE FROM kafgres_cdc_mappings WHERE mapping_name LIKE 'owner_priv_%'") + sql("DELETE FROM kafgres_cdc_errors WHERE mapping_name LIKE 'owner_priv_%'") + sql(f"REVOKE ALL ON kafgres_cdc_mappings, kafgres_topics, public.owner_priv_src FROM {role}") + sql(f"REVOKE ALL ON FUNCTION kafgres_add_mapping(text, text, text, text, text, text) FROM {role}") + sql("DROP TABLE IF EXISTS public.owner_priv_src, public.owner_priv_secret CASCADE") + sql(f"DROP ROLE IF EXISTS {role}") + sql(f"SELECT kafgres_drop_topic('{topic}')") + + +def test_transactional_id_acls_are_enforced(): + topic = "txn-acl-enforce-topic" + sql(f"SELECT kafgres_drop_topic('{topic}')") + sql(f"SELECT kafgres_create_topic('{topic}', 1)") + sql("DELETE FROM kafgres_acls") + sql("ALTER SYSTEM SET kafgres.sasl_required = off") + sql("ALTER SYSTEM SET kafgres.acls_enabled = on") + sql("SELECT pg_reload_conf()") + time.sleep(2.0) + try: + with socket.create_connection((BROKER_HOST, BROKER_PORT), timeout=15) as sock: + resp = send_frame(sock, FIND_COORDINATOR, 1, 1, _s("victim-tx") + struct.pack(">b", 1)) + (_throttle, code) = struct.unpack_from(">ih", resp, 0) + assert code == ERR_TRANSACTIONAL_ID_AUTH_FAILED, f"FindCoordinator(tx) code={code}" + + resp = send_frame(sock, INIT_PRODUCER_ID, 0, 2, _ns("victim-tx") + struct.pack(">i", 60000)) + (_throttle, code) = struct.unpack_from(">ih", resp, 0) + assert code == ERR_TRANSACTIONAL_ID_AUTH_FAILED, f"InitProducerId(tx) code={code}" + + body = _s("victim-tx") + struct.pack(">qhi", 1, 0, 1) + _s(topic) + struct.pack(">ii", 1, 0) + resp = send_frame(sock, ADD_PARTITIONS_TO_TXN, 0, 3, body) + off = 4 + 4 + 2 + len(topic) + 4 + 4 + (code,) = struct.unpack_from(">h", resp, off) + assert code == ERR_TRANSACTIONAL_ID_AUTH_FAILED, f"AddPartitionsToTxn code={code}" + + body = _s("victim-tx") + struct.pack(">qh", 1, 0) + _s("grp1") + resp = send_frame(sock, ADD_OFFSETS_TO_TXN, 0, 4, body) + (_throttle, code) = struct.unpack_from(">ih", resp, 0) + assert code == ERR_TRANSACTIONAL_ID_AUTH_FAILED, f"AddOffsetsToTxn code={code}" + + body = ( + _s("victim-tx") + _s("grp1") + struct.pack(">qhi", 1, 0, 1) + + _s(topic) + struct.pack(">iiq", 1, 0, 1) + _ns(None) + ) + resp = send_frame(sock, TXN_OFFSET_COMMIT, 0, 5, body) + off = 4 + 4 + 2 + len(topic) + 4 + 4 + (code,) = struct.unpack_from(">h", resp, off) + assert code == ERR_TRANSACTIONAL_ID_AUTH_FAILED, f"TxnOffsetCommit code={code}" + + body = _s("victim-tx") + struct.pack(">qhb", 1, 0, 1) + resp = send_frame(sock, END_TXN, 0, 6, body) + (_throttle, code) = struct.unpack_from(">ih", resp, 0) + assert code == ERR_TRANSACTIONAL_ID_AUTH_FAILED, f"EndTxn code={code}" + + sql("SELECT kafgres_add_acl('User:ANONYMOUS', 'WRITE', 'TRANSACTIONAL_ID', 'allowed-tx')") + time.sleep(2.0) + with socket.create_connection((BROKER_HOST, BROKER_PORT), timeout=15) as sock: + resp = send_frame(sock, FIND_COORDINATOR, 1, 10, _s("allowed-tx") + struct.pack(">b", 1)) + (_throttle, code) = struct.unpack_from(">ih", resp, 0) + assert code == ERR_NONE, f"FindCoordinator(allowed-tx) code={code}" + + resp = send_frame(sock, INIT_PRODUCER_ID, 0, 11, _ns("allowed-tx") + struct.pack(">i", 60000)) + (_throttle, code, pid, epoch) = struct.unpack_from(">ihqh", resp, 0) + assert code == ERR_NONE and pid >= 0 and epoch >= 0, (code, pid, epoch) + + body = _s("allowed-tx") + struct.pack(">qh", pid, epoch) + _s("grp1") + resp = send_frame(sock, ADD_OFFSETS_TO_TXN, 0, 12, body) + (_throttle, code) = struct.unpack_from(">ih", resp, 0) + assert code == ERR_GROUP_AUTH_FAILED, f"AddOffsetsToTxn without GROUP READ code={code}" + finally: + sql("DELETE FROM kafgres_acls") + sql("ALTER SYSTEM RESET kafgres.acls_enabled") + sql("ALTER SYSTEM RESET kafgres.sasl_required") + sql("SELECT pg_reload_conf()") + sql(f"SELECT kafgres_drop_topic('{topic}')") + time.sleep(2.0) + + +def test_failed_delete_topics_preserves_topic_and_data(): + topic = "delete-lock-preserve-topic" + sql(f"SELECT kafgres_drop_topic('{topic}')") + sql(f"SELECT kafgres_create_topic('{topic}', 1)") + sql(f"SELECT kafgres_produce('{topic}', 'k1', 'v1')") + sql(f"SELECT kafgres_produce('{topic}', 'k2', 'v2')") + + locker = subprocess.Popen( + [ + "docker", "compose", "exec", "-T", "postgres", + "psql", "-U", "postgres", "-c", + f"SELECT pg_advisory_lock({ARCHIVE_LOCK_KEY}); SELECT pg_sleep(10);", + ], + stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, + ) + try: + time.sleep(1.0) + with socket.create_connection((BROKER_HOST, BROKER_PORT), timeout=15) as sock: + body = struct.pack(">i", 1) + _s(topic) + struct.pack(">i", 5000) + resp = send_frame(sock, DELETE_TOPICS, 1, 1, body) + off = 4 + 4 + 2 + len(topic) + (code,) = struct.unpack_from(">h", resp, off) + assert code != ERR_NONE, "DeleteTopics unexpectedly succeeded while archive lock was held" + + rows = sql(f"SELECT count(*) FROM kafgres_read('{topic}', 0)") + assert int(rows) == 2, f"expected 2 surviving records, got {rows}" + finally: + locker.terminate() + locker.wait(timeout=5) + sql(f"SELECT kafgres_drop_topic('{topic}')") + + +def test_collapsed_leader_epoch_returns_defined_end_offset(): + topic = "collapsed-epoch-topic" + sql(f"SELECT kafgres_drop_topic('{topic}')") + sql(f"SELECT kafgres_create_topic('{topic}', 1)") + try: + tid = int(sql(f"SELECT topic_id::int FROM kafgres_topics WHERE name = '{topic}'")) + sql( + f"DELETE FROM kafgres_leader_epochs WHERE topic_id = {tid}::oid AND partition = 0; " + f"INSERT INTO kafgres_leader_epochs (topic_id, partition, leader_epoch, start_offset) " + f"VALUES ({tid}::oid, 0, 2, 0); " + f"UPDATE kafgres_partitions SET leader_epoch = 2, epoch_start_offset = 0 " + f"WHERE topic_id = {tid}::oid AND partition = 0;" + ) + with socket.create_connection((BROKER_HOST, BROKER_PORT), timeout=15) as sock: + body = struct.pack(">i", 1) + _s(topic) + struct.pack(">iiii", 1, 0, -1, 1) + resp = send_frame(sock, OFFSET_FOR_LEADER_EPOCH, 2, 1, body) + off = 4 + 4 + 2 + len(topic) + 4 + (err, part, ep, end_off) = struct.unpack_from(">hiiq", resp, off) + assert err == ERR_NONE and part == 0, (err, part) + assert ep == 1 and end_off == 0, f"expected (epoch=1, end_offset=0), got ({ep}, {end_off})" + finally: + sql(f"SELECT kafgres_drop_topic('{topic}')") + + +def test_delete_groups_handles_share_and_consumer_protocol_groups(): + share_g = "empty-share-group-del" + kip848_g = "live-consumer-group-del" + topic = "share-del-topic" + sql(f"SELECT kafgres_drop_topic('{topic}')") + sql(f"SELECT kafgres_create_topic('{topic}', 1)") + sql(f"DELETE FROM kafgres_share_groups WHERE group_id = '{share_g}'") + sql(f"DELETE FROM kafgres_consumer_groups WHERE group_id = '{kip848_g}'") + try: + tid = int(sql(f"SELECT topic_id::int FROM kafgres_topics WHERE name = '{topic}'")) + sql(f"INSERT INTO kafgres_share_groups (group_id) VALUES ('{share_g}')") + sql( + f"INSERT INTO kafgres_share_offsets (group_id, topic_id, partition, start_offset) " + f"VALUES ('{share_g}', {tid}::oid, 0, 5)" + ) + sql(f"INSERT INTO kafgres_consumer_groups (group_id, state) VALUES ('{kip848_g}', 'Stable')") + sql( + f"INSERT INTO kafgres_consumer_group_members (group_id, member_id, member_epoch) " + f"VALUES ('{kip848_g}', 'm1', 1)" + ) + + with socket.create_connection((BROKER_HOST, BROKER_PORT), timeout=15) as sock: + body = struct.pack(">i", 2) + _s(share_g) + _s(kip848_g) + resp = send_frame(sock, DELETE_GROUPS, 1, 1, body) + pos = 4 + (count,) = struct.unpack_from(">i", resp, pos) + pos += 4 + results = {} + for _ in range(count): + (slen,) = struct.unpack_from(">h", resp, pos) + pos += 2 + gid = resp[pos:pos + slen].decode() + pos += slen + (code,) = struct.unpack_from(">h", resp, pos) + pos += 2 + results[gid] = code + + assert results[share_g] == ERR_NONE, f"empty share group delete failed: {results}" + assert results[kip848_g] == ERR_NON_EMPTY_GROUP, f"live consumer-protocol group was deleted: {results}" + + assert int(sql(f"SELECT count(*) FROM kafgres_share_groups WHERE group_id = '{share_g}'")) == 0 + assert int(sql(f"SELECT count(*) FROM kafgres_share_offsets WHERE group_id = '{share_g}'")) == 0 + finally: + sql(f"DELETE FROM kafgres_consumer_groups WHERE group_id = '{kip848_g}'") + sql(f"DELETE FROM kafgres_share_groups WHERE group_id = '{share_g}'") + sql(f"SELECT kafgres_drop_topic('{topic}')") + + +def test_offset_for_timestamp_clamped_to_log_start(): + topic = "ts-clamp-topic" + sql(f"SELECT kafgres_drop_topic('{topic}')") + sql(f"SELECT kafgres_create_topic('{topic}', 1)") + try: + for i in range(10): + sql(f"SELECT kafgres_produce('{topic}', 'k{i}', 'v{i}')") + with socket.create_connection((BROKER_HOST, BROKER_PORT), timeout=15) as sock: + body = struct.pack(">i", 1) + _s(topic) + struct.pack(">iiqi", 1, 0, 5, 5000) + send_frame(sock, DELETE_RECORDS, 0, 1, body) + + body = struct.pack(">ibi", -1, 0, 1) + _s(topic) + struct.pack(">iiq", 1, 0, 1) + resp = send_frame(sock, LIST_OFFSETS, 2, 2, body) + off = 4 + 4 + 2 + len(topic) + 4 + (part, err, _ts, offset) = struct.unpack_from(">ihqq", resp, off) + assert err == ERR_NONE and part == 0, (part, err) + assert offset >= 5, f"ListOffsets returned offset {offset} below log_start_offset 5" + finally: + sql(f"SELECT kafgres_drop_topic('{topic}')") + + +def test_producer_epoch_ceiling_rotates_producer_id(): + txn_id = "epoch-ceiling-txn" + sql(f"DELETE FROM kafgres_txns WHERE transactional_id = '{txn_id}'") + sql(f"DELETE FROM kafgres_producers WHERE transactional_id = '{txn_id}'") + try: + with socket.create_connection((BROKER_HOST, BROKER_PORT), timeout=15) as sock: + resp = send_frame(sock, INIT_PRODUCER_ID, 0, 1, _ns(txn_id) + struct.pack(">i", 60000)) + (_throttle, code, pid1, ep1) = struct.unpack_from(">ihqh", resp, 0) + assert code == ERR_NONE and ep1 == 0, (code, pid1, ep1) + + sql(f"UPDATE kafgres_producers SET producer_epoch = 32767 WHERE producer_id = {pid1}") + + resp = send_frame(sock, INIT_PRODUCER_ID, 0, 2, _ns(txn_id) + struct.pack(">i", 60000)) + (_throttle, code, pid2, ep2) = struct.unpack_from(">ihqh", resp, 0) + assert code == ERR_NONE, f"InitProducerId failed at epoch 32767: code={code}" + assert pid2 != pid1 and ep2 == 0, f"expected fresh producer_id at epoch 0, got ({pid2}, {ep2})" + finally: + sql(f"DELETE FROM kafgres_txns WHERE transactional_id = '{txn_id}'") + sql(f"DELETE FROM kafgres_producers WHERE transactional_id = '{txn_id}'") From a49a507e4607b6a5aa25d816041facd0398d9905 Mon Sep 17 00:00:00 2001 From: Raynor Elgie Date: Wed, 25 Nov 2026 02:06:58 +0000 Subject: [PATCH 2/2] Fix CI failures and review findings in the safety hardening Restores decompression in the timestamp lookup and keeps the first batch past the abort-list cap (CI). Moves the new test file where CI collects it. Narrows the open-transaction re-stamp to batches that lost their window row, guards the reconstructed abort ranges, and reconciles after the epoch raise commits (I5). Drops the inline marker fsync from EndTxn and expiry (I7). AddPartitionsToTxn fails whole on a denied topic and TxnOffsetCommit checks topic READ (I6). --- extension/src/handlers/txn.rs | 176 +++++++++--------- extension/src/producer.rs | 31 +-- extension/src/replication.rs | 13 +- extension/src/server/mod.rs | 62 ++++-- extension/src/storage/mod.rs | 81 +++----- extension/src/storage/segment.rs | 14 +- extension/src/storage/table.rs | 6 +- .../produce_fetch/test_sql_read.py | 16 ++ .../test_safety_and_security.py | 48 ++++- 9 files changed, 264 insertions(+), 183 deletions(-) rename tests/integration/{ => security}/test_safety_and_security.py (89%) diff --git a/extension/src/handlers/txn.rs b/extension/src/handlers/txn.rs index 6295a63..ef9d14c 100644 --- a/extension/src/handlers/txn.rs +++ b/extension/src/handlers/txn.rs @@ -237,100 +237,84 @@ pub fn handle_add_partitions( ) }; - if let Err(auth_code) = authz.check( - crate::acl::Operation::Write, - crate::acl::ResourceType::TransactionalId, - &txn_id, - ) { - let results: Vec = topics + let respond = |code_of: &dyn Fn(usize, i32) -> ErrorCode| AddPartitionsToTxnResponse { + throttle_time_ms: 0, + error_code: 0, + results_by_topic_v3_and_below: topics .iter() - .map(|t| AddPartitionsToTxnTopicResult { + .enumerate() + .map(|(i, t)| AddPartitionsToTxnTopicResult { name: t.name.clone(), results_by_partition: t .partitions .iter() .map(|p| AddPartitionsToTxnPartitionResult { partition_index: *p, - partition_error_code: auth_code.code(), + partition_error_code: code_of(i, *p).code(), ..Default::default() }) .collect(), ..Default::default() }) - .collect(); - return Ok(AddPartitionsToTxnResponse { - throttle_time_ms: 0, - error_code: 0, - results_by_topic_v3_and_below: results, - results_by_transaction: Vec::new(), - ..Default::default() - }); + .collect(), + results_by_transaction: Vec::new(), + ..Default::default() + }; + + // Authorized before the fence, as Kafka does. A denied topic fails the whole request: nothing + // is added, and the other partitions answer UNKNOWN_TOPIC_OR_PARTITION or OPERATION_NOT_ATTEMPTED. + if let Err(code) = authz.check( + crate::acl::Operation::Write, + crate::acl::ResourceType::TransactionalId, + &txn_id, + ) { + return Ok(respond(&|_, _| code)); + } + let mut denied: Vec> = Vec::with_capacity(topics.len()); + // Per topic, its id and partition count; a count of 0 for one that does not exist. + let mut found: Vec<(Option, i32)> = Vec::with_capacity(topics.len()); + for topic in &topics { + let refused = authz + .check(crate::acl::Operation::Write, crate::acl::ResourceType::Topic, &topic.name) + .err(); + let id = match refused { + Some(_) => None, + None => crate::meta::topic_id_by_name(&topic.name) + .map_err(|e| HandlerError::Internal(e.to_string()))?, + }; + let count = match id { + Some(id) => crate::meta::partition_count(id) + .map_err(|e| HandlerError::Internal(e.to_string()))?, + None => 0, + }; + denied.push(refused); + found.push((id, count)); + } + let unknown = |i: usize, p: i32| p < 0 || p >= found[i].1; + if denied.iter().any(Option::is_some) { + return Ok(respond(&|i, p| match denied[i] { + Some(code) => code, + None if unknown(i, p) => ErrorCode::UnknownTopicOrPartition, + None => ErrorCode::OperationNotAttempted, + })); } let admitted = verdict(&txn_id, producer_id, epoch)?; let code = admitted.err().map_or(ErrorCode::None, |v| v.code(version)); - let mut topic_codes: Vec = Vec::with_capacity(topics.len()); if let Ok(admitted) = admitted { - let mut begun = false; - for topic in &topics { - if let Err(tc) = authz.check( - crate::acl::Operation::Write, - crate::acl::ResourceType::Topic, - &topic.name, - ) { - topic_codes.push(tc); - continue; - } - topic_codes.push(ErrorCode::None); - if !begun { - begin_or_continue(admitted, &txn_id) - .map_err(|e| HandlerError::Internal(e.to_string()))?; - begun = true; - } - let topic_id = crate::meta::topic_id_by_name(&topic.name) - .map_err(|e| HandlerError::Internal(e.to_string()))?; - let Some(topic_id) = topic_id else { continue }; - // Range-check: a row naming a nonexistent partition is invisible to - let count = crate::meta::partition_count(topic_id) - .map_err(|e| HandlerError::Internal(e.to_string()))?; - for partition in &topic.partitions { - if *partition < 0 || *partition >= count { - continue; - } - add_partition(producer_id, topic_id, *partition) + begin_or_continue(admitted, &txn_id).map_err(|e| HandlerError::Internal(e.to_string()))?; + for (i, (topic, (id, _))) in topics.iter().zip(&found).enumerate() { + let Some(topic_id) = id else { continue }; + // A row naming a nonexistent partition is one no marker append can reach. + for partition in topic.partitions.iter().filter(|&&p| !unknown(i, p)) { + add_partition(producer_id, *topic_id, *partition) .map_err(|e| HandlerError::Internal(e.to_string()))?; } } - } else { - topic_codes.resize(topics.len(), code); } - let results: Vec = topics - .iter() - .zip(topic_codes.iter()) - .map(|(t, &tc)| AddPartitionsToTxnTopicResult { - name: t.name.clone(), - results_by_partition: t - .partitions - .iter() - .map(|p| AddPartitionsToTxnPartitionResult { - partition_index: *p, - partition_error_code: tc.code(), - ..Default::default() - }) - .collect(), - ..Default::default() - }) - .collect(); - - Ok(AddPartitionsToTxnResponse { - throttle_time_ms: 0, - error_code: 0, - results_by_topic_v3_and_below: results.clone(), - results_by_transaction: Vec::new(), - ..Default::default() - }) + Ok(respond(&|_, _| code)) } /// Mark the transaction ongoing at the admitted epoch; a new one clears the previous one's rows. @@ -736,14 +720,6 @@ fn finish_transaction( committed, )?; } - // Every control marker must be durable before Postgres commits the abort index, - // transactional offsets, and transaction state; otherwise a power cut can lose the - // ABORT marker while keeping kafgres_txn_aborted, permanently hiding later commits. - for (topic_id, partition, _) in &partitions { - store - .sync_partition(*topic_id, *partition) - .map_err(|e| HandlerError::Internal(format!("syncing transaction marker: {e}")))?; - } // Staged offsets become visible exactly with the records, or not at all: after the if committed { @@ -1039,6 +1015,9 @@ pub fn handle_txn_offset_commit( .map_err(|e| HandlerError::Internal(e.to_string()))?, None => 0, }; + let denied = authz + .check(crate::acl::Operation::Read, crate::acl::ResourceType::Topic, &topic.name) + .err(); let mut partitions = Vec::with_capacity(topic.partitions.len()); for part in &topic.partitions { let index = part.partition_index; @@ -1046,6 +1025,7 @@ pub fn handle_txn_offset_commit( // An empty transactional id is refused before any topic lookup, unless the // group id is empty too: Kafka answers that INVALID_GROUP_ID. _ if code == ErrorCode::InvalidRequest && !req.group_id.is_empty() => code, + _ if denied.is_some() => denied.unwrap_or(ErrorCode::TopicAuthorizationFailed), (None, _) => ErrorCode::UnknownTopicOrPartition, _ if index < 0 || index >= count => ErrorCode::UnknownTopicOrPartition, _ if req.group_id.is_empty() => ErrorCode::InvalidGroupId, @@ -1053,7 +1033,7 @@ pub fn handle_txn_offset_commit( (Some(id), Some(g)) => g.code_for(id, index), _ => code, }; - any_partition |= topic_id.is_some() && (0..count).contains(&index); + any_partition |= denied.is_none() && topic_id.is_some() && (0..count).contains(&index); partitions.push(TxnOffsetCommitResponsePartition { partition_index: index, error_code: part_code.code(), @@ -1264,7 +1244,7 @@ pub fn reconcile_transactions( end: i64, ) -> Result<(), HandlerError> { use kafgres_codec::records::{ControlBatchType, LENGTH_OFFSET}; - use std::collections::HashMap; + use std::collections::{HashMap, HashSet}; // Reset first_offset for any ongoing transaction whose data did not survive. Spi::run_with_args( @@ -1368,6 +1348,8 @@ pub fn reconcile_transactions( .min(end); let mut at = scan_from; let mut first_seen: HashMap = HashMap::new(); + // Producers with a marker earlier in the scan. + let mut ended: HashSet = HashSet::new(); while at < end { let slice = store .read( @@ -1410,12 +1392,38 @@ pub fn reconcile_transactions( first_seen.entry(pid).or_insert(batch_base); continue; } + let marked_before = !ended.insert(pid); match batch.control_type() { Some(ControlBatchType::Commit) => { first_seen.remove(&pid); } Some(ControlBatchType::Abort) => { - let first = first_seen.remove(&pid).unwrap_or(scan_from); + let first = match first_seen.remove(&pid) { + Some(first) => first, + // Its own marker earlier in the scan: this transaction wrote nothing here. + None if marked_before => continue, + // Begun before the scan. `first_offset` is the conflict key, and an + // upsert there would take over another producer's entry. + None => { + let taken = Spi::get_one_with_args::( + "SELECT EXISTS (SELECT 1 FROM kafgres_txn_aborted + WHERE topic_id = $1::oid AND partition = $2 + AND first_offset = $3)", + &[(topic_id as i32).into(), partition.into(), scan_from.into()], + ) + .map_err(|e| HandlerError::Internal(e.to_string()))? + .unwrap_or(false); + if taken { + log!( + "kafgres: ABORT marker for producer {pid} at {batch_base} on \ + topic {topic_id} partition {partition} has no abort-index \ + row, and its start precedes offset {scan_from}" + ); + continue; + } + scan_from + } + }; let already = crate::storage::pmeta::aborted_at( topic_id, partition, @@ -1489,10 +1497,6 @@ fn finish_partition( first_offset, committed, )?; - store - .sync_partition(topic_id, partition) - .map_err(|e| HandlerError::Internal(format!("syncing transaction marker: {e}")))?; - Spi::run_with_args( "DELETE FROM kafgres_txn_partitions WHERE producer_id = $1 AND topic_id = $2::oid AND partition = $3", diff --git a/extension/src/producer.rs b/extension/src/producer.rs index ce045c8..c3cf7e9 100644 --- a/extension/src/producer.rs +++ b/extension/src/producer.rs @@ -578,6 +578,8 @@ pub fn rebuild_window( // Per producer: (epoch, last_seq) of its newest row, `None` with no window here. let mut newest: HashMap> = HashMap::new(); + // Per producer: the first rebuilt transactional batch after its last marker. + let mut open_txn: HashMap = HashMap::new(); let mut rebuilt = 0u64; while at < end { let slice = store @@ -601,22 +603,15 @@ pub fn rebuild_window( pos += total; let Ok(batch) = RecordBatch::new(bytes) else { continue }; let (pid, epoch, first) = (batch.producer_id(), batch.producer_epoch(), batch.base_sequence()); + // A marker ends the producer's transaction here; only data after its last marker + // can belong to the one still open. + if pid >= 0 && batch.is_control() { + open_txn.remove(&pid); + } // A batch straddling the start is read whole and kept: it may be the newest one. if pid < 0 || epoch < 0 || first < 0 || batch.is_control() { continue; } - // If a crash occurred between appending a transactional batch and stamping - // `kafgres_txn_partitions.first_offset`, restore `first_offset` now so the batch - // is held below the LSO and recorded if the transaction aborts. - if batch.is_transactional() { - crate::storage::pmeta::stamp_txn_partition( - pid, - topic_id, - partition, - batch.base_offset(), - ) - .map_err(|e| e.to_string())?; - } let last = increment_sequence(first, batch.last_offset_delta()); let state = match newest.get(&pid) { Some(s) => *s, @@ -648,6 +643,11 @@ pub fn rebuild_window( if !missing { continue; } + // A batch whose window row committed had its `first_offset` stamped with it; only + // one that lost its row can belong to an open transaction left unstamped. + if batch.is_transactional() { + open_txn.entry(pid).or_insert(batch.base_offset()); + } record(pid, epoch, topic_id, partition, first, last, batch.base_offset()) .map_err(|e| e.to_string())?; newest.insert(pid, Some((epoch, last))); @@ -658,6 +658,13 @@ pub fn rebuild_window( } at = slice.next_offset.max(at + 1); } + // A crash between a transactional append and the stamp of its `first_offset` leaves the + // open transaction unstamped: re-stamp it, or the LSO passes the batch and an abort + // would not cover it. A no-op where the stamp committed. + for (pid, base) in open_txn { + crate::storage::pmeta::stamp_txn_partition(pid, topic_id, partition, base) + .map_err(|e| e.to_string())?; + } Ok(rebuilt) } diff --git a/extension/src/replication.rs b/extension/src/replication.rs index d423cd8..0078fee 100644 --- a/extension/src/replication.rs +++ b/extension/src/replication.rs @@ -455,11 +455,7 @@ fn partitions_to_follow(store: &mut dyn crate::storage::LogStore) -> Want { .unwrap_or_default() .into_iter() .filter_map(|(id, name, part, epoch)| { - let end = store.high_watermark(id, part).ok()?; - // Report the epoch of our actual local tail, not the WAL-replicated leader_epoch, - // so a rejoined old primary detects and truncates its divergent tail. - let local_epoch = store.last_batch_epoch(id, part).ok().flatten().unwrap_or(epoch); - Some((id, name, part, end, local_epoch)) + store.high_watermark(id, part).ok().map(|end| (id, name, part, end, epoch)) }) .collect() } @@ -498,10 +494,15 @@ impl Follower { return Ok(0); } + // Reconciled with the epoch of the local tail, not the leader_epoch the WAL replicated: + // a rejoined old primary's tail was written under its own epoch. let unreconciled: Want = want .iter() .filter(|(id, _, part, _, _)| !self.reconciled.contains(&(*id, *part))) - .cloned() + .map(|(id, name, part, end, epoch)| { + let local = store.last_batch_epoch(*id, *part).ok().flatten().unwrap_or(*epoch); + (*id, name.clone(), *part, *end, local) + }) .collect(); if !unreconciled.is_empty() { self.socket()?; diff --git a/extension/src/server/mod.rs b/extension/src/server/mod.rs index 819a248..fa44b95 100644 --- a/extension/src/server/mod.rs +++ b/extension/src/server/mod.rs @@ -1393,6 +1393,11 @@ fn exclusive_holders() -> String { /// The timeline is the high half: a diverged primary restarting on its old timeline never /// reaches the epochs a promotion takes. fn raise_leader_epochs() -> bool { + // Once committed, a retry only reconciles: raising again would spend another epoch. + static RAISED: AtomicBool = AtomicBool::new(false); + if RAISED.load(Ordering::Relaxed) { + return reconcile_recovered_tails(); + } let result = BackgroundWorker::transaction(|| { crate::dbtx::guarded(|| { // Once per process: a retried raise must not spend another number. @@ -1446,11 +1451,42 @@ fn raise_leader_epochs() -> bool { crate::producer::forget_past(topic_id, partition, end) .map_err(|e| HandlerError::Internal(e.to_string()))?; crate::producer::note_startup_end(topic_id, partition, end); - crate::handlers::txn::reconcile_transactions( - &mut *store, topic_id, partition, end, - )?; - // Clamp share-group offsets to the recovered log end so a power cut or - // failover truncation does not skip records refilled into the lost range. + } + Ok((highest, raised, boot)) + }) + }); + + match result { + Ok((epoch, 0, boot)) => { + // Published once committed: a raise that rolls back never exposes its number. + BOOT_ID.get().store(boot, Ordering::Release); + log!("kafgres: leader epoch {epoch} already current for every partition"); + } + Ok((epoch, n, boot)) => { + BOOT_ID.get().store(boot, Ordering::Release); + log!("kafgres: took a new leader epoch (up to {epoch}) for {n} partition(s)"); + } + Err(e) => { + log!("kafgres: could not raise leader epochs, not serving yet: {e}"); + return false; + } + } + RAISED.store(true, Ordering::Relaxed); + reconcile_recovered_tails() +} + +/// Bring transaction and share-group state in line with the recovered log ends. After the +/// raise has committed, since it appends markers: a rolled-back raise would leave them stamped +/// with an epoch whose recorded start is past them. Appends from SQL and CDC wait on it. +fn reconcile_recovered_tails() -> bool { + let result = BackgroundWorker::transaction(|| { + crate::dbtx::guarded(|| { + let mut store = crate::storage::open(); + for (topic_id, partition) in crate::meta::all_partitions()? { + let end = crate::storage::LogStore::high_watermark(&*store, topic_id, partition) + .map_err(|e| HandlerError::Internal(e.to_string()))?; + crate::handlers::txn::reconcile_transactions(&mut *store, topic_id, partition, end)?; + // A share group's position past the recovered end would skip what refills it. pgrx::Spi::run_with_args( "UPDATE kafgres_share_offsets SET start_offset = $3 @@ -1463,26 +1499,16 @@ fn raise_leader_epochs() -> bool { &[(topic_id as i32).into(), partition.into(), end.into()], )?; } - Ok((highest, raised, boot)) + Ok(()) }) }); - match result { - Ok((epoch, 0, boot)) => { - // Published once committed: a raise that rolls back never exposes its number. - BOOT_ID.get().store(boot, Ordering::Release); - log!("kafgres: leader epoch {epoch} already current for every partition"); - EPOCHS_RAISED.get().store(true, Ordering::Release); - true - } - Ok((epoch, n, boot)) => { - BOOT_ID.get().store(boot, Ordering::Release); - log!("kafgres: took a new leader epoch (up to {epoch}) for {n} partition(s)"); + Ok(()) => { EPOCHS_RAISED.get().store(true, Ordering::Release); true } Err(e) => { - log!("kafgres: could not raise leader epochs, not serving yet: {e}"); + log!("kafgres: could not reconcile transactions with the recovered log, not serving yet: {e}"); false } } diff --git a/extension/src/storage/mod.rs b/extension/src/storage/mod.rs index ec502fb..2ced4b5 100644 --- a/extension/src/storage/mod.rs +++ b/extension/src/storage/mod.rs @@ -457,22 +457,28 @@ pub fn offset_of_max_timestamp(bytes: kafgres_codec::bytes::Bytes) -> Option<(i6 Some((base, want)) } -/// The first record at or after `timestamp` in the batch that reaches it, as Kafka's -/// `findOffsetByTimestamp` answers; undecodable means the base offset and the batch's maximum. -pub fn first_at_or_after(bytes: kafgres_codec::bytes::Bytes, timestamp: i64) -> Option<(i64, i64)> { +/// The first record at or after `timestamp`, and at or past `min_offset` (the log start), in +/// the batch that reaches it, as Kafka's `findOffsetByTimestamp` answers; undecodable means the +/// base offset and the batch's maximum. `None` when only records below `min_offset` reach it. +pub fn first_at_or_after( + bytes: kafgres_codec::bytes::Bytes, + timestamp: i64, + min_offset: i64, +) -> Option<(i64, i64)> { let batch = kafgres_codec::records::RecordBatch::new(bytes).ok()?; let base = batch.base_offset(); let base_ts = batch.base_timestamp(); - if let Ok(records) = batch.records_decompressed() { - for record in records { - let Ok(record) = record else { break }; - let ts = base_ts.saturating_add(record.timestamp_delta); - if ts >= timestamp { - return Some((base + record.offset_delta as i64, ts)); - } + let fallback = Some((base.max(min_offset), batch.max_timestamp())); + let Ok(records) = batch.records_decompressed() else { return fallback }; + for record in records { + let Ok(record) = record else { return fallback }; + let offset = base + record.offset_delta as i64; + let ts = base_ts.saturating_add(record.timestamp_delta); + if ts >= timestamp && offset >= min_offset { + return Some((offset, ts)); } } - Some((base, batch.max_timestamp())) + if base >= min_offset { fallback } else { None } } pub trait LogStore: Send { @@ -622,52 +628,25 @@ pub trait LogStore: Send { } } -/// Like [`first_at_or_after`], but ignores records below `min_offset` (e.g. `log_start_offset`). -pub(crate) fn first_at_or_after_from( - bytes: kafgres_codec::bytes::Bytes, - timestamp: i64, - min_offset: i64, -) -> Option<(i64, i64)> { - let batch = kafgres_codec::records::RecordBatch::new(bytes).ok()?; - let base_offset = batch.base_offset(); - let base_ts = batch.base_timestamp(); - for rec in batch.records().ok()? { - let rec = rec.ok()?; - let off = base_offset + rec.offset_delta as i64; - if off < min_offset { - continue; - } - let ts = base_ts + rec.timestamp_delta; - if ts >= timestamp { - return Some((off, ts)); - } - } - None -} - -/// Truncate `bytes` before the first batch whose `last_offset >= cut`, returning the new -/// `next_offset` (`last_offset + 1` of the last kept batch, or `fallback_next` if none kept). -/// Used when `pmeta::aborted_txns` hits `MAX_ABORTED_PER_FETCH` so Fetch never returns batches -/// whose aborted status was omitted by the cap. -pub(crate) fn truncate_batches_at(bytes: &mut Vec, cut: i64, fallback_next: i64) -> i64 { +/// Drop the batches after the first that reach `cut`, where `pmeta::aborted_txns` stopped +/// listing, so a read_committed Fetch never serves a batch whose abort it could not list. +/// The first batch is always kept so the reader makes progress; `RecordCursor` refuses it +/// itself. Returns the new `next_offset` if anything was dropped. +pub(crate) fn truncate_batches_at(bytes: &mut Vec, cut: i64) -> Option { use kafgres_codec::records::{BASE_OFFSET_OFFSET, LAST_OFFSET_DELTA_OFFSET, LENGTH_OFFSET, RECORD_BATCH_OVERHEAD}; let mut pos = 0usize; - let mut new_next = fallback_next; while pos + RECORD_BATCH_OVERHEAD <= bytes.len() { let len = i32::from_be_bytes( bytes[pos + LENGTH_OFFSET..pos + LENGTH_OFFSET + 4] .try_into() .expect("4 bytes"), ); - if len <= 0 { - break; + let total = LENGTH_OFFSET + 4 + len.max(0) as usize; + if len <= 0 || pos + total > bytes.len() { + return None; } - let total = LENGTH_OFFSET + 4 + len as usize; - if pos + total > bytes.len() { - break; - } - let batch_base = i64::from_be_bytes( + let base = i64::from_be_bytes( bytes[pos + BASE_OFFSET_OFFSET..pos + BASE_OFFSET_OFFSET + 8] .try_into() .expect("8 bytes"), @@ -677,15 +656,13 @@ pub(crate) fn truncate_batches_at(bytes: &mut Vec, cut: i64, fallback_next: .try_into() .expect("4 bytes"), ); - let batch_last = batch_base + last_delta as i64; - if batch_last >= cut { + if pos > 0 && base + last_delta as i64 >= cut { bytes.truncate(pos); - return new_next; + return Some(base); } - new_next = batch_last + 1; pos += total; } - new_next + None } #[cfg(test)] diff --git a/extension/src/storage/segment.rs b/extension/src/storage/segment.rs index be572ac..049b996 100644 --- a/extension/src/storage/segment.rs +++ b/extension/src/storage/segment.rs @@ -53,6 +53,16 @@ fn defer_partition_drop(topic: TopicId, partition: i32) { } }); }); + // A released subtransaction's drops become its parent's, so the parent's rollback cancels them. + pgrx::register_subxact_callback(pgrx::PgSubXactCallbackEvent::CommitSub, |sub, parent| { + PENDING_DROPS.with(|p| { + if let Some(list) = p.borrow_mut().as_mut() { + for entry in list.iter_mut().filter(|e| e.2 == sub) { + entry.2 = parent; + } + } + }); + }); } } @@ -2389,7 +2399,7 @@ impl LogStore for SegmentStore { aborted.extend(listed); aborted_cut_at = cut; if let Some(cut) = aborted_cut_at { - next = super::truncate_batches_at(&mut out, cut, offset); + next = super::truncate_batches_at(&mut out, cut).unwrap_or(next); } } } @@ -2478,7 +2488,7 @@ impl LogStore for SegmentStore { path.display() ))); } - if let Some(found) = super::first_at_or_after_from( + if let Some(found) = super::first_at_or_after( kafgres_codec::bytes::Bytes::from(body), timestamp, log_start, diff --git a/extension/src/storage/table.rs b/extension/src/storage/table.rs index bcfa445..d2dab43 100644 --- a/extension/src/storage/table.rs +++ b/extension/src/storage/table.rs @@ -498,7 +498,7 @@ impl LogStore for TableStore { (aborted, aborted_cut_at) = pmeta::aborted_txns(topic, partition, offset, next_offset.max(offset + 1))?; if let Some(cut) = aborted_cut_at { - next_offset = super::truncate_batches_at(&mut bytes, cut, offset); + next_offset = super::truncate_batches_at(&mut bytes, cut).unwrap_or(next_offset); } } } @@ -526,7 +526,7 @@ impl LogStore for TableStore { WHERE topic_id = $1::oid AND partition = $2 AND last_offset >= $4 AND max_timestamp >= $3 ORDER BY base_offset - LIMIT 100", + LIMIT 2", &[ (topic as i32).into(), partition.into(), @@ -538,7 +538,7 @@ impl LogStore for TableStore { let Some(blob) = row.get::>(1)? else { continue; }; - if let Some(found) = super::first_at_or_after_from( + if let Some(found) = super::first_at_or_after( kafgres_codec::bytes::Bytes::from(blob), timestamp, log_start, diff --git a/tests/integration/produce_fetch/test_sql_read.py b/tests/integration/produce_fetch/test_sql_read.py index bcb890f..2e6c21f 100644 --- a/tests/integration/produce_fetch/test_sql_read.py +++ b/tests/integration/produce_fetch/test_sql_read.py @@ -205,6 +205,22 @@ def test_a_full_abort_list_is_not_mistaken_for_one_cut_short(topic): WHERE topic_id = (SELECT topic_id FROM kafgres_topics WHERE name = '{topic}')""") +def test_a_consumer_is_not_stalled_by_a_cut_short_abort_list(topic): + """Fetch keeps the first batch past the abort-list cap, so a read_committed consumer makes + progress; the batches after the cut wait for the next Fetch.""" + produce(topic, ["first", "second"]) + sql(f"""INSERT INTO kafgres_txn_aborted + (topic_id, partition, producer_id, first_offset, last_offset) + SELECT topic_id, 0, 999999, -n, 1000000 + FROM kafgres_topics, generate_series(0, 1000) n + WHERE name = '{topic}'""") + try: + assert consumed(topic) == {0: "first", 1: "second"} + finally: + sql(f"""DELETE FROM kafgres_txn_aborted + WHERE topic_id = (SELECT topic_id FROM kafgres_topics WHERE name = '{topic}')""") + + @pytest.mark.skipif(sql("SHOW kafgres.storage_engine") != "segment", reason="kafgres_produce() is the segment engine's") def test_a_rolled_back_sql_produce_is_read_only_uncommitted(topic): diff --git a/tests/integration/test_safety_and_security.py b/tests/integration/security/test_safety_and_security.py similarity index 89% rename from tests/integration/test_safety_and_security.py rename to tests/integration/security/test_safety_and_security.py index 08e0ee2..5acca83 100644 --- a/tests/integration/test_safety_and_security.py +++ b/tests/integration/security/test_safety_and_security.py @@ -21,11 +21,15 @@ TXN_OFFSET_COMMIT, sql, ) +from support.docker import CLIENTS ERR_NONE = 0 ERR_TRANSACTIONAL_ID_AUTH_FAILED = 53 ERR_GROUP_AUTH_FAILED = 30 ERR_NON_EMPTY_GROUP = 68 +ERR_UNKNOWN_TOPIC_OR_PARTITION = 3 +ERR_TOPIC_AUTH_FAILED = 29 +ERR_OPERATION_NOT_ATTEMPTED = 55 ARCHIVE_LOCK_KEY = 0x7047_4B41_0000_0006 @@ -40,6 +44,16 @@ def psql_as(role, statement): ) +def produce(topic, values): + """Through the Kafka protocol, so the test runs on either engine.""" + out = subprocess.run( + ["docker", "run", "--rm", "-i", "--network", "host", CLIENTS, "kcat", + "-b", f"{BROKER_HOST}:{BROKER_PORT}", "-t", topic, "-P"], + input="".join(f"{v}\n" for v in values), capture_output=True, text=True, timeout=120, + ) + assert out.returncode == 0, out.stderr + + def _read_exact(sock, n): buf = bytearray() while len(buf) < n: @@ -212,6 +226,8 @@ def test_transactional_id_acls_are_enforced(): assert code == ERR_TRANSACTIONAL_ID_AUTH_FAILED, f"EndTxn code={code}" sql("SELECT kafgres_add_acl('User:ANONYMOUS', 'WRITE', 'TRANSACTIONAL_ID', 'allowed-tx')") + sql(f"SELECT kafgres_add_acl('User:ANONYMOUS', 'WRITE', 'TOPIC', '{topic}')") + sql("SELECT kafgres_add_acl('User:ANONYMOUS', 'WRITE', 'TOPIC', 'txn-acl-missing-topic')") time.sleep(2.0) with socket.create_connection((BROKER_HOST, BROKER_PORT), timeout=15) as sock: resp = send_frame(sock, FIND_COORDINATOR, 1, 10, _s("allowed-tx") + struct.pack(">b", 1)) @@ -226,6 +242,32 @@ def test_transactional_id_acls_are_enforced(): resp = send_frame(sock, ADD_OFFSETS_TO_TXN, 0, 12, body) (_throttle, code) = struct.unpack_from(">ih", resp, 0) assert code == ERR_GROUP_AUTH_FAILED, f"AddOffsetsToTxn without GROUP READ code={code}" + + # One denied topic fails the whole request, as Kafka does: the authorized topic is + # not added (OPERATION_NOT_ATTEMPTED), and an authorized missing one is unknown. + names = [topic, "txn-acl-denied-topic", "txn-acl-missing-topic"] + body = _s("allowed-tx") + struct.pack(">qhi", pid, epoch, len(names)) + for name in names: + body += _s(name) + struct.pack(">ii", 1, 0) + resp = send_frame(sock, ADD_PARTITIONS_TO_TXN, 0, 13, body) + pos = 4 + (count,) = struct.unpack_from(">i", resp, pos) + pos += 4 + codes = {} + for _ in range(count): + (n,) = struct.unpack_from(">h", resp, pos) + name = resp[pos + 2:pos + 2 + n].decode() + pos += 2 + n + 4 + (_part, code) = struct.unpack_from(">ih", resp, pos) + pos += 6 + codes[name] = code + assert codes == { + topic: ERR_OPERATION_NOT_ATTEMPTED, + "txn-acl-denied-topic": ERR_TOPIC_AUTH_FAILED, + "txn-acl-missing-topic": ERR_UNKNOWN_TOPIC_OR_PARTITION, + }, codes + added = sql(f"SELECT count(*) FROM kafgres_txn_partitions WHERE producer_id = {pid}") + assert added == "0", f"{added} partition(s) added despite the denial" finally: sql("DELETE FROM kafgres_acls") sql("ALTER SYSTEM RESET kafgres.acls_enabled") @@ -239,8 +281,7 @@ def test_failed_delete_topics_preserves_topic_and_data(): topic = "delete-lock-preserve-topic" sql(f"SELECT kafgres_drop_topic('{topic}')") sql(f"SELECT kafgres_create_topic('{topic}', 1)") - sql(f"SELECT kafgres_produce('{topic}', 'k1', 'v1')") - sql(f"SELECT kafgres_produce('{topic}', 'k2', 'v2')") + produce(topic, ["v1", "v2"]) locker = subprocess.Popen( [ @@ -344,8 +385,7 @@ def test_offset_for_timestamp_clamped_to_log_start(): sql(f"SELECT kafgres_drop_topic('{topic}')") sql(f"SELECT kafgres_create_topic('{topic}', 1)") try: - for i in range(10): - sql(f"SELECT kafgres_produce('{topic}', 'k{i}', 'v{i}')") + produce(topic, [f"v{i}" for i in range(10)]) with socket.create_connection((BROKER_HOST, BROKER_PORT), timeout=15) as sock: body = struct.pack(">i", 1) + _s(topic) + struct.pack(">iiqi", 1, 0, 5, 5000) send_frame(sock, DELETE_RECORDS, 0, 1, body)