Repository navigation
Expand file tree
/
Copy pathpush_queue_service.rs
More file actions
9871 lines (9419 loc) · 361 KB
/
Copy pathpush_queue_service.rs
File metadata and controls
9871 lines (9419 loc) · 361 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use std::{
sync::{
Arc,
atomic::{AtomicU64, Ordering},
},
time::{Duration, Instant},
};
use sea_orm::{DatabaseTransaction, TransactionTrait};
use serde_json::Value as JsonValue;
use sha2::{Digest, Sha256};
use crate::{
callisto::{
push_queue,
sea_orm_active_enums::{PushQueueKindEnum, PushQueueStatusEnum},
},
common::{
errors::{ImportRepoError, MegaError},
utils::{
MEGA_BRANCH_NAME, ZERO_ID, commit_body_subject, format_commit_msg, is_protocol_zero_id,
split_commit_message,
},
},
config::{DEFAULT_MAX_PUSH_COMMITS, PushPolicy},
jupiter::{
service::view_worker::ViewSignal,
storage::{
audit_storage::{AuditStorage, IMPORT_REPO_REMOVE_KIND},
base_storage::{BaseStorage, StorageConnector},
blob_path_index::BlobPathIndexMode,
git_db_storage::GitDbStorage,
mono_storage::MonoStorage,
mst2_publication_storage::{
PreparedPublication, PublicationPreparation, PublicationReceiptError,
PublicationRequest,
},
native_publication_storage::PreparedNativePublication,
push_queue_storage::{
ClaimOutcome, EnqueueOutcome, EnqueueParams, EnqueueRejectReason, PushQueueStorage,
},
},
},
};
/// Default B2 wait budget before the caller abandons (does not cancel the row).
pub const DEFAULT_WAIT_TIMEOUT: Duration = Duration::from_secs(300);
/// Default B2 poll interval.
pub const DEFAULT_POLL_INTERVAL: Duration = Duration::from_millis(200);
/// Stable operation fingerprints (trunk-push.md §1.11).
pub fn push_operation_id(old_id: &str, new_id: &str) -> String {
format!("{old_id}→{new_id}")
}
pub fn merge_operation_id(cl_link: &str) -> String {
cl_link.to_owned()
}
/// Message of the monorepo root commit that mounts an ImportRepo leaf: the
/// imported tip's subject taken from its body, so signature headers of any
/// kind (`gpgsig`, `gpgsig-sha256`, PGP or SSH) never leak (plan-20260923
/// FU-02). Framed with the header/body blank line.
fn attach_root_message(tip_message: &str) -> String {
format_commit_msg(
commit_body_subject(split_commit_message(tip_message).body),
None,
)
}
pub fn attach_operation_id(repo_id: &str, normalized_commands: &str) -> String {
let mut hasher = Sha256::new();
hasher.update(repo_id.as_bytes());
hasher.update(b"\0");
hasher.update(normalized_commands.as_bytes());
hex::encode(hasher.finalize())
}
/// Queue identity of detaching ImportRepo `repo_id` from `canonical_path`
/// (plan-20260923 ADR-FU-09 item 1). The domain prefix keeps it apart from
/// every attach id; a re-import gets a new `repo_id` and so a new id.
pub fn detach_operation_id(repo_id: i64, canonical_path: &str) -> String {
let mut hasher = Sha256::new();
hasher.update(b"import_repo.detach\0");
hasher.update(repo_id.to_string().as_bytes());
hasher.update(b"\0");
hasher.update(canonical_path.as_bytes());
hex::encode(hasher.finalize())
}
/// Deterministic attach command fingerprint input (Branch commands only).
///
/// Fingerprint covers wire intent (ref + tip ids), not derived `default_branch`
/// (smart.rs sets that from repo state and would break identical-retry adopt).
pub fn normalize_attach_commands(cmds: &[(String, String, String, String)]) -> String {
// tuples: (ref_name, command_type, old_id, new_id)
let mut rows: Vec<_> = cmds.to_vec();
rows.sort_by(|a, b| (&a.0, &a.1, &a.2, &a.3).cmp(&(&b.0, &b.1, &b.2, &b.3)));
rows.into_iter()
.map(|(ref_name, ctype, old_id, new_id)| format!("{ref_name}:{ctype}:{old_id}:{new_id}"))
.collect::<Vec<_>>()
.join("\n")
}
/// What an ImportRepo row of the attach queue does (plan-20260923 ADR-FU-09
/// item 1).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum AttachOp {
#[default]
Attach,
Detach,
}
impl AttachOp {
fn is_attach(&self) -> bool {
*self == AttachOp::Attach
}
}
/// Serializable attach payload (trunk-push 1.4 / 1.9).
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
pub struct AttachPayload {
pub repo_id: i64,
pub repo_path: String,
pub commands: Vec<AttachCommand>,
/// Absent from rows written before FU-16, which are all attaches; an
/// attach still serializes without it.
#[serde(default, skip_serializing_if = "AttachOp::is_attach")]
pub op: AttachOp,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
pub struct AttachCommand {
pub ref_name: String,
pub old_id: String,
pub new_id: String,
pub command_type: String,
pub ref_type: String,
#[serde(default)]
pub default_branch: bool,
}
impl AttachPayload {
pub fn normalize_fingerprint_input(&self) -> String {
let rows: Vec<_> = self
.commands
.iter()
.filter(|c| c.ref_type == "branch")
.map(|c| {
(
c.ref_name.clone(),
c.command_type.clone(),
c.old_id.clone(),
c.new_id.clone(),
)
})
.collect();
normalize_attach_commands(&rows)
}
}
/// Apply one push's ImportRepo branch commands inside the B3 transaction with
/// receive-pack CAS (plan-20260923 ADR-FU-08 items 2 and 4): `Create` needs
/// the ref to be absent, `Update` needs it to still point at `old_id`, and
/// `Delete` keeps its lease. The first command that fails its CAS comes back
/// as `IMPORT_REPO_STALE_REF`; the caller rolls the whole batch back, so no
/// branch moves.
pub(crate) async fn apply_import_branch_commands_in_txn(
git_db: &GitDbStorage,
repo_id: i64,
commands: &[AttachCommand],
txn: &DatabaseTransaction,
) -> Result<Result<(), ImportRepoError>, MegaError> {
use crate::{
callisto::sea_orm_active_enums::RefTypeEnum,
ceres::protocol::import_refs::{CommandType, RefCommand},
};
for cmd in commands.iter().filter(|cmd| cmd.ref_type == "branch") {
let command_type = match cmd.command_type.as_str() {
"Create" => CommandType::Create,
"Delete" => CommandType::Delete,
"Update" => CommandType::Update,
other => {
return Err(MegaError::Other(format!(
"unknown attach command_type '{other}'"
)));
}
};
let applied = match command_type {
CommandType::Create => {
let ref_cmd = RefCommand {
ref_name: cmd.ref_name.clone(),
old_id: cmd.old_id.clone(),
new_id: cmd.new_id.clone(),
status: "ok".into(),
error_msg: String::new(),
command_type: CommandType::Create,
ref_type: RefTypeEnum::Branch,
default_branch: cmd.default_branch,
};
git_db
.create_ref_if_absent(repo_id, ref_cmd.into(), txn)
.await?
}
CommandType::Update => {
git_db
.update_ref_if_unchanged(repo_id, &cmd.ref_name, &cmd.old_id, &cmd.new_id, txn)
.await?
}
CommandType::Delete => {
git_db
.remove_ref_if_unchanged(repo_id, &cmd.ref_name, &cmd.old_id, txn)
.await?
}
};
if !applied {
return Ok(Err(ImportRepoError::StaleRef {
ref_name: cmd.ref_name.clone(),
expected: cmd.old_id.clone(),
}));
}
if cmd.default_branch && command_type != CommandType::Delete {
git_db
.set_default_branch_in_txn(repo_id, &cmd.ref_name, txn)
.await?;
}
}
Ok(Ok(()))
}
/// Where an ImportRepo leaf path stands in a monorepo root tree
/// (plan-20260923 ADR-FU-08 item 1).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum ImportLeaf {
Absent,
GitkeepOnly,
Directory,
NotDirectory,
}
async fn import_leaf_in_txn(
mono: &MonoStorage,
root_tree: &str,
path: &str,
txn: &DatabaseTransaction,
) -> Result<ImportLeaf, MegaError> {
use git_internal::internal::object::tree::{Tree, TreeItemMode};
use crate::jupiter::utils::converter::FromMegaModel;
let missing = |hash: &str| MegaError::Other(format!("tree {hash} not found"));
let model = mono
.get_tree_by_hash_in_txn(root_tree, txn)
.await?
.ok_or_else(|| missing(root_tree))?;
let mut tree = Tree::from_mega_model(model);
for component in path.split('/').filter(|c| !c.is_empty()) {
let Some(item) = tree.tree_items.iter().find(|x| x.name == component) else {
return Ok(ImportLeaf::Absent);
};
if item.mode != TreeItemMode::Tree {
return Ok(ImportLeaf::NotDirectory);
}
let hash = item.id.to_string();
let next = mono
.get_tree_by_hash_in_txn(&hash, txn)
.await?
.ok_or_else(|| missing(&hash))?;
tree = Tree::from_mega_model(next);
}
Ok(
if crate::ceres::api_service::tree_ops::is_gitkeep_only(&tree) {
ImportLeaf::GitkeepOnly
} else {
ImportLeaf::Directory
},
)
}
/// Whether ImportRepo `repo_id` has at least one branch ref, without reading
/// them (the legacy-mount rule of plan-20260923 ADR-FU-08 item 1).
async fn has_branch_ref_in_txn(txn: &DatabaseTransaction, repo_id: i64) -> Result<bool, MegaError> {
use sea_orm::{ConnectionTrait, DbBackend, Statement};
let row = txn
.query_one_raw(Statement::from_sql_and_values(
DbBackend::Postgres,
"SELECT EXISTS (SELECT 1 FROM import_refs WHERE repo_id = $1 AND ref_type = 'branch') AS v",
[repo_id.into()],
))
.await?;
Ok(row
.map(|row| row.try_get::<bool>("", "v"))
.transpose()?
.unwrap_or(false))
}
/// Trees from `root_tree` down to the parent of the leaf at `path`, read in
/// the B3 transaction, with the name of each step down.
async fn import_leaf_chain_in_txn(
mono: &MonoStorage,
root_tree: &str,
path: &str,
txn: &DatabaseTransaction,
) -> Result<(Vec<git_internal::internal::object::tree::Tree>, Vec<String>), MegaError> {
use git_internal::internal::object::tree::{Tree, TreeItemMode};
use crate::jupiter::utils::converter::FromMegaModel;
let load = |hash: String| async move {
mono.get_tree_by_hash_in_txn(&hash, txn)
.await?
.map(Tree::from_mega_model)
.ok_or_else(|| MegaError::Other(format!("tree {hash} not found")))
};
let names: Vec<String> = path
.split('/')
.filter(|c| !c.is_empty())
.map(str::to_owned)
.collect();
let (_, down) = names
.split_last()
.ok_or_else(|| MegaError::Other("ImportRepo path has no leaf".into()))?;
let mut chain = Vec::with_capacity(names.len());
let mut tree = load(root_tree.to_owned()).await?;
for name in down {
let next = tree
.tree_items
.iter()
.find(|item| item.name == *name && item.mode == TreeItemMode::Tree)
.map(|item| item.id.to_string())
.ok_or_else(|| MegaError::Other(format!("tree entry {name:?} not found")))?;
chain.push(tree);
tree = load(next).await?;
}
chain.push(tree);
Ok((chain, names))
}
/// Keep exactly one default branch after a batch that deleted the old one
/// (e.g. Delete of the old default + Create of a replacement without a
/// precomputed flag).
async fn ensure_default_branch_in_txn(
git_db: &GitDbStorage,
repo_id: i64,
txn: &DatabaseTransaction,
) -> Result<(), MegaError> {
if !git_db.default_branch_exist_in_txn(repo_id, txn).await?
&& let Some(first) = git_db
.list_branch_refs_in_txn(repo_id, txn)
.await?
.into_iter()
.next()
{
git_db
.set_default_branch_in_txn(repo_id, &first.ref_name, txn)
.await?;
}
Ok(())
}
/// Context required to execute a claimed `kind=attach` round under B3.
pub struct AttachExecContext {
pub storage: crate::jupiter::storage::Storage,
pub git_object_cache: std::sync::Arc<crate::ceres::api_service::cache::GitObjectCache>,
}
/// Serializable merge payload (trunk-push 1.4 / 1.9).
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
pub struct MergePayload {
pub cl_link: String,
pub authz_principal: String,
pub execution_actor: String,
/// When true, B3 re-runs UN-17 (`decide_queue_execution`) like the legacy
/// merge-queue processor. Direct `/merge` leaves this false.
#[serde(default)]
pub apply_queue_execution_decision: bool,
/// Recorded requester for UN-17 (`None` = anonymous / missing).
#[serde(default)]
pub requester: Option<String>,
}
/// Serializable push descriptor (trunk-push 1.3). `n` is the client-baseline
/// first-parent distance `new_id → old_id` and is never recomputed from
/// object-store knownness.
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
pub struct PushPayload {
pub commits: Vec<String>,
pub fork_base: Option<String>,
pub n: u32,
}
impl PushPayload {
pub fn from_chain(
old_id: &str,
new_id: &str,
chain: &crate::ceres::pack::push_chain::PushChain,
) -> Self {
let n = if old_id == new_id {
0
} else {
u32::try_from(chain.ordered_commits.len()).unwrap_or(u32::MAX)
};
Self {
commits: chain
.ordered_commits
.iter()
.map(|c| c.id.to_string())
.collect(),
fork_base: Some(chain.base.clone()),
n,
}
}
pub fn to_json(&self) -> JsonValue {
serde_json::to_value(self).unwrap_or(JsonValue::Null)
}
}
/// Context required to execute a claimed `kind=push` round under B3.
pub struct PushExecContext {
pub storage: crate::jupiter::storage::Storage,
pub git_object_cache: std::sync::Arc<crate::ceres::api_service::cache::GitObjectCache>,
/// Test-only: two-phase sync inside the B3 txn right before
/// `apply_push_in_txn` or the n=0 root CAS (after the baseline read): the executor signals
/// "race window open" on the enter barrier, then blocks on the release
/// barrier until the test's queue-bypassing writer has committed — a
/// deterministic apply-time root CAS miss (WH-03).
pub pre_apply_enter_barrier: Option<std::sync::Arc<tokio::sync::Barrier>>,
/// Test-only: the executor resumes only after this barrier completes.
pub pre_apply_release_barrier: Option<std::sync::Arc<tokio::sync::Barrier>>,
}
struct PushRefBaseline<'a> {
cur_commit: Option<&'a str>,
cur_tree: Option<&'a str>,
root: Option<&'a crate::callisto::mega_refs::Model>,
}
/// Context required to execute a claimed `kind=merge` round under B3.
pub struct MergeExecContext {
pub storage: crate::jupiter::storage::Storage,
pub git_object_cache: std::sync::Arc<crate::ceres::api_service::cache::GitObjectCache>,
/// Test-only: roll back after refs/commits land and before CL status write.
pub abort_before_cl_status: bool,
/// Test-only: hold the B3 lock after apply so a concurrent rebase can race.
pub pause_after_apply: Duration,
/// Test-only: sync point when `pause_after_apply` begins (race window open).
pub pause_after_apply_barrier: Option<std::sync::Arc<tokio::sync::Barrier>>,
}
/// A `refs/heads/main` row whose `ref_tree_hash` does not match `resolve(root, P)`.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StaleMainRef {
pub path: String,
pub last_commit_hash: String,
pub stored_tree_hash: String,
pub resolved_tree_hash: Option<String>,
}
#[derive(Debug, Clone)]
pub struct EnqueueRequest {
pub kind: PushQueueKindEnum,
pub operation_id: String,
pub path: String,
pub old_id: String,
pub new_id: String,
pub requester: Option<String>,
pub payload: JsonValue,
/// For push kind B0: the ref name being updated.
pub ref_name: Option<String>,
/// For push kind B0: whether this is a delete command.
pub is_delete: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum QueueWaitResult {
/// Caller should proceed to B3 (claim already committed).
Ready { id: i64 },
/// Done replay — no execution needed.
Replayed {
id: i64,
landed_commit_id: Option<String>,
},
/// Caller abandoned waiting; row left untouched.
Abandoned { id: i64 },
/// Row reached a terminal reject state while waiting.
Rejected { id: i64, message: String },
}
/// Outcome of B3/B4 execution (after a successful B2.5 claim).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ExecuteOutcome {
Done {
id: i64,
landed_commit_id: String,
/// How many root CAS writes this round performed (must be 1 on success).
root_cas_writes: u32,
},
/// Fencing lost the claim (reaper or other raced); caller may retry.
ClaimLost { id: i64 },
/// Hard-stop observed; row reset to Queued.
HardStopped { id: i64 },
/// Queue-bypass tripwire fired; hard_stopped set and row Failed.
BypassDetected { id: i64 },
/// Conflict requeue completed; follow `successor_id` into B2.
Requeued { id: i64, successor_id: i64 },
/// Non-conflict failure terminalized.
Failed {
id: i64,
failure: String,
message: String,
},
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum CancelQueuedOutcome {
Cancelled,
NotFound,
NotQueued { status: PushQueueStatusEnum },
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, utoipa::ToSchema)]
pub struct QueueSnapshotItem {
pub id: i64,
pub path: String,
pub kind: String,
pub requester: Option<String>,
pub status: String,
pub wait_ms: u64,
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, utoipa::ToSchema)]
pub struct QueueControlSnapshot {
pub paused: bool,
pub hard_stopped: bool,
pub depth: u64,
pub head: Option<QueueSnapshotItem>,
pub running: Option<QueueSnapshotItem>,
pub items: Vec<QueueSnapshotItem>,
}
#[derive(Debug, Clone, PartialEq, serde::Serialize, utoipa::ToSchema)]
pub struct QueueMetricsSnapshot {
pub depth: u64,
pub wait_ms_p50: Option<f64>,
pub wait_ms_p99: Option<f64>,
pub round_ms_p50: Option<f64>,
pub round_ms_p99: Option<f64>,
pub failure_rate: f64,
pub cas_assert_failures: u64,
pub claim_lost: u64,
pub lock_timeout_alarms: u64,
pub tree_hash_assert_failures: u64,
pub inspect_tombstoned: u64,
pub reconcile_tombstoned: u64,
}
fn percentile(xs: &[f64], p: f64) -> Option<f64> {
if xs.is_empty() {
return None;
}
let mut sorted = xs.to_vec();
sorted.sort_by(|a, b| a.partial_cmp(b).unwrap_or(std::cmp::Ordering::Equal));
let idx = ((sorted.len() - 1) as f64 * p).round() as usize;
sorted.get(idx).copied()
}
/// How the B3 kind stub performs its single root write (TP-07/08/12 replace this).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum KindRootWrite {
/// Net-zero same-value CAS (tripwire present; root hashes unchanged).
#[default]
NetZero,
/// Advance root to new tip hashes (tests CAS uniqueness / bypass paths).
Advance,
}
#[derive(Debug, Clone)]
pub struct ExecuteRequest {
pub id: i64,
pub kind_root_write: KindRootWrite,
/// When `kind_root_write = Advance`, the new root tip hashes.
pub advance_commit: Option<String>,
pub advance_tree: Option<String>,
/// Injected delay after claim observation / before taking MONO_WRITE_LOCK
/// (fencing regression).
#[cfg(test)]
pub pre_lock_delay: Duration,
/// Force the B4 Conflict requeue path instead of a successful kind stub.
#[cfg(test)]
pub force_conflict: bool,
/// Force a non-Conflict failure (SystemError) after baseline/hard-stop checks.
#[cfg(test)]
pub force_failure: Option<String>,
/// Force the root CAS tripwire to miss (exercises SAVEPOINT fail-close).
#[cfg(test)]
pub force_cas_miss: bool,
}
impl Default for ExecuteRequest {
fn default() -> Self {
Self {
id: 0,
kind_root_write: KindRootWrite::NetZero,
advance_commit: None,
advance_tree: None,
#[cfg(test)]
pre_lock_delay: Duration::ZERO,
#[cfg(test)]
force_conflict: false,
#[cfg(test)]
force_failure: None,
#[cfg(test)]
force_cas_miss: false,
}
}
}
impl ExecuteRequest {
fn pre_lock_delay(&self) -> Duration {
#[cfg(test)]
{
self.pre_lock_delay
}
#[cfg(not(test))]
{
Duration::ZERO
}
}
fn force_conflict(&self) -> bool {
#[cfg(test)]
{
self.force_conflict
}
#[cfg(not(test))]
{
false
}
}
fn force_failure(&self) -> Option<&str> {
#[cfg(test)]
{
self.force_failure.as_deref()
}
#[cfg(not(test))]
{
None
}
}
fn force_cas_miss(&self) -> bool {
#[cfg(test)]
{
self.force_cas_miss
}
#[cfg(not(test))]
{
false
}
}
}
/// Process-local counters for TP-06 observability (no extra metrics crate).
#[derive(Clone, Default)]
pub struct PushQueueMetrics {
pub cas_assert_failures: Arc<AtomicU64>,
pub claim_lost: Arc<AtomicU64>,
pub lock_timeout_alarms: Arc<AtomicU64>,
pub tree_hash_assert_failures: Arc<AtomicU64>,
pub inspect_tombstoned: Arc<AtomicU64>,
pub reconcile_tombstoned: Arc<AtomicU64>,
}
#[derive(Clone)]
pub struct PushQueueService {
push_queue_storage: PushQueueStorage,
mono_storage: MonoStorage,
push_policy: PushPolicy,
max_push_commits: usize,
wait_timeout: Duration,
poll_interval: Duration,
metrics: PushQueueMetrics,
view_signal: Option<ViewSignal>,
}
impl PushQueueService {
pub fn new(base: BaseStorage, push_policy: PushPolicy) -> Self {
Self {
push_queue_storage: PushQueueStorage::new(base.clone()),
mono_storage: MonoStorage { base },
push_policy,
max_push_commits: DEFAULT_MAX_PUSH_COMMITS,
wait_timeout: DEFAULT_WAIT_TIMEOUT,
poll_interval: DEFAULT_POLL_INTERVAL,
metrics: PushQueueMetrics::default(),
view_signal: None,
}
}
pub fn with_timeouts(mut self, wait_timeout: Duration, poll_interval: Duration) -> Self {
self.wait_timeout = wait_timeout;
self.poll_interval = poll_interval;
self
}
pub(crate) fn with_native_publication(mut self, enabled: bool) -> Self {
self.push_queue_storage = self.push_queue_storage.with_native_publication(enabled);
self
}
pub fn with_max_push_commits(mut self, max_push_commits: usize) -> Self {
self.max_push_commits = max_push_commits;
self
}
pub(crate) fn with_view_signal(mut self, signal: ViewSignal) -> Self {
self.view_signal = Some(signal);
self
}
pub fn push_policy(&self) -> PushPolicy {
self.push_policy.clone()
}
pub fn storage(&self) -> &PushQueueStorage {
&self.push_queue_storage
}
pub(crate) fn mono_storage_for_reaper(
&self,
) -> &crate::jupiter::storage::mono_storage::MonoStorage {
&self.mono_storage
}
/// Deactivate descendant targets missing from the landed tree, on `txn`.
/// The push path stays. No active targets, or a missing tree row, changes nothing.
pub async fn publish_target_paths_in_txn(
&self,
txn: &DatabaseTransaction,
push_path: &str,
landed_tree_id: &str,
) -> Result<Vec<String>, MegaError> {
crate::jupiter::service::trace_target_service::deactivate_descendants_missing_from_tree(
txn,
&self.mono_storage,
push_path,
landed_tree_id,
)
.await
}
pub fn reaper(&self) -> crate::jupiter::service::push_queue_reaper::PushQueueReaper {
crate::jupiter::service::push_queue_reaper::PushQueueReaper::from_service(self.clone())
}
pub fn audit(&self) -> crate::jupiter::service::mono_write_audit::MonoWriteAudit {
crate::jupiter::service::mono_write_audit::MonoWriteAudit::from_service(self.clone())
}
pub fn blob_path_compensator(
&self,
) -> crate::jupiter::storage::blob_path_index::BlobPathCompensator {
crate::jupiter::storage::blob_path_index::BlobPathCompensator::new(
self.mono_storage.clone(),
)
}
/// C-segment (ADR-TP-11): after B3 commit, index `main@path` off the lock.
async fn run_c_segment_index(&self, id: i64, path: &str) {
match self
.mono_storage
.index_blob_paths_c_segment(path, BlobPathIndexMode::Queue { push_id: id })
.await
{
Ok(stats) if stats.skipped => {
tracing::info!(
id,
path,
"C-segment skipped; later same-path Done already indexed"
);
}
Ok(_) => {}
Err(e) => {
tracing::warn!(
id,
path,
error = %e,
"C-segment blob_path index failed; compensator will converge"
);
}
}
if let Some(signal) = &self.view_signal {
signal.notify_worker();
}
}
pub fn metrics(&self) -> &PushQueueMetrics {
&self.metrics
}
fn outcome_claim_lost(&self, id: i64) -> ExecuteOutcome {
self.metrics.claim_lost.fetch_add(1, Ordering::Relaxed);
tracing::info!(event = "push_queue_claim_lost", id, "B3 fencing ClaimLost");
ExecuteOutcome::ClaimLost { id }
}
fn note_cas_assert_failure(&self) {
self.metrics
.cas_assert_failures
.fetch_add(1, Ordering::Relaxed);
tracing::error!(
event = "push_queue_cas_assert_failure",
"root CAS affected 0 rows (should be 0 in production)"
);
}
pub async fn pause(&self) -> Result<(), MegaError> {
self.push_queue_storage
.set_control_flags(Some(true), None, None)
.await
}
pub async fn resume(&self) -> Result<(), MegaError> {
self.push_queue_storage
.set_control_flags(Some(false), None, None)
.await
}
/// Clear `hard_stopped` only. Does not touch `paused`.
pub async fn clear_hard_stop(&self, actor: &str) -> Result<(), MegaError> {
self.push_queue_storage
.set_control_flags(None, Some(false), None)
.await?;
tracing::warn!(
event = "push_queue_clear_hard_stop",
actor = %actor,
"operator cleared queue_control.hard_stopped"
);
Ok(())
}
pub async fn cancel_queued(&self, id: i64) -> Result<CancelQueuedOutcome, MegaError> {
let Some(row) = self.push_queue_storage.get_by_id(id).await? else {
return Ok(CancelQueuedOutcome::NotFound);
};
if row.status != PushQueueStatusEnum::Queued {
return Ok(CancelQueuedOutcome::NotQueued { status: row.status });
}
if self.push_queue_storage.cancel_if_queued(id).await? {
Ok(CancelQueuedOutcome::Cancelled)
} else {
let current = self.push_queue_storage.get_by_id(id).await?;
Ok(CancelQueuedOutcome::NotQueued {
status: current
.map(|r| r.status)
.unwrap_or(PushQueueStatusEnum::Cancelled),
})
}
}
pub async fn control_snapshot(&self) -> Result<QueueControlSnapshot, MegaError> {
let ctrl = self.push_queue_storage.get_control().await?;
let active = self.push_queue_storage.list_active().await?;
let now = chrono::Utc::now().fixed_offset();
let items: Vec<QueueSnapshotItem> = active
.iter()
.map(|row| QueueSnapshotItem {
id: row.id,
path: row.path.clone(),
kind: format!("{:?}", row.kind),
requester: row.requester.clone(),
status: format!("{:?}", row.status),
wait_ms: (now - row.enqueued_at).num_milliseconds().max(0) as u64,
})
.collect();
let head = items.first().cloned();
let running = items.iter().find(|i| i.status == "Running").cloned();
Ok(QueueControlSnapshot {
paused: ctrl.paused,
hard_stopped: ctrl.hard_stopped,
depth: items.len() as u64,
head,
running,
items,
})
}
pub async fn metrics_snapshot(&self) -> Result<QueueMetricsSnapshot, MegaError> {
let queued = self
.push_queue_storage
.count_by_status(PushQueueStatusEnum::Queued)
.await?;
let running = self
.push_queue_storage
.count_by_status(PushQueueStatusEnum::Running)
.await?;
let done = self
.push_queue_storage
.count_by_status(PushQueueStatusEnum::Done)
.await?;
let failed = self
.push_queue_storage
.count_by_status(PushQueueStatusEnum::Failed)
.await?;
let finished = self.push_queue_storage.list_recent_finished(200).await?;
let mut waits: Vec<f64> = finished
.iter()
.filter_map(|r| {
let started = r.started_at?;
Some((started - r.enqueued_at).num_milliseconds().max(0) as f64)
})
.collect();
waits.extend(
self.push_queue_storage
.list_active()
.await?
.into_iter()
.filter(|r| r.status == PushQueueStatusEnum::Queued)
.map(|r| {
(chrono::Utc::now().fixed_offset() - r.enqueued_at)
.num_milliseconds()
.max(0) as f64
}),
);
let rounds: Vec<f64> = finished
.iter()
.filter_map(|r| {
let started = r.started_at?;
let finished_at = r.finished_at?;
Some((finished_at - started).num_milliseconds().max(0) as f64)
})
.collect();
let terminal = done + failed;
let failure_rate = if terminal == 0 {
0.0
} else {
failed as f64 / terminal as f64
};
Ok(QueueMetricsSnapshot {
depth: queued + running,
wait_ms_p50: percentile(&waits, 0.50),
wait_ms_p99: percentile(&waits, 0.99),
round_ms_p50: percentile(&rounds, 0.50),
round_ms_p99: percentile(&rounds, 0.99),
failure_rate,
cas_assert_failures: self.metrics.cas_assert_failures.load(Ordering::Relaxed),
claim_lost: self.metrics.claim_lost.load(Ordering::Relaxed),
lock_timeout_alarms: self.metrics.lock_timeout_alarms.load(Ordering::Relaxed),
tree_hash_assert_failures: self
.metrics
.tree_hash_assert_failures
.load(Ordering::Relaxed),
inspect_tombstoned: self.metrics.inspect_tombstoned.load(Ordering::Relaxed),
reconcile_tombstoned: self.metrics.reconcile_tombstoned.load(Ordering::Relaxed),
})
}
#[cfg(test)]
pub fn mono_storage(&self) -> &MonoStorage {
&self.mono_storage
}
/// B0 early reject for push kind under the configured morphology.
///
/// Optimistic NFF precheck is **telemetry only** (see [`b0_nff_telemetry`]):
/// B0 never rejects on `old_id != tip`. B3 is the sole NFF authority.
pub fn b0_reject_push(&self, req: &EnqueueRequest) -> Result<(), MegaError> {
if req.kind != PushQueueKindEnum::Push {
return Ok(());
}
if self.push_policy == PushPolicy::Review {
return Err(MegaError::Other(
"push_policy=review: push does not enter MonoWriteQueue (CL pipeline only)".into(),
));
}
if req.is_delete || req.new_id == ZERO_ID {
return Err(MegaError::Other(
"trunk push rejects delete commands; remove content via a parent-path commit"
.into(),
));
}
let ref_name = req.ref_name.as_deref().unwrap_or("");
if ref_name != MEGA_BRANCH_NAME {
return Err(MegaError::Other(format!(
"trunk push requires ref_name={MEGA_BRANCH_NAME}, got '{ref_name}'"
)));
}
if req.path == "/" {
return Err(MegaError::Other(
"trunk push rejects path=/ (root path would collapse root CAS with P landing)"
.into(),
));
}