diff --git a/crates/qbit-prism-server/src/coordinator.rs b/crates/qbit-prism-server/src/coordinator.rs index c3562ec63..495672d66 100644 --- a/crates/qbit-prism-server/src/coordinator.rs +++ b/crates/qbit-prism-server/src/coordinator.rs @@ -3729,7 +3729,8 @@ impl Coordinator { } Landing::LeftActiveChain(tip) => { let reason = format!( - "block left the active chain (tip {tip}) while its landing retried a lost payout revision race after the offer ({offer}); nothing landed; kept for reconciliation, never offered again" + "{} (tip {tip}) while its landing retried a lost payout revision race after the offer ({offer}); nothing landed; kept for reconciliation, never offered again", + crate::ledger::LEFT_ACTIVE_CHAIN_REASON_PREFIX ); tracing::warn!(%block, %reason, "offered candidate awaits chain reconciliation"); return self.ledger.reconcile_candidate(claim, &reason).await; @@ -3798,7 +3799,8 @@ impl Coordinator { } Settled::NotActive => { let reason = format!( - "block is not on the active chain after the offer ({offer}); kept for reconciliation, never offered again" + "{} ({offer}); kept for reconciliation, never offered again", + crate::ledger::NOT_ACTIVE_AFTER_OFFER_REASON_PREFIX ); tracing::warn!(%block, %reason, "offered candidate awaits chain reconciliation"); self.ledger.reconcile_candidate(claim, &reason).await diff --git a/crates/qbit-prism-server/src/coordinator/commit_reconcile_tests.rs b/crates/qbit-prism-server/src/coordinator/commit_reconcile_tests.rs index 721199d22..42bf7b3e8 100644 --- a/crates/qbit-prism-server/src/coordinator/commit_reconcile_tests.rs +++ b/crates/qbit-prism-server/src/coordinator/commit_reconcile_tests.rs @@ -40,6 +40,10 @@ struct NodeState { chainwork: u128, /// `submitblock` calls answered: offers that reached the node. submitted: usize, + /// #885: while set, hold every submitted block off the best chain, as + /// qbit answers a block that lost a tip race (`inconclusive`), without + /// moving the tip. + side_chain: bool, } async fn node_reply( @@ -91,12 +95,15 @@ async fn node_reply( .expect("submitblock carries a hex block"), ) .expect("submitblock carries a hex block"); + node.submitted += 1; + if node.side_chain { + return Json(json!({"id":request["id"],"result":"inconclusive","error":null})); + } node.chain.insert( height + 1, codec::hash_display(&codec::double_sha256(&block[..80])), ); node.chainwork += 1; - node.submitted += 1; Value::Null } method => panic!("unexpected commit-reconcile RPC {method}"), @@ -136,6 +143,7 @@ impl Fixture { chain: BTreeMap::from([(0, "00".repeat(32)), (100, "aa".repeat(32))]), chainwork: 1, submitted: 0, + side_chain: false, })); let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await?; let rpc_url = format!("http://{}/", listener.local_addr()?); @@ -1321,6 +1329,72 @@ async fn commit_reconcile_block_whose_revision_moves_before_its_commit_is_captur settle(outcome, fixture.close().await) } +/// #885: a captured share-pass block (#657) answers as its block's +/// disposition does. A block the node holds only off its best chain lost a +/// tip race after its offer: `stale-job`, cause `parent_grace`, with no +/// credit and no persistence WARN, never the `ledger-confirmation-failed` +/// that feeds the share-append failure warning. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn commit_reconcile_captured_block_that_loses_the_tip_race_is_answered_stale_job( +) -> Result<()> { + let Some(raw) = database_url()? else { + return Ok(()); + }; + let _serial = TEST_LOCK.lock().await; + let fixture = Fixture::open(&raw, |config| { + config.share_commit_timeout = Duration::from_secs(10) + }) + .await?; + let outcome = async { + let proof = fixture.block_bearing_proof().await?; + let (share_id, block_hash) = (proof.share_id.clone(), proof.block_hash.clone()); + let issued = proof.job.wire.payout_revision; + let (mut holder, holder_pid) = fixture.hold_order_lock().await?; + let (submitted, log) = fixture.submit(proof); + wait_until_blocked(&fixture, holder_pid).await?; + let moved = fixture.bump_revision_and_release(&mut holder).await?; + ensure!(moved > issued, "the revision did not move past {issued}"); + until("the captured candidate", || async { + Ok(fixture.outbox_state(&block_hash).await?.as_deref() == Some("pending")) + }) + .await?; + fixture.node.lock().await.side_chain = true; + fixture.drive_candidate().await?; + let answered = answer(submitted).await?; + ensure!( + reason(&answered).as_deref() == Some("stale-job"), + "a captured block that lost the tip race was answered {:?}", + reason(&answered) + ); + let causes = super::miner_tests::stale_causes::stale_causes(&fixture.coordinator.metrics); + ensure!( + causes == [0., 0., 1., 0.], + "the lost race was not counted under parent_grace: {causes:?}" + ); + ensure!( + !log.text().contains("share persistence failed"), + "a lost tip race was logged as a database failure:\n{}", + log.text() + ); + ensure!( + fixture.outbox_state(&block_hash).await?.as_deref() == Some("reconciliation"), + "a side-chain block must stay in reconciliation after its offer" + ); + ensure!( + fixture.submitblock_calls().await == 1, + "offered other than once" + ); + ensure!( + fixture.rows(&share_id).await? == 0, + "a block off the best chain credited its deferred share" + ); + drop(holder); + Ok::<_, anyhow::Error>(()) + } + .await; + settle(outcome, fixture.close().await) +} + /// The fence's refusal, from a share queued behind `ORDER_LOCK` and so past /// its submit check: the submit check's own answer for superseded work, /// `stale-job` with its one `payout_revision` cause, never the diff --git a/crates/qbit-prism-server/src/coordinator/d2_below_target_tests.rs b/crates/qbit-prism-server/src/coordinator/d2_below_target_tests.rs index 37665c9f3..0a919af38 100644 --- a/crates/qbit-prism-server/src/coordinator/d2_below_target_tests.rs +++ b/crates/qbit-prism-server/src/coordinator/d2_below_target_tests.rs @@ -111,6 +111,10 @@ enum SubmitMode { LoseReply, /// The node refuses the block and its tip does not move. Reject, + /// The node holds the block as valid but off its best chain, as qbit's + /// `submitblock` answers a block that lost a tip race (`inconclusive`), + /// and its tip does not move (#885). + SideChain, } impl SubmitMode { @@ -212,6 +216,7 @@ async fn node_reply( node.submissions += 1; match node.submit { SubmitMode::Reject => json!("rejected"), + SubmitMode::SideChain => json!("inconclusive"), mode => { node.adopt(tip_height + 1, hash); if mode == SubmitMode::LoseReply { @@ -951,6 +956,90 @@ async fn block_only_proof_the_node_rejects_fails_the_submission_without_credit() settle(outcome, fixture.close().await) } +/// #885: a block-only proof whose block the node holds only off its best chain +/// (a lost tip race, `inconclusive`) is answered `stale-job`, cause +/// `parent_grace`, as a race lost before the offer is: the ledger recorded and +/// offered the block, so it is not `ledger-confirmation-failed`, which feeds +/// the share-append failure warning, and no persistence WARN is logged. +#[tokio::test(flavor = "multi_thread", worker_threads = 4)] +async fn block_only_proof_whose_block_loses_the_tip_race_is_stale_job_without_credit() -> Result<()> +{ + let Some(raw) = database_url()? else { + return Ok(()); + }; + let _serial = TEST_LOCK.lock().await; + let case = vector_case("block-only-proof-rejected")?; + let fixture = Fixture::open(&raw, &case).await?; + let outcome = async { + let name = "block-only-proof-side-chain"; + fixture.node.lock().await.submit = SubmitMode::SideChain; + let solved = solve(&fixture, &case).await?; + assert_uncredited_intent(&fixture, &solved, name).await?; + + fixture.drive_candidate().await??; + ensure!( + fixture.submissions().await == 1, + "{name}: the block reached submitblock more than once" + ); + ensure!( + fixture.outbox_state(&solved.block_hash).await?.as_deref() == Some("reconciliation"), + "{name}: a side-chain block must stay in reconciliation after its offer" + ); + let log = solved.log.clone(); + let share_id = solved.share_id.clone(); + let error = submission_result(solved, name) + .await? + .expect_err("a block off the best chain cannot produce an accepted share"); + ensure!( + error.code == 21 + && error.reason_id.as_deref() == Some("stale-job") + && error.message == "stale job", + "{name}: the miner saw {} {:?} {:?}", + error.code, + error.message, + error.reason_id + ); + let metrics = fixture.coordinator.metrics.render(); + for (series, want) in [ + ( + "qbit_prism_stale_job_rejections_total{cause=\"parent_grace\"} ", + "1", + ), + ( + "qbit_prism_stale_job_rejections_total{cause=\"payout_revision\"} ", + "0", + ), + ] { + let got = metrics.lines().find_map(|line| line.strip_prefix(series)); + ensure!( + got == Some(want), + "{name}: {series}is {got:?}, wanted {want}" + ); + } + ensure!( + !log.text().contains("share persistence failed"), + "{name}: a lost tip race was logged as a ledger failure:\n{}", + log.text() + ); + + // The network moves on without the side-chain block. + { + let mut node = fixture.node.lock().await; + let height = node.tip_height() + 1; + node.adopt(height, "bb".repeat(32)); + } + fixture.coordinator.refresh_once().await?; + ensure!( + fixture.credit_rows(&share_id).await? == 0, + "{name}: a block off the best chain was credited" + ); + assert_projection(name, &expectation(&case)?, &fixture.projection().await?)?; + Ok::<_, anyhow::Error>(()) + } + .await; + settle(outcome, fixture.close().await) +} + #[tokio::test(flavor = "multi_thread", worker_threads = 4)] async fn share_passing_block_proof_is_credited_its_assigned_difficulty_at_once() -> Result<()> { let Some(raw) = database_url()? else { diff --git a/crates/qbit-prism-server/src/coordinator/miner_submit.rs b/crates/qbit-prism-server/src/coordinator/miner_submit.rs index 48141778a..25ce22c75 100644 --- a/crates/qbit-prism-server/src/coordinator/miner_submit.rs +++ b/crates/qbit-prism-server/src/coordinator/miner_submit.rs @@ -60,9 +60,11 @@ pub(super) enum SaveOutcome { /// A block-only proof whose block is stale by the pool's own decision, /// not by a ledger failure: its candidate was abandoned before its offer /// (a parent change, the #478 overpay ceiling, or capture turned off), or - /// it is block-only work, whose share is never credited. Also a - /// share-pass append the payout-revision fence refused before any write - /// (#675). `stale-job`, with the cause recorded once. + /// it is block-only work, whose share is never credited; or its offered + /// block lost a tip race the chain decided (#885, + /// [`candidate_lost_tip_race`]). Also a share-pass append the + /// payout-revision fence refused before any write (#675). `stale-job`, + /// with the cause recorded once. Superseded(StaleJobCause), /// Not known by the acknowledgement deadline; the share may still be /// credited. @@ -214,6 +216,39 @@ fn closed_gate_outcome(closure: Option, error: anyhow::Error) -> Sa } } +/// #885: whether a deferred share's candidate, polled after its offer, lost a +/// tip race the chain has already decided: settled as a proven orphan (#415), +/// or kept in reconciliation because the node refused it with a side-chain +/// reply (`inconclusive`, `duplicate`, `duplicate-inconclusive`: a valid +/// block that did not become the tip) and the observation after its landing, +/// or the landing run again after a lost payout-revision race, found it not +/// active. A proven orphan is the chain's verdict whatever its offer's +/// outcome, an unknown delivery included, unless the node refused the block +/// as invalid. Either is the chain's staleness verdict on a block the +/// ledger recorded and offered, not a ledger failure. Any other refusal reply +/// (an invalid block), a missing one, or a reason naming a landing refusal or +/// a post-offer error is not proven a lost race and keeps the strict answer. +fn candidate_lost_tip_race( + state: &str, + offer_outcome: Option<&str>, + offer_reply: Option<&str>, + last_error: Option<&str>, +) -> bool { + let rejected = offer_outcome == Some(OfferOutcome::Rejected.as_str()); + let side_chain = + offer_reply.is_some_and(|reply| crate::ledger::SIDE_CHAIN_REPLIES.contains(&reply)); + if state == ORPHANED_STATE { + return !rejected || side_chain; + } + state == CandidateState::Reconciliation.as_str() + && rejected + && side_chain + && last_error.is_some_and(|reason| { + reason.starts_with(crate::ledger::NOT_ACTIVE_AFTER_OFFER_REASON_PREFIX) + || reason.starts_with(crate::ledger::LEFT_ACTIVE_CHAIN_REASON_PREFIX) + }) +} + /// A refusal at the append's pre-COMMIT hook: COMMIT was never sent and the /// attempt rolled back, so nothing was written. fn refused_at_hook(error: &anyhow::Error) -> bool { @@ -1558,8 +1593,8 @@ impl Coordinator { let ledger = self.ledger.clone(); let (share_id, block_hash) = (share_id.to_owned(), block_hash.to_owned()); async move { - sqlx::query_as::<_, (bool, Option, Option, Option)>( - "SELECT EXISTS(SELECT 1 FROM qbit_share_ledger WHERE share_id=$1 AND share_seq>=qbit_prism_share_probe_floor()), (SELECT state FROM qbit_block_candidate_outbox WHERE block_hash=$2), (SELECT offer_outcome FROM qbit_block_candidate_outbox WHERE block_hash=$2), (SELECT last_error FROM qbit_block_candidate_outbox WHERE block_hash=$2)", + sqlx::query_as::<_, (bool, Option, Option, Option, Option)>( + "SELECT EXISTS(SELECT 1 FROM qbit_share_ledger WHERE share_id=$1 AND share_seq>=qbit_prism_share_probe_floor()), (SELECT state FROM qbit_block_candidate_outbox WHERE block_hash=$2), (SELECT offer_outcome FROM qbit_block_candidate_outbox WHERE block_hash=$2), (SELECT last_error FROM qbit_block_candidate_outbox WHERE block_hash=$2), (SELECT offer_reply FROM qbit_block_candidate_outbox WHERE block_hash=$2)", ) .bind(share_id) .bind(block_hash) @@ -1572,7 +1607,7 @@ impl Coordinator { .map(|joined| anyhow::Ok(joined??)); match poll { Err(_) => break, - Ok(Ok((true, _, _, _))) => return SaveOutcome::Accepted, + Ok(Ok((true, _, _, _, _))) => return SaveOutcome::Accepted, // A candidate abandoned before its offer never reached the // node: the pool itself decided the block is stale (its // parent changed, the #478 overpay ceiling refused it, or @@ -1580,7 +1615,7 @@ impl Coordinator { // a proof at submit, never a ledger failure: the ledger wrote // the candidate, and `ledger-confirmation-failed` feeds the // share-append failure warning. - Ok(Ok((false, Some(state), _, reason))) if state == "abandoned" => { + Ok(Ok((false, Some(state), _, reason, _))) if state == "abandoned" => { return SaveOutcome::Superseded( if reason.as_deref() == Some("parent superseded") { StaleJobCause::ParentGrace @@ -1589,24 +1624,51 @@ impl Coordinator { }, ) } - // D2b's answer for a candidate the node refused after the - // offer (kept in reconciliation with the rejected outcome), - // or one the chain proved an orphan after the offer (#415, - // terminal with its evidence). It is not a proof: - // reconciliation still credits the deferred share if the - // block later becomes active, and so does the reorg - // reconciler for an orphaned block, from its landed audit. - Ok(Ok((false, Some(state), outcome, _))) + // #885: a block that lost a tip race after its offer (a + // proven orphan, or a side-chain reply the chain observation + // confirmed) is stale by the chain's own decision, as a lost + // race before the offer is: `stale-job`, cause + // `parent_grace`, never a ledger failure. The block was + // recorded and offered. It is not a final verdict either: + // reconciliation, or the reorg reconciler for an orphan, + // still credits the deferred share if the block later + // becomes active. + Ok(Ok((false, Some(state), outcome, reason, reply))) + if candidate_lost_tip_race( + &state, + outcome.as_deref(), + reply.as_deref(), + reason.as_deref(), + ) => + { + tracing::info!( + share_id, + block_hash, + path = log_path, + state, + reply, + last_error = reason, + "{log_path} proof's block lost a tip race after its offer; answered stale-job" + ); + return SaveOutcome::Superseded(StaleJobCause::ParentGrace); + } + // D2b's answer for any other candidate the node refused after + // the offer (kept in reconciliation with the rejected + // outcome): an invalid block, or a side-chain block whose + // landing or post-offer processing failed. The node's reply + // goes into the persistence WARN. + Ok(Ok((false, Some(state), outcome, _, reply))) if state == ORPHANED_STATE || (state == CandidateState::Reconciliation.as_str() && outcome.as_deref() == Some(OfferOutcome::Rejected.as_str())) => { return SaveOutcome::Failed(anyhow::anyhow!( - "block-only proof was not accepted on the active chain" + "{log_path} proof was not accepted on the active chain ({state}, node reply {})", + reply.as_deref().unwrap_or("none") )) } - Ok(Ok((false, Some(_), _, _))) => phase = "candidate-pending", - Ok(Ok((false, None, _, _))) => {} + Ok(Ok((false, Some(_), _, _, _))) => phase = "candidate-pending", + Ok(Ok((false, None, _, _, _))) => {} // The candidate is already durable, so a failed read proves // nothing about its credit. Ok(Err(error)) => { diff --git a/crates/qbit-prism-server/src/coordinator/miner_submit_acquire_tests.rs b/crates/qbit-prism-server/src/coordinator/miner_submit_acquire_tests.rs index f24688b85..a330f7877 100644 --- a/crates/qbit-prism-server/src/coordinator/miner_submit_acquire_tests.rs +++ b/crates/qbit-prism-server/src/coordinator/miner_submit_acquire_tests.rs @@ -626,34 +626,77 @@ async fn block_only_poll_checkout_cancel_and_deadline_stay_unknown() -> Result<( #[tokio::test] async fn block_only_poll_terminal_results_preserve_checkout_success() -> Result<()> { + /// The outbox row the poll finds. A rejected row is kept in + /// reconciliation with `(offer_reply, last_error)`; the schema requires + /// a rejected row's reply. #[derive(Clone, Copy, Debug, PartialEq, Eq)] enum Disposition { Accepted, Abandoned, + /// A proven orphan whose offer the node accepted (#415). Orphaned, - Rejected, + /// A proven orphan the node had refused as invalid. + OrphanedInvalid, + /// A proven orphan the node had held off its best chain. + OrphanedSideChain, + Rejected(&'static str, &'static str), } + // #885: what the settler writes for a block the observation after its + // landing found not active, and for the two post-offer failures. + const NOT_ACTIVE: &str = "block is not on the active chain after the offer (node rejected the offer: inconclusive); kept for reconciliation, never offered again"; + const LANDING_FAILED: &str = "landing failed after the offer (node rejected the offer: inconclusive): test landing refusal"; + const POST_OFFER_FAILED: &str = + "post-offer processing failed (node rejected the offer: inconclusive): test database error"; + const LEFT_ACTIVE_CHAIN: &str = "block left the active chain (tip test) while its landing retried a lost payout revision race after the offer (node rejected the offer: inconclusive); nothing landed; kept for reconciliation, never offered again"; for disposition in [ Disposition::Accepted, Disposition::Abandoned, Disposition::Orphaned, - Disposition::Rejected, + Disposition::OrphanedInvalid, + Disposition::OrphanedSideChain, + // A refusal reply that is not a side-chain block: the pool built an + // invalid block. Strict, even with the ordinary not-active reason. + Disposition::Rejected("test refusal", NOT_ACTIVE), + // A side-chain reply the observation confirmed: a lost tip race. + Disposition::Rejected("inconclusive", NOT_ACTIVE), + Disposition::Rejected("duplicate", NOT_ACTIVE), + Disposition::Rejected("duplicate-inconclusive", NOT_ACTIVE), + // The same race, found when the landing ran again after a lost + // payout-revision race. + Disposition::Rejected("inconclusive", LEFT_ACTIVE_CHAIN), + Disposition::Rejected("test refusal", LEFT_ACTIVE_CHAIN), + // A side-chain reply whose landing or post-offer processing failed: + // not proven a lost race, and possibly the ledger. + Disposition::Rejected("inconclusive", LANDING_FAILED), + Disposition::Rejected("inconclusive", POST_OFFER_FAILED), ] { eprintln!("block-only terminal disposition: {disposition:?}"); - with_database(|h| Box::pin(async move { - let mut persist = Box::pin(h.persist(TokioInstant::now())); - let held = first_poll(h, &mut persist).await?; - match disposition { - Disposition::Accepted => { - h.plain.append(h.share.clone(), None).await?; - } - Disposition::Abandoned | Disposition::Orphaned => { - let state = match disposition { - Disposition::Abandoned => "abandoned", - _ => "orphaned", - }; - sqlx::query( - "UPDATE qbit_block_candidate_outbox SET + with_database(|h| { + Box::pin(async move { + let mut persist = Box::pin(h.persist(TokioInstant::now())); + let held = first_poll(h, &mut persist).await?; + match disposition { + Disposition::Accepted => { + h.plain.append(h.share.clone(), None).await?; + } + Disposition::Abandoned + | Disposition::Orphaned + | Disposition::OrphanedInvalid + | Disposition::OrphanedSideChain => { + let state = match disposition { + Disposition::Abandoned => "abandoned", + _ => "orphaned", + }; + let (outcome, reply) = match disposition { + Disposition::Abandoned => (None, None), + Disposition::Orphaned => (Some("unknown"), None), + Disposition::OrphanedSideChain => { + (Some("rejected"), Some("inconclusive")) + } + _ => (Some("rejected"), Some("bad-cb-amount")), + }; + sqlx::query( + "UPDATE qbit_block_candidate_outbox SET state=$1,completed_at=clock_timestamp(),candidate=NULL, block_bytes=NULL,window_anchor_ms=NULL, window_prior_balances_sha256=NULL,window_first_share_seq=NULL, @@ -661,47 +704,80 @@ async fn block_only_poll_terminal_results_preserve_checkout_success() -> Result< window_snapshot_sha256=NULL, offer_reserved_at=CASE WHEN $1='orphaned' THEN clock_timestamp() END, offer_reserved_by=CASE WHEN $1='orphaned' THEN 'test' END, - offer_outcome=CASE WHEN $1='orphaned' THEN 'unknown' END, + offered_at_ms=CASE WHEN $2='rejected' THEN 1234 END, + offer_outcome=$2,offer_reply=$3, last_error='test disposition'", - ).bind(state).execute(&h.side).await?; - } - Disposition::Rejected => { - sqlx::query( - "UPDATE qbit_block_candidate_outbox SET + ) + .bind(state) + .bind(outcome) + .bind(reply) + .execute(&h.side) + .await?; + } + Disposition::Rejected(reply, last_error) => { + sqlx::query( + "UPDATE qbit_block_candidate_outbox SET state='reconciliation',offer_outcome='rejected', offer_reserved_at=clock_timestamp(),offer_reserved_by='test', - offered_at_ms=1234,offer_reply='test refusal',last_error='test refusal'", - ).execute(&h.side).await?; + offered_at_ms=1234,offer_reply=$1,last_error=$2", + ) + .bind(reply) + .bind(last_error) + .execute(&h.side) + .await?; + } } - } - let before = counts(h.metrics()); - drop(held); - let answer = tokio::time::timeout(WAIT, persist).await?; - match disposition { - Disposition::Accepted => assert!(matches!(answer, SaveOutcome::Accepted)), - // Abandoned before its offer: the pool's own staleness - // decision, `stale-job`, never a ledger failure (#478). - Disposition::Abandoned => assert!( - matches!( - answer, - SaveOutcome::Superseded(crate::metrics::StaleJobCause::PayoutRevision) + let before = counts(h.metrics()); + drop(held); + let answer = tokio::time::timeout(WAIT, persist).await?; + let lost_race = matches!( + disposition, + Disposition::Orphaned + | Disposition::OrphanedSideChain + | Disposition::Rejected( + "inconclusive" | "duplicate" | "duplicate-inconclusive", + NOT_ACTIVE | LEFT_ACTIVE_CHAIN + ) + ); + match disposition { + Disposition::Accepted => assert!(matches!(answer, SaveOutcome::Accepted)), + // Abandoned before its offer: the pool's own staleness + // decision, `stale-job`, never a ledger failure (#478). + Disposition::Abandoned => assert!( + matches!( + answer, + SaveOutcome::Superseded(crate::metrics::StaleJobCause::PayoutRevision) + ), + "abandoned before its offer: {answer:?}" ), - "abandoned before its offer: {answer:?}" - ), - Disposition::Orphaned | Disposition::Rejected => { - let SaveOutcome::Failed(error) = answer else { - panic!("terminal disposition {disposition:?}: {answer:?}") - }; - assert_eq!( - error.to_string(), - "block-only proof was not accepted on the active chain" - ); + // #885: a tip race the chain decided after the offer is + // `stale-job`, `parent_grace`, as one lost before it is. + _ if lost_race => assert!( + matches!( + answer, + SaveOutcome::Superseded(crate::metrics::StaleJobCause::ParentGrace) + ), + "lost tip race {disposition:?}: {answer:?}" + ), + _ => { + let SaveOutcome::Failed(error) = answer else { + panic!("terminal disposition {disposition:?}: {answer:?}") + }; + let error = error.to_string(); + assert!( + error.starts_with( + "block-only proof was not accepted on the active chain" + ), + "{disposition:?}: {error}" + ); + } } - } - assert_eq!(counts(h.metrics()), (before.0 + 1., before.1)); - drop(tokio::time::timeout(WAIT, h.ledger().pool.acquire()).await??); - Ok(()) - })).await?; + assert_eq!(counts(h.metrics()), (before.0 + 1., before.1)); + drop(tokio::time::timeout(WAIT, h.ledger().pool.acquire()).await??); + Ok(()) + }) + }) + .await?; } Ok(()) } diff --git a/crates/qbit-prism-server/src/ledger.rs b/crates/qbit-prism-server/src/ledger.rs index 08631e671..4e8cb47f8 100644 --- a/crates/qbit-prism-server/src/ledger.rs +++ b/crates/qbit-prism-server/src/ledger.rs @@ -39,8 +39,9 @@ pub use candidates::{ coinbase_witness_reserved_value, header_bits_hex, Candidate, CandidateClaim, CandidateCtv, CandidateState, ClaimLifecycle, ClaimParts, LandedAudit, OfferOutcome, OfferRecord, RecoveryClaim, RecoveryReader, RecoveryRow, RecoveryTakeover, SignerKeys, - ADOPTED_OFFER_REPLY_PREFIX, LANDING_FAILED_REASON_PREFIX, OFFER_NOT_SENT_REASON_PREFIX, - ORPHANED_STATE, SIDE_CHAIN_REPLIES, + ADOPTED_OFFER_REPLY_PREFIX, LANDING_FAILED_REASON_PREFIX, LEFT_ACTIVE_CHAIN_REASON_PREFIX, + NOT_ACTIVE_AFTER_OFFER_REASON_PREFIX, OFFER_NOT_SENT_REASON_PREFIX, ORPHANED_STATE, + SIDE_CHAIN_REPLIES, }; use candidates::{prepare_candidate_observed, prepare_fenced_candidate}; pub use claim_observer::UNRECORDED_LEASE; diff --git a/crates/qbit-prism-server/src/ledger/candidates.rs b/crates/qbit-prism-server/src/ledger/candidates.rs index 84556f88a..ae5b60019 100644 --- a/crates/qbit-prism-server/src/ledger/candidates.rs +++ b/crates/qbit-prism-server/src/ledger/candidates.rs @@ -194,6 +194,21 @@ pub fn adoption_evidence(block_hash: &str, height: u64, tip: &str) -> String { /// recovery overwrites this reason (#493). pub const LANDING_FAILED_REASON_PREFIX: &str = "landing failed after the offer"; +/// The `last_error` prefix of a reconciliation row whose audit landed and +/// whose block the chain observation after the offer did not find active, +/// and nothing else failed. A block-only proof whose block was refused with a +/// side-chain reply and carries this reason lost a tip race, and is answered +/// `stale-job` (#885); any other reason (a landing refusal, a post-offer +/// error) keeps the strict answer. +pub const NOT_ACTIVE_AFTER_OFFER_REASON_PREFIX: &str = + "block is not on the active chain after the offer"; + +/// The `last_error` prefix of a reconciliation row whose landing, run again +/// after a lost payout-revision race, found the block no longer active and +/// landed nothing. For a side-chain reply this is the same lost tip race as +/// [`NOT_ACTIVE_AFTER_OFFER_REASON_PREFIX`] (#885). +pub const LEFT_ACTIVE_CHAIN_REASON_PREFIX: &str = "block left the active chain"; + /// The `last_error` prefix of a `pending` row whose reservation was returned /// because its `submitblock` call provably never ran on the node: the /// connection the request would have been written to was never established diff --git a/docs/prism-ledger-ops.md b/docs/prism-ledger-ops.md index e7fb811b2..9a9c3490e 100644 --- a/docs/prism-ledger-ops.md +++ b/docs/prism-ledger-ops.md @@ -2167,7 +2167,18 @@ the tip (a lost race) is answered `stale-job` too, counted under `parent_grace`. An abandonment before the offer is the pool's own staleness decision on a block the ledger wrote correctly, so it never answers `ledger-confirmation-failed`. That answer feeds the share-append failure -warning. +warning. The same holds after the offer (#885): a block the node held only +off its best chain (a side-chain reply, `inconclusive`, `duplicate` or +`duplicate-inconclusive`) that the chain observation then found not active, +or one settled as a proven orphan that the node did not refuse as invalid, +lost a tip race, and its deferred share is +answered `stale-job` under `parent_grace`. A block the node refused as +invalid, or one it refused with a side-chain reply whose landing or +post-offer processing then failed, keeps `ledger-confirmation-failed`. A race the node first accepted (a `null` +reply) and then reorganised away is not settled within the acknowledgement +bound at the default `PRISM_CANDIDATE_ORPHAN_CONFIRMATIONS` (6) and is still +answered `ledger-outcome-unknown`; with that setting at 1 its orphan proof can +arrive within the bound, and it is then answered `stale-job` too. The ceiling bounds, in every order of confirmations, each block whose payout revision was already superseded when its offer was reserved. It does not @@ -2373,6 +2384,9 @@ read from the canonical balances and stay exact. series. - a capture abandoned before its offer: under `payout_revision` for a ceiling refusal or capture off, under `parent_grace` for a lost race. + - a capture that lost a tip race after its offer, by a side-chain reply or + a proven orphan the node did not refuse as invalid, under `parent_grace` + (#885). - **Acknowledgement.** A block captured from ordinary work defers its share: the miner is acknowledged when the block confirms and the share is credited, within the block-only acknowledgement bound (60 s), as for every diff --git a/docs/prism-rejections.md b/docs/prism-rejections.md index 099114c86..57eccc600 100644 --- a/docs/prism-rejections.md +++ b/docs/prism-rejections.md @@ -24,7 +24,7 @@ share-rejection label set. | `internal-error` | An internal coordinator failure prevented normal classification. | | `pool-closed` | The coordinator was no longer accepting shares. | | `block-stale` | Legacy taxonomy; no native share producer. The block candidate height was stale against the active qbit tip. | -| `ledger-confirmation-failed` | The ledger did not record the share. For share-pass submissions, the commit was not sent or was rolled back. A share whose payout revision moved between its submit check and its commit is not answered here: the append's fence refuses it before any write as `stale-job`, cause `payout_revision` (#675), and while capture is on (`PRISM_CAPTURE_OVERPAY_CEILING_BPS` > 0) a share-pass submission that carries a found block is not refused at all: its block is captured and its answer follows the block's, as for a block-only proof (#657). Nor is a share whose published-work lease's commit gate could not prove its authority: since #716 that is answered as admission answers readiness it cannot prove, as is contention for that authority's locks that outlasts the acknowledgement deadline; shorter contention is waited out and retried (see "Commit-gate refusals"). For block-only proofs, the block was not on the active chain when its candidate was abandoned, refused by the node after the offer, or settled as a proven orphan (#415); a later reorg or late landing can still credit it. | +| `ledger-confirmation-failed` | The ledger did not record the share. For share-pass submissions, the commit was not sent or was rolled back. A share whose payout revision moved between its submit check and its commit is not answered here: the append's fence refuses it before any write as `stale-job`, cause `payout_revision` (#675), and while capture is on (`PRISM_CAPTURE_OVERPAY_CEILING_BPS` > 0) a share-pass submission that carries a found block is not refused at all: its block is captured and its answer follows the block's, as for a block-only proof (#657). Nor is a share whose published-work lease's commit gate could not prove its authority: since #716 that is answered as admission answers readiness it cannot prove, as is contention for that authority's locks that outlasts the acknowledgement deadline; shorter contention is waited out and retried (see "Commit-gate refusals"). For block-only proofs, and for share-pass proofs whose block was captured (#657), the node refused the block after the offer with a reply other than a side-chain one (an invalid block), or refused it with a side-chain reply and the block's landing or post-offer processing then failed (after an accepted or unknown offer such a block is still pending at the acknowledgement bound and is answered `ledger-outcome-unknown`); the WARN `share persistence failed` names the node's reply, and a later reorg or late landing can still credit it. Not here: a candidate abandoned before its offer, which is `stale-job` (#478; see "Stale-job causes"), and a block that lost a tip race after its offer, which is `stale-job`, cause `parent_grace` (#885): one the node held only off its best chain (`inconclusive`, `duplicate` or `duplicate-inconclusive`) and the chain then found not active, or a proven orphan (#415) the node did not refuse as invalid. | | `ledger-outcome-unknown` | The ledger outcome was not known by the acknowledgement deadline; the share may still be credited (logged with `share_id`). | The native coordinator exposes its produced reason IDs in: @@ -246,7 +246,7 @@ a cause, and backend-unavailable answers are never stale-job causes. | --- | --- | --- | | `resume_expired` | Stratum found the job's absolute resume lease expired after restoring it for a reconnected miner, before submitting to the coordinator. Message `stale job`. | Reconnect churn and how long miners take to resubmit old work: `qbit_prism_connections`, `qbit_prism_stratum_connection_refusals_total` and the retention settings `PRISM_STRATUM_SAME_TIP_JOB_RETENTION_SECONDS` and `PRISM_STRATUM_STALE_GRACE_SECONDS`, whichever is longer. | | `fee_floor` | The coordinator found the job's CTV fanout fee below the live relay floor, or the floor unavailable. Message `job CTV fee is below the current relay floor`. | Node relay policy and mempool minimum fee, then whether replacement work reached miners: `qbit_prism_authorized_missing_current_work` and `qbit_prism_stratum_current_tip_coverage_gap_seconds`. | -| `parent_grace` | The job's parent is not the published tip, and stale grace was unavailable, expired, or the job's parent is not the new tip's immediate parent. Block-only work (#478) is counted here after a tip change without any grace check, and so is a capture abandoned before its offer because its parent is no longer the tip. Message `stale job`. | Tip freshness and delivery: `qbit_prism_stratum_semantic_current_work_ratio`, `qbit_prism_authorized_missing_current_work`, `qbit_prism_stratum_current_tip_coverage_gap_seconds`, `qbit_prism_job_delivery_failures_total` and `qbit_prism_grace_credited_shares_total`. | +| `parent_grace` | The job's parent is not the published tip, and stale grace was unavailable, expired, or the job's parent is not the new tip's immediate parent. Block-only work (#478) is counted here after a tip change without any grace check, and so is a capture abandoned before its offer because its parent is no longer the tip. So is a deferred-share proof whose block lost a tip race after its offer (#885): the node answered a side-chain reply and the chain observation after its landing (or its landing run again after a lost payout-revision race) found it not active, or the block was settled as a proven orphan the node did not refuse as invalid; an INFO line names the block, the reply and the reason. A reorg that later activates such a block still credits its share. Message `stale job`. | Tip freshness and delivery: `qbit_prism_stratum_semantic_current_work_ratio`, `qbit_prism_authorized_missing_current_work`, `qbit_prism_stratum_current_tip_coverage_gap_seconds`, `qbit_prism_job_delivery_failures_total` and `qbit_prism_grace_credited_shares_total`. | | `payout_revision` | The parent is current, but either the job's payout snapshot or the current published payout snapshot disagrees with the durable payout revision, and no share-lease exception applies. Since #478 a block-bearing proof from ordinary work on the active tip is captured instead and is not counted here. Counted here: block-only work, which a same-parent payout replacement retired (its plain shares, and the share of a block captured from it), and a capture abandoned before its offer by the overpay ceiling or with capture off. Also counted here, after every check above passed (a stale-grace share included): a share-pass submission whose revision a settlement moved before the append's fence read it under `ORDER_LOCK`, refused there before any write (#675). That is a plain share, or a block-bearing one with capture off, whose lost block a WARN names; with capture on its block is captured instead (#657). It is counted when the miner is answered `stale-job`; a block-bearing append still waiting at its acknowledgement deadline was answered `ledger-outcome-unknown` instead and is not. Around each pool block: the block moves the revision twice on its new tip, when a frontend first records the tip and when the landing confirms the block, so work published on the new tip in between is superseded at the confirmation. Since #752 the confirmation (like every same-tip bump) notifies every frontend through PostgreSQL, and each republishes at once instead of at its next `PRISM_BLOCKPOLL_SECONDS` tick; what is still counted here is a share on that work sent before the replacement reached its session. A frontend whose notification listener is down keeps its tick and logs a WARN, at most once a minute, until it reconnects. Message `stale job`. | Payout revision changes and replacement delivery: `qbit_prism_pending_job_builds`, `qbit_prism_job_delivery_successes_total`, `qbit_prism_job_delivery_failures_total` and the coverage series above. | | `window_not_held` | A block-bearing proof passed every check above, but the candidate enqueue, in the transaction that would write the candidate, found that the current primary does not hold the window its coinbase pays: the window's last row is absent or is another share credited after the window's anchor (#619). After an asynchronous promotion that lost the end of the replication gap, a session can still hold a job on work read from the lost history. The block is never enqueued or offered, and the share it carried is not credited. Message `stale job`; a WARN names the block and #619. The ledger counts the refusal itself, so one that finishes after the miner's acknowledgement deadline (the miner then saw `ledger-outcome-unknown`) is counted too. | A database promotion: the refresh logs and `qbit_prism_refresh_seconds{trigger="writer_timeline"}`, then the HA reference's promotion steps. See [the #619 design note](prism-async-promotion-gap-blocks.md). | diff --git a/test/prism-gated-tests.txt b/test/prism-gated-tests.txt index 002dc35f9..de1fc1027 100644 --- a/test/prism-gated-tests.txt +++ b/test/prism-gated-tests.txt @@ -794,6 +794,7 @@ qbit-prism-server::qbit_prism_server::coordinator::commit_reconcile_tests::commi qbit-prism-server::qbit_prism_server::coordinator::commit_reconcile_tests::commit_reconcile_block_only_still_pending_at_its_bound_is_unknown qbit-prism-server::qbit_prism_server::coordinator::commit_reconcile_tests::commit_reconcile_block_whose_revision_moves_before_its_commit_is_captured_and_lands_once qbit-prism-server::qbit_prism_server::coordinator::commit_reconcile_tests::commit_reconcile_block_whose_revision_moves_with_capture_off_is_refused_as_before +qbit-prism-server::qbit_prism_server::coordinator::commit_reconcile_tests::commit_reconcile_captured_block_that_loses_the_tip_race_is_answered_stale_job qbit-prism-server::qbit_prism_server::coordinator::commit_reconcile_tests::commit_reconcile_commit_held_past_the_deadline_is_accepted_late qbit-prism-server::qbit_prism_server::coordinator::commit_reconcile_tests::commit_reconcile_commit_held_past_the_grace_is_unknown_and_lands_later qbit-prism-server::qbit_prism_server::coordinator::commit_reconcile_tests::commit_reconcile_commit_refused_by_the_server_is_rejected_without_a_row @@ -821,6 +822,7 @@ qbit-prism-server::qbit_prism_server::coordinator::compact_decode_tests::cancell qbit-prism-server::qbit_prism_server::coordinator::d2_below_target_tests::block_only_credit_survives_a_reorg_that_disconnects_its_block qbit-prism-server::qbit_prism_server::coordinator::d2_below_target_tests::block_only_proof_is_credited_network_work_only_once_the_block_is_active qbit-prism-server::qbit_prism_server::coordinator::d2_below_target_tests::block_only_proof_the_node_rejects_fails_the_submission_without_credit +qbit-prism-server::qbit_prism_server::coordinator::d2_below_target_tests::block_only_proof_whose_block_loses_the_tip_race_is_stale_job_without_credit qbit-prism-server::qbit_prism_server::coordinator::d2_below_target_tests::block_only_proof_with_a_lost_submitblock_reply_is_credited_once_by_reconciliation qbit-prism-server::qbit_prism_server::coordinator::d2_below_target_tests::share_passing_block_proof_is_credited_its_assigned_difficulty_at_once qbit-prism-server::qbit_prism_server::coordinator::d2_bootstrap_tests::a_bootstrap_block_still_pays_carried_forward_balances