Skip to main content

ic_query/nns/neuron/report/
collection.rs

1//! Module: nns::neuron::report::collection
2//!
3//! Responsibility: advance caller-persisted complete public-neuron walks one page at a time.
4//! Does not own: stable memory, filesystem caches, scheduling, retries, or publication.
5//! Boundary: validates resumable input and derives the next state from one admitted source page.
6
7#[cfg(feature = "nns-host")]
8use super::NnsNeuronHostError;
9use super::{
10    NnsNeuronError,
11    model::{NnsNeuronListReport, NnsNeuronListRequest},
12    source::{NnsNeuronSource, build_nns_neuron_list_report_with_source, validate_page_size},
13};
14use crate::nns::{
15    MAINNET_GOVERNANCE_CANISTER_ID,
16    governance::{
17        NnsGovernanceCollectionStatus, NnsGovernanceRequest, NnsGovernanceSourceProvenance,
18        NnsGovernanceSourceSelection, validate_governance_request,
19        validate_governance_time_interval, validate_source_provenance,
20    },
21};
22#[cfg(feature = "nns-host")]
23use crate::{nns::LiveNnsSource, runtime::block_on_current_thread};
24use serde::{Deserialize, Serialize};
25
26/// Version of the persistable resumable NNS neuron collection state.
27pub const NNS_NEURON_COLLECTION_STATE_SCHEMA_VERSION: u32 = 1;
28
29///
30/// NnsNeuronCollectionState
31///
32/// Serializable continuation state for an explicitly bounded public-neuron walk.
33///
34
35#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
36pub struct NnsNeuronCollectionState {
37    schema_version: u32,
38    network: String,
39    governance_canister_id: String,
40    requested_source: NnsGovernanceSourceSelection,
41    source: Option<NnsGovernanceSourceProvenance>,
42    page_size: u32,
43    max_pages: u32,
44    pages_fetched: u32,
45    neurons_fetched: u64,
46    next_start_neuron_id: Option<u64>,
47    started_at: String,
48    updated_at: String,
49    status: NnsGovernanceCollectionStatus,
50}
51
52impl NnsNeuronCollectionState {
53    /// Start an empty neuron walk with explicit per-page and cumulative call ceilings.
54    pub fn new(
55        request: &NnsGovernanceRequest,
56        page_size: u32,
57        max_pages: u32,
58    ) -> Result<Self, NnsNeuronError> {
59        validate_governance_request(request)?;
60        validate_page_size(page_size)?;
61        if max_pages == 0 {
62            return Err(NnsNeuronError::InvalidCollectionMaxPages);
63        }
64        Ok(Self {
65            schema_version: NNS_NEURON_COLLECTION_STATE_SCHEMA_VERSION,
66            network: request.network.clone(),
67            governance_canister_id: MAINNET_GOVERNANCE_CANISTER_ID.to_string(),
68            requested_source: request.source.clone(),
69            source: None,
70            page_size,
71            max_pages,
72            pages_fetched: 0,
73            neurons_fetched: 0,
74            next_start_neuron_id: None,
75            started_at: request.fetched_at.clone(),
76            updated_at: request.fetched_at.clone(),
77            status: NnsGovernanceCollectionStatus::Ready,
78        })
79    }
80
81    /// Return the state schema version.
82    #[must_use]
83    pub const fn schema_version(&self) -> u32 {
84        self.schema_version
85    }
86
87    /// Return the fixed network identity.
88    #[must_use]
89    pub fn network(&self) -> &str {
90        &self.network
91    }
92
93    /// Return the fixed Governance canister identity.
94    #[must_use]
95    pub fn governance_canister_id(&self) -> &str {
96        &self.governance_canister_id
97    }
98
99    /// Return the source selection fixed when collection started.
100    #[must_use]
101    pub const fn requested_source(&self) -> &NnsGovernanceSourceSelection {
102        &self.requested_source
103    }
104
105    /// Return the concrete source provenance after the first admitted page.
106    #[must_use]
107    pub const fn source(&self) -> Option<&NnsGovernanceSourceProvenance> {
108        self.source.as_ref()
109    }
110
111    /// Return the maximum rows requested from each Governance call.
112    #[must_use]
113    pub const fn page_size(&self) -> u32 {
114        self.page_size
115    }
116
117    /// Return the cumulative source-call ceiling.
118    #[must_use]
119    pub const fn max_pages(&self) -> u32 {
120        self.max_pages
121    }
122
123    /// Return the number of successfully admitted pages.
124    #[must_use]
125    pub const fn pages_fetched(&self) -> u32 {
126        self.pages_fetched
127    }
128
129    /// Return the number of successfully admitted neuron rows.
130    #[must_use]
131    pub const fn neurons_fetched(&self) -> u64 {
132        self.neurons_fetched
133    }
134
135    /// Return the exclusive lower neuron-id bound for the next page.
136    #[must_use]
137    pub const fn next_start_neuron_id(&self) -> Option<u64> {
138        self.next_start_neuron_id
139    }
140
141    /// Return the caller-supplied time at which the collection state was created.
142    #[must_use]
143    pub fn started_at(&self) -> &str {
144        &self.started_at
145    }
146
147    /// Return the caller-supplied time attached to the latest admitted page.
148    #[must_use]
149    pub fn updated_at(&self) -> &str {
150        &self.updated_at
151    }
152
153    /// Return the collection lifecycle status.
154    #[must_use]
155    pub const fn status(&self) -> NnsGovernanceCollectionStatus {
156        self.status
157    }
158
159    /// Return whether Governance API exhaustion was observed.
160    #[must_use]
161    pub const fn is_complete(&self) -> bool {
162        matches!(self.status, NnsGovernanceCollectionStatus::Complete)
163    }
164}
165
166///
167/// NnsNeuronCollectionStep
168///
169/// One admitted bounded page and the continuation state that follows it.
170///
171
172#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
173pub struct NnsNeuronCollectionStep {
174    /// Page returned by the shared public-neuron report builder.
175    pub page: NnsNeuronListReport,
176    /// Validated state to persist only after retaining the page.
177    pub state: NnsNeuronCollectionState,
178}
179
180/// Advance a resumable public-neuron walk through the native replica adapter.
181#[cfg(feature = "nns-host")]
182pub fn advance_nns_neuron_collection(
183    request: &NnsGovernanceRequest,
184    state: &NnsNeuronCollectionState,
185) -> Result<NnsNeuronCollectionStep, NnsNeuronHostError> {
186    Ok(block_on_current_thread(
187        advance_nns_neuron_collection_with_source(request, state, &LiveNnsSource),
188    )??)
189}
190
191/// Advance a resumable public-neuron walk by exactly one caller-runtime source call.
192pub async fn advance_nns_neuron_collection_with_source(
193    request: &NnsGovernanceRequest,
194    state: &NnsNeuronCollectionState,
195    source: &dyn NnsNeuronSource,
196) -> Result<NnsNeuronCollectionStep, NnsNeuronError> {
197    validate_governance_request(request)?;
198    validate_collection_state(state)?;
199    validate_continuation_request(request, state)?;
200    validate_governance_time_interval(
201        "updated_at",
202        &state.updated_at,
203        "fetched_at",
204        &request.fetched_at,
205    )?;
206    match state.status {
207        NnsGovernanceCollectionStatus::Complete => {
208            return Err(NnsNeuronError::CollectionComplete {
209                pages_fetched: state.pages_fetched,
210            });
211        }
212        NnsGovernanceCollectionStatus::PageLimitReached => {
213            return Err(NnsNeuronError::CollectionPageLimitReached {
214                pages_fetched: state.pages_fetched,
215                max_pages: state.max_pages,
216            });
217        }
218        NnsGovernanceCollectionStatus::Ready | NnsGovernanceCollectionStatus::Collecting => {}
219    }
220
221    let mut page_request = NnsNeuronListRequest::new(request.clone(), state.page_size);
222    page_request.exclusive_start_neuron_id = state.next_start_neuron_id;
223    let page = build_nns_neuron_list_report_with_source(&page_request, source).await?;
224    if let Some(expected) = &state.source
225        && *expected != page.context.source
226    {
227        return Err(NnsNeuronError::CollectionSourceChanged {
228            expected: expected.clone(),
229            actual: page.context.source,
230        });
231    }
232
233    let pages_fetched = state
234        .pages_fetched
235        .checked_add(1)
236        .ok_or(NnsNeuronError::CollectionAccountingOverflow)?;
237    let page_row_count = u64::try_from(page.returned_neuron_count)
238        .map_err(|_| NnsNeuronError::CollectionAccountingOverflow)?;
239    let neurons_fetched = state
240        .neurons_fetched
241        .checked_add(page_row_count)
242        .ok_or(NnsNeuronError::CollectionAccountingOverflow)?;
243    let next_start_neuron_id = page.next_start_neuron_id;
244    let status = if next_start_neuron_id.is_none() {
245        NnsGovernanceCollectionStatus::Complete
246    } else if pages_fetched == state.max_pages {
247        NnsGovernanceCollectionStatus::PageLimitReached
248    } else {
249        NnsGovernanceCollectionStatus::Collecting
250    };
251    let next_state = NnsNeuronCollectionState {
252        source: Some(page.context.source.clone()),
253        pages_fetched,
254        neurons_fetched,
255        next_start_neuron_id,
256        updated_at: request.fetched_at.clone(),
257        status,
258        ..state.clone()
259    };
260    Ok(NnsNeuronCollectionStep {
261        page,
262        state: next_state,
263    })
264}
265
266fn validate_continuation_request(
267    request: &NnsGovernanceRequest,
268    state: &NnsNeuronCollectionState,
269) -> Result<(), NnsNeuronError> {
270    if request.network != state.network {
271        return Err(NnsNeuronError::CollectionRequestMismatch {
272            field: "network",
273            expected: state.network.clone(),
274            actual: request.network.clone(),
275        });
276    }
277    if request.source != state.requested_source {
278        return Err(NnsNeuronError::CollectionRequestMismatch {
279            field: "requested_source",
280            expected: format!("{:?}", state.requested_source),
281            actual: format!("{:?}", request.source),
282        });
283    }
284    Ok(())
285}
286
287pub(super) fn validate_collection_state(
288    state: &NnsNeuronCollectionState,
289) -> Result<(), NnsNeuronError> {
290    let invalid = |reason| NnsNeuronError::InvalidCollectionState { reason };
291    if state.schema_version != NNS_NEURON_COLLECTION_STATE_SCHEMA_VERSION {
292        return Err(invalid(format!(
293            "schema_version is {}, expected {NNS_NEURON_COLLECTION_STATE_SCHEMA_VERSION}",
294            state.schema_version
295        )));
296    }
297    if state.governance_canister_id != MAINNET_GOVERNANCE_CANISTER_ID {
298        return Err(invalid(format!(
299            "governance_canister_id is {}, expected {MAINNET_GOVERNANCE_CANISTER_ID}",
300            state.governance_canister_id
301        )));
302    }
303    let state_request = NnsGovernanceRequest {
304        network: state.network.clone(),
305        fetched_at: state.started_at.clone(),
306        source: state.requested_source.clone(),
307    };
308    validate_governance_request(&state_request)?;
309    validate_governance_time_interval(
310        "started_at",
311        &state.started_at,
312        "updated_at",
313        &state.updated_at,
314    )?;
315    validate_page_size(state.page_size)?;
316    if state.max_pages == 0 {
317        return Err(invalid("max_pages must be greater than zero".to_string()));
318    }
319    if state.pages_fetched > state.max_pages {
320        return Err(invalid(format!(
321            "pages_fetched {} exceeds max_pages {}",
322            state.pages_fetched, state.max_pages
323        )));
324    }
325    if let Some(source) = &state.source {
326        validate_source_provenance(&state.requested_source, source)?;
327    }
328
329    let page_size = u64::from(state.page_size);
330    let pages_fetched = u64::from(state.pages_fetched);
331    let neurons_fetched = state.neurons_fetched;
332    // Both operands originate as u32, so their product fits in u64.
333    let maximum_rows = pages_fetched * page_size;
334    let minimum_rows = pages_fetched.saturating_sub(1) * page_size;
335    if neurons_fetched < minimum_rows || neurons_fetched > maximum_rows {
336        return Err(invalid(format!(
337            "neurons_fetched {} is outside {}..={} for {} pages of size {}",
338            state.neurons_fetched, minimum_rows, maximum_rows, state.pages_fetched, state.page_size
339        )));
340    }
341
342    let valid_lifecycle = match state.status {
343        NnsGovernanceCollectionStatus::Ready => {
344            state.pages_fetched == 0
345                && state.neurons_fetched == 0
346                && state.next_start_neuron_id.is_none()
347                && state.source.is_none()
348        }
349        NnsGovernanceCollectionStatus::Collecting => {
350            state.pages_fetched > 0
351                && state.pages_fetched < state.max_pages
352                && neurons_fetched == maximum_rows
353                && state.next_start_neuron_id.is_some()
354                && state.source.is_some()
355        }
356        NnsGovernanceCollectionStatus::Complete => {
357            state.pages_fetched > 0
358                && neurons_fetched < maximum_rows
359                && state.next_start_neuron_id.is_none()
360                && state.source.is_some()
361        }
362        NnsGovernanceCollectionStatus::PageLimitReached => {
363            state.pages_fetched == state.max_pages
364                && neurons_fetched == maximum_rows
365                && state.next_start_neuron_id.is_some()
366                && state.source.is_some()
367        }
368    };
369    if !valid_lifecycle {
370        return Err(invalid(format!(
371            "status {} disagrees with cursor, provenance, or counters",
372            state.status
373        )));
374    }
375    Ok(())
376}
377
378#[cfg(test)]
379mod tests {
380    use super::*;
381    use crate::nns::governance::NnsGovernanceError;
382
383    struct UnexpectedSource;
384    impl NnsNeuronSource for UnexpectedSource {
385        fn fetch_neuron_page<'a>(
386            &'a self,
387            _: &'a NnsGovernanceRequest,
388            _: Option<u64>,
389            _: u32,
390        ) -> crate::nns::neuron::NnsNeuronSourceFuture<'a, crate::nns::neuron::NnsNeuronPage>
391        {
392            panic!("unexpected source call")
393        }
394        fn fetch_neuron<'a>(
395            &'a self,
396            _: &'a NnsGovernanceRequest,
397            _: u64,
398        ) -> crate::nns::neuron::NnsNeuronSourceFuture<'a, crate::nns::neuron::NnsNeuronRow>
399        {
400            panic!("unexpected source call")
401        }
402    }
403
404    #[test]
405    fn collection_rejects_backward_continuations_and_restored_intervals() {
406        let start = NnsGovernanceRequest::replicated_inter_canister_call_from_unix_secs("ic", 100);
407        let state = NnsNeuronCollectionState::new(&start, 2, 3).unwrap();
408        let before = NnsGovernanceRequest::replicated_inter_canister_call_from_unix_secs("ic", 99);
409        let mut future = std::pin::pin!(advance_nns_neuron_collection_with_source(
410            &before,
411            &state,
412            &UnexpectedSource
413        ));
414        let mut context = std::task::Context::from_waker(std::task::Waker::noop());
415        let result = std::future::Future::poll(future.as_mut(), &mut context);
416        assert!(matches!(
417            result,
418            std::task::Poll::Ready(Err(NnsNeuronError::Governance(
419                NnsGovernanceError::InvalidTimestampOrder { .. }
420            )))
421        ));
422        let mut value = serde_json::to_value(&state).unwrap();
423        value["updated_at"] = serde_json::json!(before.fetched_at);
424        let restored = serde_json::from_value(value).unwrap();
425        assert!(matches!(
426            validate_collection_state(&restored),
427            Err(NnsNeuronError::Governance(
428                NnsGovernanceError::InvalidTimestampOrder { .. }
429            ))
430        ));
431        assert!(
432            validate_governance_time_interval(
433                "updated_at",
434                &state.updated_at,
435                "fetched_at",
436                &start.fetched_at
437            )
438            .is_ok()
439        );
440    }
441
442    #[test]
443    fn collection_validates_request_and_restored_timestamps() {
444        let mut request = NnsGovernanceRequest::replicated_inter_canister_call_from_unix_secs(
445            "ic",
446            1_700_000_000,
447        );
448        let valid_state = NnsNeuronCollectionState::new(&request, 2, 3).expect("valid state");
449        for timestamp in ["not a UTC timestamp", "+2023-11-14T22:13:20Z"] {
450            request.fetched_at = timestamp.to_string();
451            assert!(matches!(
452                NnsNeuronCollectionState::new(&request, 2, 3),
453                Err(NnsNeuronError::Governance(
454                    NnsGovernanceError::InvalidTimestamp {
455                        field: "fetched_at",
456                        ..
457                    }
458                ))
459            ));
460            for field in ["started_at", "updated_at"] {
461                let mut value = serde_json::to_value(&valid_state).expect("serialize state");
462                value[field] = serde_json::json!(timestamp);
463                let state = serde_json::from_value(value).expect("restore caller state");
464                assert!(matches!(
465                    validate_collection_state(&state),
466                    Err(NnsNeuronError::Governance(
467                        NnsGovernanceError::InvalidTimestamp { value, .. }
468                    )) if value == timestamp
469                ));
470            }
471        }
472    }
473}