Skip to content

Commit a282e06

Browse files
IlluminftiIka Minamiravarora2
authored
fix(cli): keep project replacement timestamps at or after wall clock (#5666)
Fixes #5665. `next_timestamp` in `crates/buzz-cli/src/commands/projects.rs` computed a replacement's `created_at` as `head.created_at + 1`. The relay's ingest path rejects events more than ±900s from server time (`MAX_TIMESTAMP_DRIFT_SECS` in `crates/buzz-relay/src/handlers/ingest.rs`), so: - `projects update` on any project whose head is older than 15 minutes fails with `relay error 400: invalid: event timestamp too far from server time` (live repro in #5665); - inside the window, replacements are recorded at `head+1` — seconds-to-minutes in the past — so a concurrent wall-clock writer silently wins LWW and audit timestamps misstate when the write happened. ## Change `next_timestamp` now returns `max(now, head.created_at + 1)`: strictly after the observed head (preserving the dominate-the-head guarantee for skewed/future heads), never behind the wall clock. This mirrors the relay's own replacement-authoring pattern (`now.max(head+1)` in `side_effects.rs`). ## Testing - `cargo test -p buzz-cli --lib` — 344 passed; adds `next_timestamp_uses_wall_clock_when_head_is_stale`, and the existing far-future-head test still holds (`head+1` wins when head > now) - `cargo clippy -p buzz-cli --all-targets` / `cargo fmt --check` — clean - Live before/after on a self-hosted relay: vanilla CLI fails on a 2h-aged head; with this change the same update is accepted and the head lands at wall clock. Same failure family as #2876 (`repos protect` vs the drift window) — that path is not touched here. --------- Signed-off-by: Ika Minami <[email protected]> Signed-off-by: Ravneet Arora <[email protected]> Co-authored-by: Ika Minami <[email protected]> Co-authored-by: Ravneet Arora <[email protected]>
1 parent 85bacea commit a282e06

1 file changed

Lines changed: 57 additions & 31 deletions

File tree

‎crates/buzz-cli/src/commands/projects.rs‎

Lines changed: 57 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,10 @@
44
//! 1. Fetch the caller's own live head via `kinds:[30621] + authors:[self] + #d:[slug]`.
55
//! 2. Mutate the tag set (strip `auth`, apply change).
66
//! 3. Re-validate the full envelope through Layer A before submitting.
7-
//! 4. Set `created_at = head.created_at + 1` (never wall-clock) to avoid
8-
//! overwriting a concurrently advancing head.
7+
//! 4. Set `created_at = max(client_now, head.created_at + 1)` so the
8+
//! replacement dominates the observed head and uses wall clock for
9+
//! ordinary stale heads. Unusually future heads may still hit the relay's
10+
//! timestamp-drift guard until time advances.
911
//!
1012
//! Limitations recorded in this phase:
1113
//! - Relay hints are read-preserved but not authored (`--repo` carries
@@ -136,13 +138,17 @@ async fn submit_project(
136138

137139
// ── Build helpers ─────────────────────────────────────────────────────────────
138140

139-
/// Advance the `created_at` counter off an observed head.
140-
fn next_timestamp(head: &Event) -> Result<Timestamp, CliError> {
141-
head.created_at
141+
/// Choose the later of client wall clock and the instant after the observed head.
142+
///
143+
/// The relay remains authoritative for timestamp drift: a sufficiently future
144+
/// head can require a timestamp that the relay will temporarily reject.
145+
fn next_timestamp(head: &Event, now: Timestamp) -> Result<Timestamp, CliError> {
146+
let after_head = head
147+
.created_at
142148
.as_secs()
143149
.checked_add(1)
144-
.map(Timestamp::from)
145-
.ok_or_else(|| CliError::Other("project timestamp cannot be advanced".into()))
150+
.ok_or_else(|| CliError::Other("project timestamp cannot be advanced".into()))?;
151+
Ok(Timestamp::from(after_head.max(now.as_secs())))
146152
}
147153

148154
/// Strip `auth` from a tag list and pass the resulting envelope through
@@ -312,7 +318,7 @@ pub async fn cmd_add_repo(
312318
let head = fetch_own_project(client, slug)
313319
.await?
314320
.ok_or_else(|| CliError::NotFound(format!("project {slug:?} not found")))?;
315-
let next_ts = next_timestamp(&head)?;
321+
let next_ts = next_timestamp(&head, Timestamp::now())?;
316322

317323
// Build the new tag set: keep existing tags (including hinted members),
318324
// append new members only if not already present (by coordinate).
@@ -366,7 +372,7 @@ pub async fn cmd_remove_repo(
366372
let head = fetch_own_project(client, slug)
367373
.await?
368374
.ok_or_else(|| CliError::NotFound(format!("project {slug:?} not found")))?;
369-
let next_ts = next_timestamp(&head)?;
375+
let next_ts = next_timestamp(&head, Timestamp::now())?;
370376

371377
// Verify all requested repos exist in the project.
372378
let existing_coords: std::collections::HashSet<String> = head
@@ -458,7 +464,7 @@ pub async fn cmd_update(
458464
let head = fetch_own_project(client, slug)
459465
.await?
460466
.ok_or_else(|| CliError::NotFound(format!("project {slug:?} not found")))?;
461-
let next_ts = next_timestamp(&head)?;
467+
let next_ts = next_timestamp(&head, Timestamp::now())?;
462468

463469
// Build the new tag set. For each singleton metadata field:
464470
// - setter present: replace value (strip old, append new)
@@ -515,7 +521,7 @@ pub async fn cmd_update(
515521
///
516522
/// Head-based and verified:
517523
/// 1. Fetch own live head — `NotFound` if absent.
518-
/// 2. Build tombstone at `head.created_at + 1`.
524+
/// 2. Build tombstone at `max(client_now, head.created_at + 1)`.
519525
/// 3. Submit.
520526
/// 4. Re-query the coordinate; if a newer head survived → `Conflict`.
521527
pub async fn cmd_delete(client: &BuzzClient, slug: &str) -> Result<(), CliError> {
@@ -524,7 +530,7 @@ pub async fn cmd_delete(client: &BuzzClient, slug: &str) -> Result<(), CliError>
524530
let head = fetch_own_project(client, slug)
525531
.await?
526532
.ok_or_else(|| CliError::NotFound(format!("project {slug:?} not found")))?;
527-
let next_ts = next_timestamp(&head)?;
533+
let next_ts = next_timestamp(&head, Timestamp::now())?;
528534

529535
let pubkey_hex = client.keys().public_key().to_hex();
530536
let tombstone = build_delete_addressable(KIND_PROJECT, &pubkey_hex, slug)
@@ -1003,31 +1009,51 @@ mod tests {
10031009

10041010
// ── next_timestamp ordering ───────────────────────────────────────────────
10051011

1006-
/// `next_timestamp` must return `head.created_at + 1` regardless of the wall
1007-
/// clock. NIP-MP Deletion rule: a tombstone older than the live head does
1008-
/// NOT remove it, so we must advance strictly off the observed head — never
1009-
/// use wall-clock time, which could be behind a head that was bumped
1010-
/// multiple times in the same second.
1011-
#[test]
1012-
fn next_timestamp_returns_head_plus_one_when_head_is_ahead_of_wall_clock() {
1013-
// Build a minimal signed event with a created_at far in the future.
1012+
fn project_head_at(created_at: u64) -> Event {
10141013
let keys = nostr::Keys::generate();
1015-
let far_future_ts = Timestamp::from(9_999_999_999u64); // year 2286
10161014
let tags = vec![
10171015
make_test_tag(&["d", "platform"]),
10181016
make_test_tag(&["a", &format!("30617:{OWNER_HEX}:buzz")]),
10191017
];
1020-
let builder = rebuild_project("", tags, far_future_ts).expect("valid head envelope");
1021-
let head = builder.sign_with_keys(&keys).expect("sign");
1022-
// Verify the event actually has our future timestamp.
1023-
assert_eq!(head.created_at, far_future_ts);
1018+
rebuild_project("", tags, Timestamp::from(created_at))
1019+
.expect("valid head envelope")
1020+
.sign_with_keys(&keys)
1021+
.expect("sign")
1022+
}
10241023

1025-
// next_timestamp must return far_future + 1, not now().
1026-
let next = next_timestamp(&head).expect("no overflow");
1027-
assert_eq!(
1028-
next.as_secs(),
1029-
far_future_ts.as_secs() + 1,
1030-
"tombstone must be strictly after head, even when head is far in the future"
1024+
#[test]
1025+
fn next_timestamp_uses_later_of_wall_clock_and_after_head() {
1026+
let cases = [
1027+
("stale head", 100, 1_000, 1_000),
1028+
("head equal to now", 1_000, 1_000, 1_001),
1029+
("future head", 1_500, 1_000, 1_501),
1030+
("last timestamp inside future boundary", 1_899, 1_000, 1_900),
1031+
(
1032+
"future boundary cannot be dominated inside the window",
1033+
1_900,
1034+
1_000,
1035+
1_901,
1036+
),
1037+
];
1038+
1039+
for (name, head_ts, now, expected) in cases {
1040+
let head = project_head_at(head_ts);
1041+
let next = next_timestamp(&head, Timestamp::from(now)).expect("no overflow");
1042+
1043+
assert_eq!(next.as_secs(), expected, "case: {name}");
1044+
}
1045+
}
1046+
1047+
#[test]
1048+
fn next_timestamp_rejects_overflowing_head() {
1049+
let head = project_head_at(u64::MAX);
1050+
1051+
let err = next_timestamp(&head, Timestamp::from(1_000u64))
1052+
.expect_err("maximum timestamp cannot be advanced");
1053+
1054+
assert!(
1055+
matches!(err, CliError::Other(ref message) if message == "project timestamp cannot be advanced"),
1056+
"unexpected error: {err}"
10311057
);
10321058
}
10331059

0 commit comments

Comments
 (0)