ic-query 0.59.0

Internet Computer query library for CloudEngine, NNS, SNS, ICRC, system canisters, and public network metadata
Documentation
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
use crate::sns::report::source::validate_mainnet_sns_neuron;
use crate::sns::report::tests::{fixtures::*, *};

#[tokio::test(flavor = "current_thread")]
async fn neuron_evidence_is_rejected_at_live_detail_page_and_restored_boundaries() {
    let mut row = fixture_reward_row(1);
    row.disburse_maturity_in_progress = fixture_sns_neuron().detail.disburse_maturity_in_progress;
    let (mint, staking) = row.derived_policy_observations();
    row.maturity_mint_conversion_observed_disabled = mint;
    row.manual_maturity_staking_observed_disabled = staking;
    let valid = build_sns_reward_checkpoint_report_with_source(
        &reward_checkpoint_request("1"),
        &FixtureSnsRewardSource::new(vec![fixture_reward_page(vec![row], None)]),
    )
    .await
    .expect("valid variable evidence");
    let mutations: [fn(&mut SnsRewardCheckpointRow); 8] = [
        |row| row.permissions[0].principal = Some("invalid".to_string()),
        |row| row.permissions[0].principal = Some(ROOT_A.to_uppercase()),
        |row| row.permissions.push(row.permissions[0].clone()),
        |row| {
            let permission = row.permissions[0].permission_types[0].clone();
            row.permissions[0].permission_types.push(permission);
        },
        |row| row.permissions[0].permission_types[0].name = "incorrect".to_string(),
        |row| {
            row.disburse_maturity_in_progress[0]
                .account_to_disburse_to
                .as_mut()
                .unwrap()
                .owner = Some("invalid".to_string());
        },
        |row| {
            row.disburse_maturity_in_progress[0]
                .account_to_disburse_to
                .as_mut()
                .unwrap()
                .subaccount_hex = Some("AB".repeat(32));
        },
        |row| {
            row.disburse_maturity_in_progress[0]
                .account_to_disburse_to
                .as_mut()
                .unwrap()
                .subaccount_hex = Some("ab".to_string());
        },
    ];
    for mutate in mutations {
        let mut restored = valid.clone();
        mutate(&mut restored.rows[0]);
        assert!(validate_sns_reward_checkpoint_report(&restored).is_err());
        assert!(matches!(
            validate_mainnet_sns_reward_neuron_page(&fixture_reward_page(
                restored.rows.clone(),
                None,
            )),
            Err(SnsHostError::InvalidSourceData {
                capability: "SNS reward checkpoint",
                ..
            })
        ));
        let row = &restored.rows[0];
        let mut neuron = fixture_sns_neuron();
        neuron.detail.permissions = row.permissions.clone();
        neuron.detail.disburse_maturity_in_progress = row.disburse_maturity_in_progress.clone();
        let (mint, staking) = neuron.detail.derived_policy_observations();
        neuron.detail.maturity_mint_conversion_observed_disabled = mint;
        neuron.detail.manual_maturity_staking_observed_disabled = staking;
        assert!(matches!(
            validate_mainnet_sns_neuron(&neuron, &neuron.detail.neuron.neuron_id),
            Err(SnsHostError::InvalidSourceData {
                capability: "SNS neuron detail",
                ..
            })
        ));
    }
}

#[tokio::test(flavor = "current_thread")]
async fn checkpoint_retains_unassessable_permission_evidence_while_detail_requires_principals() {
    let mut row = fixture_reward_row(1);
    row.permissions[0].permission_types = [0, 11, -1]
        .map(SnsNeuronPermissionValue::from_code)
        .to_vec();
    row.permissions[0].principal = None;
    let (mint, staking) = row.derived_policy_observations();
    row.maturity_mint_conversion_observed_disabled = mint;
    row.manual_maturity_staking_observed_disabled = staking;
    let report = build_sns_reward_checkpoint_report_with_source(
        &reward_checkpoint_request("1"),
        &FixtureSnsRewardSource::new(vec![fixture_reward_page(vec![row], None)]),
    )
    .await
    .expect("checkpoint preserves incomplete and unknown evidence");
    validate_sns_reward_checkpoint_report(&report).expect("restored evidence remains valid");
    assert_eq!(
        report.maturity_conversion_policy_observed_status,
        SnsPolicyObservationStatus::Unassessable,
    );
    let mut neuron = fixture_sns_neuron();
    neuron.detail.permissions = report.rows[0].permissions.clone();
    assert!(matches!(
        validate_mainnet_sns_neuron(&neuron, &neuron.detail.neuron.neuron_id),
        Err(SnsHostError::InvalidSourceData { reason, .. })
            if reason.contains("principal is missing")
    ));
    neuron.detail.permissions[0].principal = Some(ROOT_A.to_string());
    let (mint, staking) = neuron.detail.derived_policy_observations();
    neuron.detail.maturity_mint_conversion_observed_disabled = mint;
    neuron.detail.manual_maturity_staking_observed_disabled = staking;
    validate_mainnet_sns_neuron(&neuron, &neuron.detail.neuron.neuron_id)
        .expect("detail preserves unknown permission codes with canonical labels");
}

#[tokio::test(flavor = "current_thread")]
async fn reward_checkpoint_collects_stable_brackets_and_exhausted_rows_in_order() {
    let source = FixtureSnsRewardSource::new(vec![fixture_reward_page(
        vec![fixture_reward_row(1), fixture_reward_row(2)],
        None,
    )]);
    let report =
        build_sns_reward_checkpoint_report_with_source(&reward_checkpoint_request("1"), &source)
            .await
            .expect("stable checkpoint");
    let text = sns_reward_checkpoint_report_text(&report);

    assert_eq!(
        source.calls(),
        [
            "version",
            "parameters",
            "event",
            "page",
            "event",
            "parameters",
            "version",
        ]
    );
    assert_eq!(report.page_count, 1);
    assert_eq!(report.row_count, 2);
    assert_eq!(report.unique_neuron_id_count, 2);
    assert_eq!(report.client_query_count, 9);
    assert_eq!(report.aggregate_maturity_e8s_equivalent, 300);
    assert_eq!(report.aggregate_staked_maturity_e8s_equivalent, 30);
    assert_eq!(report.aggregate_combined_maturity_e8s_equivalent, 330);
    assert_eq!(
        report.collection_status,
        SnsRewardCollectionStatus::ApiExhaustedObserved
    );
    assert!(!report.point_in_time_guaranteed);
    assert_eq!(
        report.maturity_conversion_policy_observed_status,
        SnsPolicyObservationStatus::ObservedSatisfied
    );
    assert!(text.contains("collection_status: api_exhausted_observed"));
    assert!(text.contains("row_count: 2"));
    assert!(!text.contains(&report.rows[0].neuron_id));
}

#[tokio::test(flavor = "current_thread")]
async fn reward_checkpoint_rejects_invalid_request_before_source_access() {
    let source = FixtureSnsRewardSource::new(vec![fixture_reward_page(Vec::new(), None)]);
    let mut request = reward_checkpoint_request("1");
    request.lookup.network = "local".to_string();
    assert!(matches!(
        build_sns_reward_checkpoint_report_with_source(&request, &source).await,
        Err(SnsHostError::UnsupportedNetwork { network }) if network == "local"
    ));
    assert_eq!(source.calls(), Vec::<&str>::new());

    let source = FixtureSnsRewardSource::new(vec![fixture_reward_page(Vec::new(), None)]);
    let request = reward_checkpoint_request("1").with_max_pages(Some(0));
    assert!(matches!(
        build_sns_reward_checkpoint_report_with_source(&request, &source).await,
        Err(SnsHostError::InvalidRewardCheckpointPageCap { max_pages: 0 })
    ));
    assert_eq!(source.calls(), Vec::<&str>::new());
}

#[tokio::test(flavor = "current_thread")]
async fn live_reward_source_rejects_non_mainnet_before_agent_construction() {
    let request = SnsSourceRequest::new(
        "local",
        "not a valid endpoint",
        "2026-08-03T00:00:00Z",
        "test",
    );
    let sns = fixture_sns_a();

    let errors = [
        LiveSnsSource::default()
            .fetch_sns_reward_running_version(&request, &sns)
            .await
            .expect_err("running-version source must reject non-mainnet"),
        LiveSnsSource::default()
            .fetch_sns_reward_parameters(&request, &sns)
            .await
            .expect_err("parameter source must reject non-mainnet"),
        LiveSnsSource::default()
            .fetch_sns_reward_event(&request, &sns)
            .await
            .expect_err("reward-event source must reject non-mainnet"),
        LiveSnsSource::default()
            .fetch_sns_reward_neuron_page(&request, &sns, SNS_REWARD_CHECKPOINT_PAGE_SIZE, None)
            .await
            .expect_err("neuron-page source must reject non-mainnet"),
    ];

    assert!(errors.into_iter().all(|error| matches!(
        error,
        SnsHostError::UnsupportedNetwork { network } if network == "local"
    )));
}

#[tokio::test(flavor = "current_thread")]
async fn reward_checkpoint_rejects_any_changed_complete_bracket() {
    for (component, expected) in [
        ("parameters", "nervous-system parameters"),
        ("event", "reward event"),
        ("version", "running SNS version"),
    ] {
        let source = FixtureSnsRewardSource::unstable(
            vec![fixture_reward_page(vec![fixture_reward_row(1)], None)],
            component,
        );
        assert!(matches!(
            build_sns_reward_checkpoint_report_with_source(
                &reward_checkpoint_request("1"),
                &source,
            ).await,
            Err(SnsHostError::UnstableRewardCheckpoint { component }) if component == expected
        ));
    }
}

#[test]
fn reward_checkpoint_rejects_overlap_and_noncanonical_cursor_evidence() {
    let mut full_rows = (1..=100).map(fixture_reward_row).collect::<Vec<_>>();
    let final_cursor = SnsNeuronId { id: vec![100; 32] };
    let mut state = SnsRewardCollectionState::new();
    assert!(!state.exhausted());
    state
        .ingest_page(fixture_reward_page(full_rows.clone(), Some(final_cursor)))
        .expect("first full page");
    assert!(!state.exhausted());
    assert!(matches!(
        state.ingest_page(fixture_reward_page(
            vec![fixture_reward_row(100)],
            None,
        )),
        Err(SnsHostError::InvalidSourceData {
            capability: "SNS reward checkpoint",
            reason,
        }) if reason.contains("does not increase")
    ));
    assert_eq!(state.page_count(), 1);
    assert_eq!(state.row_count(), 100);
    assert_eq!(
        state.next_cursor().expect("full-page cursor").id,
        vec![100; 32]
    );
    assert!(!state.exhausted());
    state
        .ingest_page(fixture_reward_page(Vec::new(), None))
        .expect("empty terminal page after a rejected page");
    assert_eq!(state.page_count(), 2);
    assert_eq!(state.row_count(), 100);
    assert!(state.next_cursor().is_none());
    assert!(state.exhausted());

    let short_with_cursor = fixture_reward_page(
        vec![fixture_reward_row(1)],
        Some(SnsNeuronId { id: vec![1; 32] }),
    );
    assert!(matches!(
        validate_mainnet_sns_reward_neuron_page(&short_with_cursor),
        Err(SnsHostError::InvalidSourceData { reason, .. })
            if reason.contains("must not advertise a cursor")
    ));

    full_rows[99].neuron_id = "ff".repeat(32);
    let wrong_cursor = fixture_reward_page(full_rows, Some(SnsNeuronId { id: vec![100; 32] }));
    assert!(matches!(
        validate_mainnet_sns_reward_neuron_page(&wrong_cursor),
        Err(SnsHostError::InvalidSourceData { reason, .. })
            if reason.contains("does not equal final neuron id")
    ));
}

#[tokio::test(flavor = "current_thread")]
async fn reward_checkpoint_rejects_diagnostic_cap_before_exhaustion() {
    let rows = (1..=100).map(fixture_reward_row).collect::<Vec<_>>();
    let source = FixtureSnsRewardSource::new(vec![
        fixture_reward_page(rows, Some(SnsNeuronId { id: vec![100; 32] })),
        fixture_reward_page(Vec::new(), None),
    ]);
    let request = reward_checkpoint_request("1").with_max_pages(Some(1));

    assert!(matches!(
        build_sns_reward_checkpoint_report_with_source(&request, &source).await,
        Err(SnsHostError::IncompleteRewardCheckpoint {
            pages_fetched: 1,
            rows_fetched: 100,
            reason,
        }) if reason.contains("diagnostic max_pages 1")
    ));
}

#[tokio::test(flavor = "current_thread")]
async fn reward_checkpoint_enforces_parameter_derived_collection_ceiling() {
    for ceiling in [None, Some(0), Some(200_001)] {
        let source = FixtureSnsRewardSource::new(vec![fixture_reward_page(Vec::new(), None)])
            .with_max_number_of_neurons(ceiling);
        assert!(matches!(
            build_sns_reward_checkpoint_report_with_source(
                &reward_checkpoint_request("1"),
                &source,
            ).await,
            Err(SnsHostError::InvalidRewardCheckpointCeiling { value, maximum: 200_000 })
                if value == ceiling
        ));
    }

    let source = FixtureSnsRewardSource::new(vec![fixture_reward_page(
        vec![fixture_reward_row(1), fixture_reward_row(2)],
        None,
    )])
    .with_max_number_of_neurons(Some(1));
    assert!(matches!(
        build_sns_reward_checkpoint_report_with_source(&reward_checkpoint_request("1"), &source).await,
        Err(SnsHostError::InvalidSourceData { reason, .. })
            if reason.contains("above mandatory ceiling 1")
    ));
}

#[test]
fn reward_checkpoint_collection_rejects_rows_after_exhaustion() {
    for rows in [Vec::new(), vec![fixture_reward_row(1)]] {
        let row_count = rows.len();
        let mut state = SnsRewardCollectionState::new();
        assert!(!state.exhausted());
        state
            .ingest_page(fixture_reward_page(rows, None))
            .expect("short or empty first page exhausts the API");
        assert!(state.exhausted());
        assert!(matches!(
            state.ingest_page(fixture_reward_page(Vec::new(), None)),
            Err(SnsHostError::InvalidSourceData { reason, .. })
                if reason.contains("after reported API exhaustion")
        ));
        assert_eq!(state.page_count(), 1);
        assert_eq!(state.row_count(), row_count);
        assert!(state.exhausted());
    }
}

#[test]
fn reward_row_policy_fails_closed_but_preserves_known_violations() {
    let mut row = fixture_reward_row(1);
    row.permissions[0].principal = None;
    row.permissions[0]
        .permission_types
        .push(SnsNeuronPermissionValue::from_code(11));
    let observations = row.derived_policy_observations();
    assert_eq!(
        observations,
        (
            SnsPolicyObservationStatus::Unassessable,
            SnsPolicyObservationStatus::Unassessable,
        )
    );

    row.permissions[0]
        .permission_types
        .push(SnsNeuronPermissionValue::from_code(7));
    row.maturity_mint_conversion_observed_disabled = SnsPolicyObservationStatus::Violated;
    row.manual_maturity_staking_observed_disabled = SnsPolicyObservationStatus::Unassessable;
    assert_eq!(
        row.derived_policy_observations().0,
        SnsPolicyObservationStatus::Violated
    );
}

#[tokio::test(flavor = "current_thread")]
async fn checkpoint_files_preserve_reports_and_refuse_unbounded_or_invalid_inputs() {
    let root = crate::test_support::temp_dir("ic-query-reward-checkpoint-files");
    let path = root.join("checkpoint.json");
    let report = build_sns_reward_checkpoint_report_with_source(
        &reward_checkpoint_request("1"),
        &FixtureSnsRewardSource::new(vec![fixture_reward_page(vec![fixture_reward_row(1)], None)]),
    )
    .await
    .expect("valid checkpoint");
    let bytes = serde_json::to_vec(&report).unwrap();
    std::fs::write(&path, &bytes).unwrap();
    assert_eq!(load_sns_reward_checkpoint(&path).unwrap(), report);
    let file = std::fs::OpenOptions::new().write(true).open(&path).unwrap();
    file.set_len(64 * 1024 * 1024 + 1).unwrap();
    let error = load_sns_reward_checkpoint(&path).unwrap_err();
    assert!(
        matches!(error, SnsHostError::ReadRewardCheckpoint { path: failed, source }
        if failed == path && matches!(source.get_ref().and_then(|cause|
            cause.downcast_ref::<ic_host_artifacts::artifact::ArtifactError>()),
            Some(ic_host_artifacts::artifact::ArtifactError::LimitExceeded { limit })
                if *limit == 64 * 1024 * 1024))
    );
    assert_eq!(
        std::fs::metadata(&path).unwrap().len(),
        64 * 1024 * 1024 + 1
    );
    for invalid in [b"{".as_slice(), &[0xff][..]] {
        std::fs::write(&path, invalid).unwrap();
        assert!(matches!(load_sns_reward_checkpoint(&path),
            Err(SnsHostError::ParseRewardCheckpoint { path: failed, .. }) if failed == path));
    }
    assert!(matches!(load_sns_reward_checkpoint(&root),
        Err(SnsHostError::ReadRewardCheckpoint { path: failed, .. }) if failed == root));
    let missing = root.join("missing.json");
    assert!(matches!(load_sns_reward_checkpoint(&missing),
        Err(SnsHostError::ReadRewardCheckpoint { path: failed, source })
            if failed == missing && source.kind() == std::io::ErrorKind::NotFound));
    std::fs::remove_dir_all(root).unwrap();
}