Portals0.7.0 · dev (544a5c68c72e · 2026-11-28 UTC)
Loading...
Searching...
No Matches
model_query.hpp
1// Copyright (c) 2026 ttldtor.
2// SPDX-License-Identifier: BSL-1.0
3#pragma once
4
5#include <portals/model.hpp>
6
7#include <concepts>
8#include <tuple>
9
10namespace portals {
21
24 std::size_t maxInFlight{4};
25 std::size_t maxOutputRows{256};
26 std::size_t maxSourceRows{65536};
27 std::size_t maxComparisons{1048576};
28};
29
36template <class T, class Q> struct Query {
37 std::shared_ptr<const ModelSnapshot<T>> source;
39 RowRange page{0, 256};
40};
41
45template <class T> struct QueryPage {
46 std::shared_ptr<const ModelSnapshot<T>> snapshot;
47 std::uint64_t totalRows{};
48};
49
51namespace detail {
52struct QueryEvaluationAbort {
53 QueryError error;
54};
55
56inline TreeError queryTreeError(SchedulerError error) noexcept {
57 switch (error) {
59 return TreeError::CLOSED;
66 default:
68 }
69}
70
71inline bool validQueryOptions(QueryOptions options) noexcept {
72 return options.maxInFlight && options.maxOutputRows && options.maxSourceRows && options.maxComparisons;
73}
74
75template <class T> struct LocalQueryRows final : ModelSnapshot<T> {
76 LocalQueryRows(std::shared_ptr<const ModelSnapshot<T>> original, std::vector<ModelRow<T>> value)
77 : ModelSnapshot<T>(original->revision(), value.size()), source(std::move(original)), rows(std::move(value)) {
78 identities.reserve(rows.size());
79
80 for (std::size_t index = 0; index < rows.size(); ++index) {
81 identities.emplace_back(rows[index].id, index);
82 }
83
84 std::ranges::sort(identities, [](const auto &left, const auto &right) {
85 return std::tie(left.first.value, left.first.generation) < std::tie(right.first.value, right.first.generation);
86 });
87 }
88
89 ModelRows<T> read(RowRange range) const override {
90 return {RangeState::READY, std::span(rows).subspan(static_cast<std::size_t>(range.first), range.count), {}};
91 }
92
93 RowLookup locateRow(RowId id) const override {
94 auto found = std::lower_bound(identities.begin(), identities.end(), id, [](const auto &entry, RowId wanted) {
95 return std::tie(entry.first.value, entry.first.generation) < std::tie(wanted.value, wanted.generation);
96 });
97
98 return found == identities.end() || found->first != id ? RowLookup{RowLookupState::NOT_FOUND, 0}
99 : RowLookup{RowLookupState::FOUND, found->second};
100 }
101
102 std::shared_ptr<const ModelSnapshot<T>> source;
103 std::vector<ModelRow<T>> rows;
104 std::vector<std::pair<RowId, std::size_t>> identities;
105};
106} // namespace detail
107
109
126template <std::copy_constructible T, class Q, class Filter, class Compare, class Stop = std::function<bool()>>
127std::expected<QueryPage<T>, QueryError> transformSnapshot(
128 const Query<T, Q> &query, Filter filter, Compare compare, QueryOptions options = {}, Stop stop = [] {
129 return false;
130 }) {
131 if (!query.source || !detail::validQueryOptions(options) || query.page.count > options.maxOutputRows) {
132 return std::unexpected(QueryError::INVALID_ARGUMENT);
133 }
134
135 if (query.source->rowCount() > options.maxSourceRows) {
136 return std::unexpected(QueryError::LIMIT_EXCEEDED);
137 }
138
139 try {
140 if (stop()) {
141 return std::unexpected(QueryError::CANCELLED);
142 }
143
144 auto input =
145 ModelRange<T>::read(query.source, {0, static_cast<std::size_t>(query.source->rowCount())}, options.maxSourceRows);
146
147 if (!input) {
148 return std::unexpected(input.error() == TreeError::NO_MEMORY ? QueryError::NO_MEMORY
151 }
152
153 if (input->state() != RangeState::READY) {
154 return std::unexpected(QueryError::NOT_READY);
155 }
156
157 std::vector<std::size_t> indices;
158
159 indices.reserve(input->rows().size());
160
161 for (std::size_t index = 0; index < input->rows().size(); ++index) {
162 if (stop()) {
163 return std::unexpected(QueryError::CANCELLED);
164 }
165
166 if (filter(input->rows()[index].value, query.criteria)) {
167 indices.push_back(index);
168 }
169 }
170
171 std::size_t comparisons{};
172
173 std::stable_sort(indices.begin(), indices.end(), [&](auto left, auto right) {
174 if (stop()) {
175 throw detail::QueryEvaluationAbort{QueryError::CANCELLED};
176 }
177
178 if (comparisons == options.maxComparisons) {
179 throw detail::QueryEvaluationAbort{QueryError::LIMIT_EXCEEDED};
180 }
181
182 ++comparisons;
183
184 return compare(input->rows()[left].value, input->rows()[right].value, query.criteria);
185 });
186
187 const auto first = static_cast<std::size_t>(std::min<std::uint64_t>(query.page.first, indices.size()));
188 const auto count = std::min(query.page.count, indices.size() - first);
189 std::vector<ModelRow<T>> output;
190
191 output.reserve(count);
192
193 for (std::size_t offset = 0; offset < count; ++offset) {
194 if (stop()) {
195 return std::unexpected(QueryError::CANCELLED);
196 }
197
198 output.push_back(input->rows()[indices[first + offset]]);
199 }
200
201 return QueryPage<T>{std::make_shared<const detail::LocalQueryRows<T>>(query.source, std::move(output)),
202 indices.size()};
203 } catch (detail::QueryEvaluationAbort abort) {
204 return std::unexpected(abort.error);
205 } catch (const std::bad_alloc &) {
206 return std::unexpected(QueryError::NO_MEMORY);
207 } catch (...) {
208 return std::unexpected(QueryError::CALLBACK_FAILED);
209 }
210}
211
217template <class T> class QuerySnapshot final : public ModelSnapshot<T> {
218public:
227 QuerySnapshot(std::uint64_t projectionRevision, std::uint64_t sourceIdentity, std::uint64_t queryGeneration,
228 std::shared_ptr<const ModelSnapshot<T>> source, QueryPage<T> result, RowRange page)
229 : ModelSnapshot<T>(projectionRevision, result.snapshot->rowCount()), source_(std::move(source)),
230 result_(std::move(result)), sourceIdentity_(sourceIdentity), queryGeneration_(queryGeneration), page_(page) {
231 }
232
237 ModelRows<T> read(RowRange range) const override {
238 return result_.snapshot->read(range);
239 }
240
245 RowLookup locateRow(RowId id) const override {
246 return result_.snapshot->locateRow(id);
247 }
248
252 std::uint64_t sourceRevision() const noexcept {
253 return source_->revision();
254 }
255
259 std::uint64_t sourceIdentity() const noexcept {
260 return sourceIdentity_;
261 }
262
266 std::uint64_t queryGeneration() const noexcept {
267 return queryGeneration_;
268 }
269
273 std::shared_ptr<const ModelSnapshot<T>> source() const noexcept {
274 return source_;
275 }
276
280 std::uint64_t totalRows() const noexcept {
281 return result_.totalRows;
282 }
283
287 RowRange page() const noexcept {
288 return page_;
289 }
290
291private:
292 std::shared_ptr<const ModelSnapshot<T>> source_;
293 QueryPage<T> result_;
294 std::uint64_t sourceIdentity_{};
295 std::uint64_t queryGeneration_{};
296 RowRange page_;
297};
298
300namespace detail {
301template <class T, class Q> struct QueryCompletion {
302 std::shared_ptr<ModelLease> lease;
303 std::shared_ptr<const Query<T, Q>> query;
304 std::uint64_t sourceIdentity{};
305 std::uint64_t generation{};
306 std::expected<QueryPage<T>, QueryError> result;
307};
308} // namespace detail
309
311
318template <class T, class Q> class QueryRequest {
319public:
321 QueryRequest() = default;
322
326 QueryRequest(const QueryRequest &other) = default;
327
331 QueryRequest(QueryRequest &&other) noexcept = default;
332
335 query_.reset();
336 lease_.reset();
337 }
338
344 std::swap(query_, other.query_);
345 std::swap(lease_, other.lease_);
346 std::swap(publisher_, other.publisher_);
347 std::swap(options_, other.options_);
348 std::swap(sourceIdentity_, other.sourceIdentity_);
349 std::swap(generation_, other.generation_);
350
351 return *this;
352 }
353
357 std::shared_ptr<const Query<T, Q>> query() const noexcept {
358 return query_;
359 }
360
364 QueryOptions options() const noexcept {
365 return options_;
366 }
367
371 bool stopRequested() const noexcept {
372 return !lease_ || lease_->cancelled.load() || !lease_->lifetime->alive.load();
373 }
374
376 void cancel() const noexcept {
377 if (lease_) {
378 lease_->cancelled.store(true);
379 }
380 }
381
387 std::expected<PublishResult, SchedulerError> complete(std::expected<QueryPage<T>, QueryError> result) const {
388 auto retained = *this;
389
390 return retained.completeOwned(std::move(result));
391 }
392
393private:
394 std::expected<PublishResult, SchedulerError> completeOwned(std::expected<QueryPage<T>, QueryError> result) const {
395 if (stopRequested()) {
396 return std::unexpected(SchedulerError::CLOSED);
397 }
398
399 if (result) {
400 const auto &value = *result;
401 const auto total = value.totalRows;
402 const auto count =
403 query_->page.first < total ? std::min<std::uint64_t>(query_->page.count, total - query_->page.first) : 0;
404
405 if (!value.snapshot || value.snapshot->revision() != query_->source->revision() ||
406 total > query_->source->rowCount() || value.snapshot->rowCount() != count) {
407 return std::unexpected(SchedulerError::INVALID_ARGUMENT);
408 }
409
410 auto rows = ModelRange<T>::read(value.snapshot, {0, static_cast<std::size_t>(count)}, options_.maxOutputRows);
411
412 if (!rows) {
413 return std::unexpected(rows.error() == TreeError::NO_MEMORY ? SchedulerError::NO_MEMORY
414 : rows.error() == TreeError::CALLBACK_FAILED ? SchedulerError::CALLBACK_FAILED
415 : SchedulerError::INVALID_ARGUMENT);
416 }
417
418 if (rows->state() != RangeState::READY) {
419 return std::unexpected(SchedulerError::INVALID_ARGUMENT);
420 }
421 }
422
423 if (stopRequested()) {
424 return std::unexpected(SchedulerError::CLOSED);
425 }
426
427 if (lease_->submitted.exchange(true)) {
428 return std::unexpected(SchedulerError::WOULD_BLOCK);
429 }
430
431 try {
432 auto event = std::make_shared<const detail::QueryCompletion<T, Q>>(lease_, query_, sourceIdentity_, generation_,
433 std::move(result));
434 auto accepted = publisher_.publish(std::move(event));
435
436 if (!accepted) {
437 lease_->submitted.store(false);
438 }
439
440 return accepted;
441 } catch (const std::bad_alloc &) {
442 lease_->submitted.store(false);
443
444 return std::unexpected(SchedulerError::NO_MEMORY);
445 }
446 }
447
448private:
449 template <class, class> friend class QueryController;
450 std::shared_ptr<const Query<T, Q>> query_;
451 std::shared_ptr<detail::ModelLease> lease_;
452 Publisher<detail::QueryCompletion<T, Q>> publisher_;
453 QueryOptions options_;
454 std::uint64_t sourceIdentity_{};
455 std::uint64_t generation_{};
456};
457
462template <class T, class Q> class QueryProvider {
463public:
465 virtual ~QueryProvider() = default;
466
471 virtual void start(QueryRequest<T, Q> request) = 0;
472
476 virtual std::expected<void, SchedulerError> retry() {
477 return {};
478 }
479};
480
489template <std::copy_constructible T, class Q, class Filter, class Compare>
490class MemoryQueryProvider final : public QueryProvider<T, Q> {
491public:
496 MemoryQueryProvider(Filter filter, Compare compare) : filter_(std::move(filter)), compare_(std::move(compare)) {
497 }
498
502 void start(QueryRequest<T, Q> request) override {
503 auto value =
504 transformSnapshot(*request.query(), std::ref(filter_), std::ref(compare_), request.options(), [&request] {
505 return request.stopRequested();
506 });
507
508 if (request.stopRequested()) {
509 return;
510 }
511
512 // Commit a complete new pending value before old criteria/storage can reenter.
513 // Assignment to an engaged optional would retire the old token mid-assignment.
514 auto retired = std::exchange(pending_, {});
515
516 pending_.emplace(Pending{std::move(request), std::move(value)});
517 (void)retry();
518 }
519
523 std::expected<void, SchedulerError> retry() override {
524 if (!pending_) {
525 return {};
526 }
527
528 auto current = std::exchange(pending_, {});
529
530 if (current->request.stopRequested()) {
531 return {};
532 }
533
534 auto accepted = current->request.complete(current->result);
535
536 if (!accepted) {
537 if (!pending_ && !current->request.stopRequested()) {
538 pending_ = std::move(current);
539 }
540
541 return std::unexpected(accepted.error());
542 }
543
544 return {};
545 }
546
547private:
548 struct Pending {
549 QueryRequest<T, Q> request;
550 std::expected<QueryPage<T>, QueryError> result;
551 };
552
553 Filter filter_;
554 Compare compare_;
555 std::optional<Pending> pending_;
556};
557
565template <class T, class Q> class QueryController {
566private:
567 struct State {
568 State(WidgetTree &value, Node<Widget> node) : tree(value), target(node) {
569 }
570
571 std::expected<void, TreeError> allowed() const {
572 if (owner != std::this_thread::get_id()) {
573 return std::unexpected(TreeError::WRONG_THREAD);
574 }
575
576 if (!lifetime->alive.load()) {
577 return std::unexpected(TreeError::CLOSED);
578 }
579
580 return tree.withScope(target, [](const UiScope &) {
581 });
582 }
583
584 std::expected<void, TreeError> retry() {
585 std::shared_ptr<const detail::QueryCompletion<T, Q>> retiredCompletion;
586
587 if (completion) {
588 if (projectionRevision == std::numeric_limits<std::uint64_t>::max()) {
589 notificationError = TreeError::IDENTITY_EXHAUSTED;
590
591 return std::unexpected(*notificationError);
592 }
593
594 try {
595 auto next = std::make_shared<const QuerySnapshot<T>>(projectionRevision + 1, sourceIdentity, generation,
596 completion->query->source, *completion->result,
597 completion->query->page);
598 retiredCompletion = std::move(completion);
599
600 ++projectionRevision;
601 pending = std::move(next);
602 queryError.reset();
603 } catch (const std::bad_alloc &) {
604 notificationError = TreeError::NO_MEMORY;
605
606 return std::unexpected(*notificationError);
607 }
608 }
609
610 if (!pending) {
611 return {};
612 }
613
614 auto frame = model->pin();
615
616 if (!frame) {
617 return std::unexpected(frame.error());
618 }
619
620 if (frame->dataRevision() == pending->revision()) {
621 auto retired = std::move(applied);
622
623 applied = std::exchange(pending, {});
624 notificationError.reset();
625
626 return {};
627 }
628
629 auto accepted = model->publisher().publish(pending);
630
631 if (!accepted) {
632 notificationError = detail::queryTreeError(accepted.error());
633
634 return std::unexpected(*notificationError);
635 }
636
637 notificationError.reset();
638
639 return {};
640 }
641
642 WidgetTree &tree;
643 Node<Widget> target;
644 const std::thread::id owner{std::this_thread::get_id()};
645 QueryOptions options;
646 std::shared_ptr<detail::ModelLifetime> lifetime = std::make_shared<detail::ModelLifetime>();
647 std::weak_ptr<detail::ModelLease> active;
648 std::shared_ptr<QueryProvider<T, Q>> provider;
649 std::unique_ptr<Model<T>> model;
650 std::shared_ptr<const detail::QueryCompletion<T, Q>> completion;
651 std::shared_ptr<const QuerySnapshot<T>> pending;
652 std::shared_ptr<const QuerySnapshot<T>> applied;
653 std::optional<QueryError> queryError;
654 std::optional<TreeError> notificationError;
655 std::uint64_t sourceIdentity{};
656 std::uint64_t sourceRevision{};
657 std::uint64_t generation{};
658 std::uint64_t projectionRevision{1};
659 };
660
661public:
671 static std::expected<std::unique_ptr<QueryController>, TreeError>
672 create(WidgetTree &tree, Node<Widget> context, std::shared_ptr<const ModelSnapshot<T>> source,
673 std::unique_ptr<QueryProvider<T, Q>> provider, QueryOptions options = {}, ModelOptions modelOptions = {}) {
674 if (!source || !provider || !detail::validQueryOptions(options) ||
675 source->rowCount() > std::numeric_limits<std::size_t>::max()) {
676 return std::unexpected(TreeError::INVALID_ARGUMENT);
677 }
678
679 auto allowed = tree.withScope(context, [](const UiScope &) {
680 });
681 auto identity = detail::modelSession();
682
683 if (!allowed || !identity) {
684 return std::unexpected(!allowed ? allowed.error() : identity.error());
685 }
686
687 try {
688 auto state = std::make_shared<State>(tree, context);
689
690 state->options = options;
691 state->sourceIdentity = *identity;
692 state->sourceRevision = source->revision();
693 state->provider = std::move(provider);
694 state->applied =
695 std::make_shared<const QuerySnapshot<T>>(1, *identity, 0, source, QueryPage<T>{source, source->rowCount()},
696 RowRange{0, static_cast<std::size_t>(source->rowCount())});
697
698 auto model = Model<T>::create(tree, context, state->applied, modelOptions);
699
700 if (!model) {
701 return std::unexpected(model.error());
702 }
703
704 state->model = std::move(*model);
705
706 auto connection = tree.template connect<detail::QueryCompletion<T, Q>>(
707 context, [weak = std::weak_ptr(state)](Widget &, std::shared_ptr<const detail::QueryCompletion<T, Q>> event) {
708 auto state = weak.lock();
709
710 if (!state || !state->lifetime->alive.load() || event->lease->cancelled.load() ||
711 event->sourceIdentity != state->sourceIdentity || event->generation != state->generation ||
712 event->query->source->revision() != state->sourceRevision) {
713 return;
714 }
715
716 if (!event->result) {
717 state->queryError = event->result.error();
718
719 return;
720 }
721
722 // Retain accepted ownership before allocating the derived wrapper. A failed
723 // UI allocation is recoverable even after the producer drops every token.
724 state->completion = std::move(event);
725 (void)state->retry();
726 });
727
728 if (!connection) {
729 return std::unexpected(connection.error());
730 }
731
732 return std::unique_ptr<QueryController>(new QueryController(std::move(state), std::move(*connection)));
733 } catch (const std::bad_alloc &) {
734 return std::unexpected(TreeError::NO_MEMORY);
735 }
736 }
737
740 if (state_->owner != std::this_thread::get_id()) {
741 std::terminate();
742 }
743
744 (void)close();
745 }
746
754 std::expected<QueryRequest<T, Q>, TreeError> submit(Query<T, Q> query) {
755 auto state = state_;
756 auto allowed = state->allowed();
757
758 if (!allowed) {
759 return std::unexpected(allowed.error());
760 }
761
762 // Only one derived publication may await observation. This bounds retained
763 // provenance and prevents a queued projection from losing its exact wrapper.
764 auto frame = state->model->pin();
765
766 if (!frame) {
767 return std::unexpected(frame.error());
768 }
769
770 std::shared_ptr<const QuerySnapshot<T>> retired;
771
772 if (state->completion) {
773 return std::unexpected(TreeError::WOULD_BLOCK);
774 }
775
776 if (state->pending) {
777 if (frame->dataRevision() != state->pending->revision()) {
778 return std::unexpected(TreeError::WOULD_BLOCK);
779 }
780
781 retired = std::move(state->applied);
782 state->applied = std::exchange(state->pending, {});
783 }
784
785 if (!query.source || query.page.count > state->options.maxOutputRows ||
786 query.source->revision() < state->sourceRevision) {
787 return std::unexpected(TreeError::INVALID_ARGUMENT);
788 }
789
790 if (state->lifetime->outstanding.load() >= state->options.maxInFlight) {
791 return std::unexpected(TreeError::WOULD_BLOCK);
792 }
793
794 if (state->generation == std::numeric_limits<std::uint64_t>::max()) {
795 return std::unexpected(TreeError::IDENTITY_EXHAUSTED);
796 }
797
798 QueryRequest<T, Q> request;
799 auto publisher = connection_.publisher;
800 auto provider = state->provider;
801 const auto entryGeneration = state->generation;
802 std::shared_ptr<detail::ModelLease> previous;
803
804 try {
805 request.query_ = std::make_shared<const Query<T, Q>>(std::move(query));
806
807 // Moving domain criteria may reenter or destroy this controller. From here
808 // onward use retained state/endpoints only, and revalidate before reserving.
809 auto constructedAllowed = state->allowed();
810
811 if (!constructedAllowed) {
812 return std::unexpected(constructedAllowed.error());
813 }
814
815 if (state->generation != entryGeneration) {
816 return std::unexpected(TreeError::CLOSED);
817 }
818
819 if (request.query_->source->revision() < state->sourceRevision) {
820 return std::unexpected(TreeError::INVALID_ARGUMENT);
821 }
822
823 if (state->completion || state->pending || state->lifetime->outstanding.load() >= state->options.maxInFlight) {
824 return std::unexpected(TreeError::WOULD_BLOCK);
825 }
826
827 request.lease_ = std::make_shared<detail::ModelLease>(state->lifetime, request.query_);
828 request.publisher_ = std::move(publisher);
829 request.sourceIdentity_ = state->sourceIdentity;
830 request.generation_ = state->generation + 1;
831 request.options_ = state->options;
832
833 previous = state->active.lock();
834
835 if (previous) {
836 previous->cancelled.store(true);
837 }
838
839 state->active = request.lease_;
840 state->generation = request.generation_;
841 state->sourceRevision = request.query_->source->revision();
842 state->queryError.reset();
843 provider->start(request);
844
845 // Retirement can execute criteria/source deleters. Check validity only after
846 // releasing these old owners, with the new generation already committed.
847 previous.reset();
848 retired.reset();
849 frame = std::unexpected(TreeError::CLOSED);
850
851 auto stillAllowed = state->allowed();
852
853 if (!stillAllowed) {
854 request.cancel();
855
856 return std::unexpected(stillAllowed.error());
857 }
858
859 if (state->generation != request.generation_ || request.stopRequested()) {
860 request.cancel();
861
862 return std::unexpected(TreeError::CLOSED);
863 }
864
865 return request;
866 } catch (const std::bad_alloc &) {
867 request.cancel();
868
869 return std::unexpected(TreeError::NO_MEMORY);
870 } catch (...) {
871 request.cancel();
872
873 if (request.generation_ == state->generation) {
874 state->queryError = QueryError::CALLBACK_FAILED;
875 }
876
877 return std::unexpected(TreeError::CALLBACK_FAILED);
878 }
879 }
880
884 std::expected<ModelFrame<T>, TreeError> pin() const {
885 auto allowed = state_->allowed();
886
887 return allowed ? state_->model->pin() : std::unexpected(allowed.error());
888 }
889
893 std::expected<ModelConsumer<T>, TreeError> openRange() {
894 auto allowed = state_->allowed();
895
896 return allowed ? state_->model->openRange() : std::unexpected(allowed.error());
897 }
898
903 std::expected<void, TreeError> retryPublication() {
904 auto state = state_;
905 auto allowed = state->allowed();
906
907 if (!allowed) {
908 return std::unexpected(allowed.error());
909 }
910
911 auto provider = state->provider;
912
913 try {
914 auto retried = provider->retry();
915
916 if (!retried) {
917 state->notificationError = detail::queryTreeError(retried.error());
918
919 return std::unexpected(*state->notificationError);
920 }
921 } catch (const std::bad_alloc &) {
922 return std::unexpected(TreeError::NO_MEMORY);
923 } catch (...) {
924 return std::unexpected(TreeError::CALLBACK_FAILED);
925 }
926
927 if (!state->lifetime->alive.load()) {
928 return std::unexpected(TreeError::CLOSED);
929 }
930
931 return state->retry();
932 }
933
937 std::expected<std::shared_ptr<const QuerySnapshot<T>>, TreeError> snapshot() {
938 auto state = state_;
939 auto allowed = state->allowed();
940
941 if (!allowed) {
942 return std::unexpected(allowed.error());
943 }
944
945 auto frame = state->model->pin();
946
947 if (!frame) {
948 return std::unexpected(frame.error());
949 }
950
951 std::shared_ptr<const QuerySnapshot<T>> retired;
952
953 if (state->pending && frame->dataRevision() == state->pending->revision()) {
954 retired = std::move(state->applied);
955 state->applied = std::exchange(state->pending, {});
956 }
957
958 auto result = state->applied;
959
960 return result;
961 }
962
966 std::expected<std::optional<QueryError>, TreeError> lastQueryError() const {
967 auto allowed = state_->allowed();
968
969 return allowed ? std::expected<std::optional<QueryError>, TreeError>(state_->queryError)
970 : std::unexpected(allowed.error());
971 }
972
976 std::expected<std::optional<TreeError>, TreeError> lastError() const {
977 auto allowed = state_->allowed();
978
979 if (!allowed) {
980 return std::unexpected(allowed.error());
981 }
982
983 return state_->notificationError ? std::expected<std::optional<TreeError>, TreeError>(state_->notificationError)
984 : state_->model->lastError();
985 }
986
990 std::expected<void, TreeError> close() {
991 auto state = state_;
992
993 if (state->owner != std::this_thread::get_id()) {
994 return std::unexpected(TreeError::WRONG_THREAD);
995 }
996
997 state->lifetime->alive.store(false);
998
999 if (auto request = state->active.lock()) {
1000 request->cancelled.store(true);
1001 }
1002
1003 (void)connection_.subscription.disconnect();
1004 state->model.reset();
1005 state->provider.reset();
1006 state->pending.reset();
1007 state->completion.reset();
1008
1009 return {};
1010 }
1011
1012private:
1013 QueryController(std::shared_ptr<State> state, SchedulerConnection<detail::QueryCompletion<T, Q>> connection)
1014 : state_(std::move(state)), connection_(std::move(connection)) {
1015 }
1016
1017 std::shared_ptr<State> state_;
1018 SchedulerConnection<detail::QueryCompletion<T, Q>> connection_;
1019};
1020} // namespace portals
std::expected< void, SchedulerError > retry() override
Retry the same result after queue rejection; closed/cancelled retained work is discarded.
Definition model_query.hpp:523
void start(QueryRequest< T, Q > request) override
Evaluate and queue the exact query; retain a rejected notification for retry.
Definition model_query.hpp:502
MemoryQueryProvider(Filter filter, Compare compare)
Own domain callbacks.
Definition model_query.hpp:496
static std::expected< ModelRange, TreeError > read(std::shared_ptr< const ModelSnapshot< T > > owner, RowRange range, std::size_t max_rows)
Read only memory and retain its snapshot. Bounds/provider contract failures are explicit....
Definition model.hpp:244
Immutable list/table provider storage, independent of view/source lifetime. Implement read as bounded...
Definition model.hpp:94
std::uint64_t rowCount() const noexcept
Logical count, without materializing rows.
Definition model.hpp:116
ModelSnapshot(std::uint64_t revision, std::uint64_t rows)
Define immutable metadata.
Definition model.hpp:100
Copyable typed observer; never owns or exposes an unchecked widget pointer.
Definition widget.hpp:92
UI-owned adapter coordinating a fixed provider session and one long-lived Model. Operations require t...
Definition model_query.hpp:565
std::expected< ModelFrame< T >, TreeError > pin() const
Pin the existing model; query queue acceptance may still be awaiting application.
Definition model_query.hpp:884
~QueryController()
Close on UI without joining workers; retained frames and rows stay immutable.
Definition model_query.hpp:739
std::expected< ModelConsumer< T >, TreeError > openRange()
Open an unchanged low-level model interval consumer.
Definition model_query.hpp:893
std::expected< QueryRequest< T, Q >, TreeError > submit(Query< T, Q > query)
Submit explicit provider work; supersedes the previous generation after reservation succeeds.
Definition model_query.hpp:754
std::expected< std::optional< QueryError >, TreeError > lastQueryError() const
Inspect latest typed provider evaluation failure.
Definition model_query.hpp:966
std::expected< std::optional< TreeError >, TreeError > lastError() const
Inspect notification failure first, then existing model UI application failure.
Definition model_query.hpp:976
static std::expected< std::unique_ptr< QueryController >, TreeError > create(WidgetTree &tree, Node< Widget > context, std::shared_ptr< const ModelSnapshot< T > > source, std::unique_ptr< QueryProvider< T, Q > > provider, QueryOptions options={}, ModelOptions modelOptions={})
Create an unqueried source projection and existing bounded scheduler endpoints.
Definition model_query.hpp:672
std::expected< void, TreeError > retryPublication()
Retry retained notification and detect exact projection application; UI-only. Call after dispatch and...
Definition model_query.hpp:903
std::expected< std::shared_ptr< const QuerySnapshot< T > >, TreeError > snapshot()
Inspect provenance of the model's currently applied projection.
Definition model_query.hpp:937
std::expected< void, TreeError > close()
Idempotent UI closure; workers retain source/criteria but receive stop requests.
Definition model_query.hpp:990
Provider owned by a UI query controller; workers retain only query tokens.
Definition model_query.hpp:462
virtual std::expected< void, SchedulerError > retry()
Retry provider-retained rejected completion values on UI; default has no retained work.
Definition model_query.hpp:476
virtual void start(QueryRequest< T, Q > request)=0
Begin explicit provider-side work on UI; do not dispatch, block, or retain UI references....
virtual ~QueryProvider()=default
Reclaim provider resources on UI; outstanding worker tokens remain independently owned.
Copyable worker token owning criteria, source pin and one bounded reservation. Cancellation never joi...
Definition model_query.hpp:318
bool stopRequested() const noexcept
Check cancellation without touching UI.
Definition model_query.hpp:371
void cancel() const noexcept
Cooperatively cancel this work; its reservation remains until the last owner dies.
Definition model_query.hpp:376
std::shared_ptr< const Query< T, Q > > query() const noexcept
Access owning query data while retaining this token.
Definition model_query.hpp:357
QueryRequest(QueryRequest &&other) noexcept=default
Transfer immutable owners and reservation.
std::expected< PublishResult, SchedulerError > complete(std::expected< QueryPage< T >, QueryError > result) const
Validate and queue an owning result or typed failure from any worker thread.
Definition model_query.hpp:387
QueryRequest(const QueryRequest &other)=default
Retain the same work reservation and immutable owners.
QueryOptions options() const noexcept
Evaluation budgets captured when submitted.
Definition model_query.hpp:364
QueryRequest & operator=(QueryRequest other) noexcept
Commit all replacement fields before releasing old storage, which may reenter.
Definition model_query.hpp:343
QueryRequest()=default
Empty cancelled token.
~QueryRequest()
Release criteria before the reservation; the final criteria deleter still sees reserved work.
Definition model_query.hpp:334
std::uint64_t sourceIdentity() const noexcept
Fixed provider session identity.
Definition model_query.hpp:259
QuerySnapshot(std::uint64_t projectionRevision, std::uint64_t sourceIdentity, std::uint64_t queryGeneration, std::shared_ptr< const ModelSnapshot< T > > source, QueryPage< T > result, RowRange page)
Retain immutable source and result owners under a new projection revision.
Definition model_query.hpp:227
std::uint64_t queryGeneration() const noexcept
Query generation represented by the page.
Definition model_query.hpp:266
std::shared_ptr< const ModelSnapshot< T > > source() const noexcept
Original source owner.
Definition model_query.hpp:273
std::uint64_t totalRows() const noexcept
Logical filtered result size before paging.
Definition model_query.hpp:280
RowRange page() const noexcept
Query page in filtered-result coordinates.
Definition model_query.hpp:287
std::uint64_t sourceRevision() const noexcept
Original exact source revision.
Definition model_query.hpp:252
ModelRows< T > read(RowRange range) const override
Read only the already materialized page.
Definition model_query.hpp:237
RowLookup locateRow(RowId id) const override
Resolve identity in the page-local result.
Definition model_query.hpp:245
UI-owned scope disconnecting all its subscriptions and timers, in any token order....
Definition scheduler.hpp:154
Exclusive parent/child ownership on Scheduler's UI thread. Scheduler must outlive this object....
Definition widget.hpp:179
std::expected< void, TreeError > withScope(Node< Widget > node, Callback &&callback)
Borrow the node-owned scope for registration with the existing Scheduler. Registrations borrowing wid...
Definition widget.hpp:340
Public Portals API.
Definition action.hpp:8
SchedulerError
Observable operation failures; no callback is started on rejection.
Definition scheduler.hpp:20
@ CLOSED
Scheduler, scope, registration or endpoint is closed.
Definition scheduler.hpp:24
@ CALLBACK_FAILED
A user callback threw; dispatch disconnects its registration.
Definition scheduler.hpp:29
@ WOULD_BLOCK
A bounded queue or registration budget has no available slot.
Definition scheduler.hpp:25
@ NO_MEMORY
Allocation failed inside the operation boundary.
Definition scheduler.hpp:26
@ READY
Exactly the requested immutable rows are available.
Definition model.hpp:47
@ NOT_READY
Immutable provider range is pending or failed; no I/O was started.
Definition find_bar.hpp:54
@ CALLBACK_FAILED
A non-allocation exception escaped into a runner callback boundary.
Definition application.hpp:34
@ NO_MEMORY
Allocation failed at a runner exception boundary.
Definition application.hpp:33
@ CANCELLED
Explicit cancellation or replacement stopped the invocation.
Definition async.hpp:29
@ INVALID_ARGUMENT
Empty task, callback or immutable data owner, or invalid policy.
Definition async.hpp:26
@ LIMIT_EXCEEDED
A storage request cannot fit its configured aggregate budget.
Definition background_options.hpp:19
QueryError
Domain query evaluation failures, separate from scheduler acceptance.
Definition model_query.hpp:12
@ LIMIT_EXCEEDED
Source scan or comparison budget is exhausted.
Definition model_query.hpp:14
@ CALLBACK_FAILED
Domain predicate, comparator, copy, or source read threw.
Definition model_query.hpp:19
@ STALE_SOURCE
Result does not have the exact requested source revision.
Definition model_query.hpp:16
@ NOT_READY
Local source is pending or failed; no I/O is initiated.
Definition model_query.hpp:15
@ CANCELLED
Cooperative cancellation was observed.
Definition model_query.hpp:17
@ INVALID_ARGUMENT
Invalid page, limits, or malformed provider result.
Definition model_query.hpp:13
@ NO_MEMORY
Evaluation could not allocate its bounded storage.
Definition model_query.hpp:18
std::expected< QueryPage< T >, QueryError > transformSnapshot(const Query< T, Q > &query, Filter filter, Compare compare, QueryOptions options={}, Stop stop=[] { return false;})
Explicit local filter, stable sort, and page; never dispatches or starts provider I/O....
Definition model_query.hpp:127
TreeError
Checked tree failures; rejected operations never start the requested callback.
Definition widget_types.hpp:26
@ CLOSED
The owning tree or source is closed.
Definition widget_types.hpp:31
@ CALLBACK_FAILED
A user extension or callback threw.
Definition widget_types.hpp:37
@ WRONG_THREAD
Operation requires the tree's UI thread.
Definition widget_types.hpp:28
@ WOULD_BLOCK
The current frame/reentry boundary or finite queue/work budget rejects this operation.
Definition widget_types.hpp:32
@ IDENTITY_EXHAUSTED
A session, generation or revision cannot advance without reuse.
Definition widget_types.hpp:34
@ INVALID_ARGUMENT
An option, enum value or operation argument is invalid.
Definition widget_types.hpp:27
@ NO_MEMORY
Allocation failed inside the operation boundary.
Definition widget_types.hpp:33
Finite per-model storage and work budgets; all fields must be positive.
Definition model.hpp:165
Provider result borrowing from its immutable snapshot.
Definition model.hpp:64
Configurable finite query budgets; all values must be positive.
Definition model_query.hpp:23
std::size_t maxComparisons
Maximum comparator invocations per local evaluation.
Definition model_query.hpp:27
std::size_t maxOutputRows
Maximum requested and returned page size, in rows.
Definition model_query.hpp:25
std::size_t maxInFlight
Reservations, including cancelled tokens still owned by workers.
Definition model_query.hpp:24
std::size_t maxSourceRows
Maximum rows examined by local snapshot evaluation.
Definition model_query.hpp:26
Provider's owning page at the exact source revision, before projection publication.
Definition model_query.hpp:45
std::shared_ptr< const ModelSnapshot< T > > snapshot
Contiguous page; revision equals requested source revision.
Definition model_query.hpp:46
std::uint64_t totalRows
Logical filtered row count before paging.
Definition model_query.hpp:47
Owning domain criteria, exact indexed source, and explicit output page. This value performs no I/O....
Definition model_query.hpp:36
Q criteria
Owning domain value interpreted by the provider.
Definition model_query.hpp:38
std::shared_ptr< const ModelSnapshot< T > > source
Exact immutable source pin retained by the work token.
Definition model_query.hpp:37
RowRange page
Page within the filtered/sorted result; default first 256 rows.
Definition model_query.hpp:39
Provider-assigned row identity, independent of position; increment generation on reuse.
Definition row_id.hpp:9
Owning lookup result; no row storage is borrowed.
Definition model.hpp:78
Half-open logical row interval; arithmetic is checked before provider access.
Definition model.hpp:35
std::uint64_t first
First logical row.
Definition model.hpp:36
std::size_t count
Number of rows, bounded independently of logical model size.
Definition model.hpp:37
UI owns the subscription; workers receive copies of only the publisher.
Definition scheduler.hpp:227