Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 4 additions & 2 deletions crates/qbit-prism-server/src/coordinator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -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}"),
Expand Down Expand Up @@ -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()?);
Expand Down Expand Up @@ -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
Expand Down
89 changes: 89 additions & 0 deletions crates/qbit-prism-server/src/coordinator/d2_below_target_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down Expand Up @@ -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 {
Expand Down
98 changes: 80 additions & 18 deletions crates/qbit-prism-server/src/coordinator/miner_submit.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -214,6 +216,39 @@ fn closed_gate_outcome(closure: Option<GateClosure>, 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 {
Expand Down Expand Up @@ -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<String>, Option<String>, Option<String>)>(
"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<String>, Option<String>, Option<String>, Option<String>)>(
"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)
Expand All @@ -1572,15 +1607,15 @@ 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
// capture is off). That is `stale-job`, as base answered such
// 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
Expand All @@ -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)) => {
Expand Down
Loading