From b952a29634b94b7c7d5b4f6b76a88ab2e26f5720 Mon Sep 17 00:00:00 2001 From: victor Date: Wed, 11 Nov 2026 20:01:24 -0800 Subject: [PATCH 1/3] docs(resource-groups): document CPU limits, fair scheduling and SET RESOURCE GROUP Document the resource group features of QuestDB Enterprise 4.2.0: the cpu_limit and scheduling_policy parameters, the new resource_groups() columns, SET and RESET RESOURCE GROUP with the resource_group parameter of /execute, and the USE RESOURCE GROUP permission. Correct when CPU scheduling engages and how the parallel tasks of CREATE TABLE AS SELECT are charged. --- documentation/changelog.mdx | 7 +- documentation/concepts/resource-groups.md | 214 ++++++++++++++--- .../configuration/resource-groups.md | 4 +- .../connect/compatibility/rest-api.md | 1 + documentation/operations/logging-metrics.md | 11 +- documentation/operations/resource-groups.md | 216 +++++++++++++++++- documentation/operations/upgrade.md | 17 ++ .../query/functions/access-control.md | 5 +- documentation/query/functions/meta.md | 57 ++++- .../sql/acl/alter-group-set-resource-group.md | 6 + .../query/sql/acl/alter-resource-group.md | 33 ++- ...lter-service-account-set-resource-group.md | 6 + .../sql/acl/alter-user-set-resource-group.md | 6 + .../query/sql/acl/create-resource-group.md | 77 +++++-- documentation/query/sql/acl/grant.md | 58 +++++ documentation/query/sql/acl/revoke.md | 30 +++ .../query/sql/acl/set-resource-group.md | 177 ++++++++++++++ documentation/security/rbac.md | 2 + documentation/sidebars.js | 1 + 19 files changed, 846 insertions(+), 82 deletions(-) create mode 100644 documentation/query/sql/acl/set-resource-group.md diff --git a/documentation/changelog.mdx b/documentation/changelog.mdx index e6568ed98..8d14cc2cf 100644 --- a/documentation/changelog.mdx +++ b/documentation/changelog.mdx @@ -25,6 +25,9 @@ This page tracks significant updates to the QuestDB documentation. - [Durability and commit modes](/docs/concepts/durability/) - New page on what a commit survives in each commit mode, and on adaptive durability mode, which keeps commits to WAL tables safe from power loss without flushing every table file on each commit. Covers how it works, the group-commit window, durable acknowledgements, guarantees and limits, costs, changing the mode and downgrading, monitoring, and troubleshooting - [UPSERT and SKIP modes](/docs/concepts/deduplication/#upsert-and-skip-modes) - The new `SKIP` deduplication mode in QuestDB 10.2.0 and QuestDB Enterprise 4.2.0 keeps the first row written for a key and discards later duplicates, the counterpart of `UPSERT`, which keeps the latest. Covers which row wins within a commit and across connections, choosing a mode, switching modes with [`ALTER TABLE DEDUP ENABLE`](/docs/query/sql/alter-table-enable-deduplication/), reading the mode from [`SHOW CREATE TABLE`](/docs/query/sql/show/#deduplication-clause), and how earlier versions handle such tables - [ALTER TABLE FORCE REINDEX PARQUET](/docs/query/sql/alter-table-force-reindex-parquet/) - Rebuild bitmap and posting indexes on Parquet partitions while the table stays online, available from QuestDB 10.2.0 and QuestDB Enterprise 4.2.0. Use it to repair Parquet partitions left with stale column metadata by QuestDB 9.3.4 through 10.0.1. Covers column and partition selection, cancellation, skipped partitions, automatic repair by `ADD INDEX` and out-of-order writes, and running it on QuestDB Enterprise replicas +- [Resource group CPU limits](/docs/concepts/resource-groups/#a-cpu-limit-is-a-ceiling-not-a-share) - `cpu_limit` caps a resource group's query CPU at a percentage of the node's CPUs, even while the rest of the node is idle, available from QuestDB Enterprise 4.2.0. Covers how the limit is enforced for whole and fractional cores, what it does not count, how parallel queries and `CREATE TABLE ... AS SELECT` behave under it, and [what to check](/docs/operations/resource-groups/#troubleshooting) when a group waits or exceeds its limit +- [Fair scheduling inside a resource group](/docs/concepts/resource-groups/#the-scheduling-policy-divides-a-group-between-its-users) - `scheduling_policy = 'fair'`, available from QuestDB Enterprise 4.2.0, divides a group's CPU by user first, then by query, and admits the user with the fewest admitted queries first, while `fifo` stays the default +- [SET RESOURCE GROUP](/docs/query/sql/acl/set-resource-group/) - New page: a PostgreSQL session chooses its resource group with `SET RESOURCE GROUP`, and an HTTP request with the `resource_group` parameter of `/execute`, so one account can send urgent and routine work to different groups, available from QuestDB Enterprise 4.2.0. Covers the new `USE RESOURCE GROUP` permission, which [GRANT](/docs/query/sql/acl/grant/#grant-use-of-resource-groups) and [REVOKE](/docs/query/sql/acl/revoke/#revoke-use-of-resource-groups) give for one group or for all, its check at every managed query, connection poolers, and access control being off ### Reference @@ -35,16 +38,18 @@ This page tracks significant updates to the QuestDB documentation. - Added the `durableEpochSeqTxn`, `recoveryIncarnation`, `localDurableSeqTxn`, and `lastEpochTs` columns to [`wal_tables()`](/docs/query/functions/meta/#wal_tables) and three adaptive commit [metrics](/docs/integrations/other/prometheus/#wal-metrics), and corrected the names of `questdb_wal_apply_seq_txn` and `questdb_wal_apply_writer_txn` - [CREATE TABLE](/docs/query/sql/create-table/#deduplication) - `DEDUP { UPSERT | SKIP } KEYS` in the syntax of both creation forms; `CREATE TABLE LIKE` copies the keys and the mode - [Standard SQL equivalents](/docs/concepts/deep-dive/sql-extensions/#standard-sql-features-not-supported) - `INSERT ... ON CONFLICT DO NOTHING` maps to `DEDUP SKIP KEYS` +- Added the `cpu_limit` and `scheduling_policy` parameters to [CREATE RESOURCE GROUP](/docs/query/sql/acl/create-resource-group/#parameters) and [ALTER RESOURCE GROUP](/docs/query/sql/acl/alter-resource-group/), the `cpu_min_share_pct`, `cpu_limit_pct`, `cpu_limit_cores`, and `scheduling_policy` columns to [`resource_groups()`](/docs/query/functions/meta/#resource_groups), the `resource_group` parameter to [`/execute`](/docs/connect/compatibility/rest-api/#execute), and `USE RESOURCE GROUP` to the [permissions reference](/docs/security/rbac/#permissions) ### Updated +- [Resource groups](/docs/concepts/resource-groups/) and [Configure and use resource groups](/docs/operations/resource-groups/) - CPU scheduling also engages when any group has a CPU limit or the `fair` policy; a group that returns from idle neither gains nor owes CPU, however long the instance has run; corrected that the parallel tasks of a `CREATE TABLE ... AS SELECT` are not charged to a group without a CPU limit. Added scenarios for a tenant capped at part of the node, a team sharing a group fairly, one account sending urgent and routine queries, and a protected operator share - [REINDEX](/docs/query/sql/reindex/) - Explains that `LOCK EXCLUSIVE` is required and takes the table's writer lock, and that `REINDEX` rebuilds native partitions only: it skips Parquet partitions and rejects a Parquet partition named in `PARTITION` - [CREATE MATERIALIZED VIEW](/docs/query/sql/create-mat-view/#limit-and-window-function-restrictions) - Breaking change in QuestDB 10.2.0 and QuestDB Enterprise 4.2.0: the part of a materialized view's query that reads its base table (this includes a subquery on the base table) can no longer use `LIMIT`, or a window function nested inside an expression, such as `row_number() OVER (ORDER BY timestamp) + 1`. A window function that makes up a whole column was already rejected. A `LIMIT` in a subquery over a *different* table is still allowed - [ALTER TABLE SET TYPE](/docs/query/sql/alter-table-set-type/) - A conversion to non-WAL applies the WAL first, and is refused while it cannot - [ALTER TABLE SET TYPE](/docs/query/sql/alter-table-set-type/) and [ALTER TABLE REBASE WAL](/docs/query/sql/alter-table-rebase-wal/) - The table keeps its TTL, `FORMAT PARQUET`, per-column Parquet encoding, and deduplication keys and mode; a table converted to WAL keeps dropping partitions past its TTL - [ALTER TABLE RESUME WAL](/docs/query/sql/alter-table-resume-wal/) - In adaptive durability mode, `RESUME WAL` may first take a save point and need the table's writer, so it can fail with `table busy` or leave the table suspended until you retry - [Disaster recovery](/docs/high-availability/disaster-recovery/#a-primary-refuses-to-start-after-a-power-loss) - A QuestDB Enterprise primary refuses to start when its log of a table ends before the object store, and how to recover -- [Upgrade QuestDB](/docs/operations/upgrade/#upgrading-to-420) - What to check before upgrading to QuestDB Enterprise 4.2.0, and the limits on going back to an earlier release +- [Upgrade QuestDB](/docs/operations/upgrade/#upgrading-to-420) - What to check before upgrading to QuestDB Enterprise 4.2.0, including what changes for resource groups, and the limits on going back to an earlier release - [Monitoring and alerting](/docs/operations/monitoring-alerting/#detect-adaptive-commit-problems) - What to alert on in adaptive durability mode - [SHOW CREATE TABLE](/docs/query/sql/show/#show-create-table) - The example output matches what the server returns, without symbol capacities or a `WITH` clause - [Store-and-forward](/docs/high-availability/store-and-forward/concepts/) and client pages - Switched to the same plain terms throughout: *memory-only mode*, previously *memory mode*, for running without `sf_dir`, distinct from `sf_durability=memory`; *sender directory*, previously *slot*, and *journal* on the [Node.js](/docs/connect/clients/nodejs/#store-and-forward) page, for `//`; and *batch* for what a flush sends, which the protocol calls a frame. The [storage keys](/docs/high-availability/store-and-forward/configuration/#storage-keys) of the store-and-forward configuration page now say what each key does to flushes and sender directories, and which flushes are split into several batches or rejected diff --git a/documentation/concepts/resource-groups.md b/documentation/concepts/resource-groups.md index 0cf301d0c..9e29ea2e7 100644 --- a/documentation/concepts/resource-groups.md +++ b/documentation/concepts/resource-groups.md @@ -3,8 +3,8 @@ title: Resource groups sidebar_label: Resource groups description: Resource groups isolate query workloads inside one QuestDB instance. Learn how - a query is assigned to a group, and what admission, CPU weight and memory - limits actually guarantee. + a query is assigned to a group, and what admission, CPU weights, CPU limits, + scheduling policies and memory limits actually guarantee. --- import { EnterpriseNote } from "@site/src/components/EnterpriseNote" @@ -36,27 +36,37 @@ CREATE RESOURCE GROUP reporting WITH ( ALTER USER analyst SET RESOURCE GROUP reporting; ``` -A policy sets three controls, and they differ in how strong a guarantee they +A policy sets four controls, and they differ in how strong a guarantee they give: - [Admission](#admission-is-a-hard-gate) is how many queries a group may run at once, how many may wait, and how long they may wait. It is an exact limit. - [Weighted CPU](#cpu-weight-is-a-share-not-a-reservation) is the share of query CPU a group receives while groups compete. It is a share, not a reservation. +- [A CPU limit](#a-cpu-limit-is-a-ceiling-not-a-share) is the most query CPU a + group may use, as a percentage of the node, even while the rest of the node + is idle. It holds on average over a short window. - [Memory](#memory-limits-use-batched-accounting) is the process and group budgets for tracked native query memory. It is approximate at the margin. +A group's +[scheduling policy](#the-scheduling-policy-divides-a-group-between-its-users) +then decides how the group divides what it receives between its own users and +queries. + The design is [cooperative](#how-cooperative-cpu-scheduling-works). QuestDB executes query work on shared worker pools, and resource groups do not create -one operating-system thread pool per group. A query and all of its parallel -tasks use the same resource group, while every worker stays available to every -group. +one operating-system thread pool per group. A query and its parallel tasks use +the same resource group, with one exception for +[`CREATE TABLE ... AS SELECT`](#which-statements-are-managed), while every +worker stays available to every group. ## Who a resource group applies to A policy attaches to **principals**, and a principal is one of three things: a user, an ACL group, or a service account. Assignment follows the authenticated -principal, not the statement. +principal, not the statement, unless the session +[chooses another group](#choosing-a-group-per-session-or-request). ```questdb-sql title="The three kinds of principal you can map" ALTER USER analyst SET RESOURCE GROUP reporting; @@ -89,8 +99,8 @@ mappings distinct priorities when the order matters. ::: Anything not mapped runs in `DEFAULT`, which always exists and carries no limits -of its own: a CPU weight of 100, unlimited admission, and the instance-wide -memory limits. You can change its policy, but you cannot drop or rename it. +of its own: a CPU weight of 100, no CPU limit, `fifo` scheduling, unlimited +admission, and the instance-wide memory limits. You can change its policy, but you cannot drop or rename it. A session that assumes a service account keeps the group of the principal that logged in, while the service account's own mapping applies to sessions that @@ -100,6 +110,33 @@ The group is resolved once, when the query starts, and stays fixed for the statement's lifetime. Changing a mapping affects statements that start after the change, never one already running. +### Choosing a group per session or request + +A mapping gives each principal one group, but one account often sends work of +different urgency, such as a monitoring account that evaluates alert rules and +also serves dashboards. Such an account can choose the group itself: a +PostgreSQL session with +[`SET RESOURCE GROUP`](/docs/query/sql/acl/set-resource-group/), and an HTTP +request with the `resource_group` parameter of +[`/execute`](/docs/connect/compatibility/rest-api/#execute). + +```questdb-sql title="Run the rest of this session's queries in the alerts group" +SET RESOURCE GROUP alerts; +``` + +Choosing a group per session or request is available from QuestDB Enterprise +4.2.0. The chosen group replaces the mapping for every query the session starts +afterwards, until `RESET RESOURCE GROUP`. A group other than the principal's own +requires the `USE RESOURCE GROUP` permission, granted for one group with +[`GRANT USE ON RESOURCE GROUP`](/docs/query/sql/acl/grant/#grant-use-of-resource-groups) +or for every group with `GRANT USE RESOURCE GROUP`, so users cannot move +themselves into a heavier group. The permission is checked at the start of every +managed query, so a revoke applies to the session's next one. + +With access control disabled there is no permission check, and since mapping +statements need access control, choosing the group per session or request is +then the only way to run queries outside `DEFAULT`. + ## Which statements are managed Resource groups govern the statements that read data: @@ -117,7 +154,11 @@ For `CREATE TABLE ... AS SELECT` and `INSERT ... SELECT` the group is charged for reading the source and producing rows, including parallel work. Where writing a row cannot be separated from producing it, that CPU is charged to the group as well. The commit, durability and any work handed to writer or WAL -queues are outside the guarantee. +queues are outside the guarantee. The parallel tasks of a +`CREATE TABLE ... AS SELECT` are an exception: they run outside the group and +are not charged to it, unless the group has a CPU limit, in which case the copy +runs them itself on its own thread. See +[A CPU limit is a ceiling](#a-cpu-limit-is-a-ceiling-not-a-share). Resource groups account **tracked native query memory**. They do not represent JVM heap, resident set size, memory-mapped table pages or long-lived engine @@ -157,18 +198,128 @@ CREATE RESOURCE GROUP adhoc WITH (cpu_weight = 50); ``` Weights only matter when groups compete. A group that is alone on the instance -uses everything it can, regardless of its weight. When two groups both have +uses everything it can, regardless of its weight, unless it has a +[CPU limit](#a-cpu-limit-is-a-ceiling-not-a-share). When two groups both have work, the scheduler hands out CPU so that measured CPU divided by `cpu_weight` stays balanced: weights 100 and 50 converge to a 2:1 split of query CPU. A query that was running alone starts sharing at its next checkpoint. -Weights are relative. 100 and 50 are the same as 2 and 1. A group that becomes -active starts level with the groups already running, so it neither banks the CPU -it did not use while idle nor is punished for having been busy. +Weights are relative. 100 and 50 are the same as 2 and 1. +[`resource_groups()`](/docs/query/functions/meta/#resource_groups) shows each +weight as a percentage of all weights in `cpu_min_share_pct`: the share a group +can count on while every group has work. Adding a group lowers every other +group's percentage, and the column shows by how much. + +Idle CPU is not banked in either direction. A group that becomes active takes +the next free worker and then runs at its share: it gains nothing for the time +it left its share unused, and a group that used the spare CPU meanwhile owes +nothing for it. This holds however long the instance has been running. A +group's CPU is counted once for the whole process, so its queries over HTTP and +over PostgreSQL draw on the same share. -Shares are between groups, not between queries. Within a group, work is served -in arrival order, and a parallel query can hold several places in that order, so -there is no promise of equal CPU between individual queries. +Shares are between groups, not between queries. How a group divides its share +between its own users and queries depends on its +[scheduling policy](#the-scheduling-policy-divides-a-group-between-its-users). + +### A CPU limit is a ceiling, not a share + +```questdb-sql title="Never more than a quarter of the node, even when it is idle" +CREATE RESOURCE GROUP tenant_a WITH (cpu_limit = '25%'); +``` + +`cpu_limit` caps the query CPU a group may use at a percentage of the CPUs +available to the QuestDB process, which respects a container's CPU limit. On 16 +CPUs, `'25%'` is 4 cores and `'5%'` is 0.8 of a core. A weight lets a group use +CPU that others leave idle; a limit does not, so the group stays at its limit +when the rest of the node has nothing to do. That makes a limit the tool for +capacity sold by the core, for performance that does not change with the +neighbours' load, and for keeping room for work outside resource groups, such as +ingestion. Below its limit a group still competes by weight as usual. CPU +limits are available from QuestDB Enterprise 4.2.0. + +The limit holds on average over a short window, and it is enforced in two +parts: + +- A group holds at most as many workers at once as its limit rounded up to + whole cores, across every worker pool. A limit of a whole number of cores + needs nothing more, because a worker uses at most one core. +- A fractional limit, such as 0.8 or 3.5 cores, adds a CPU budget that refills + at the limit's rate. The group can run ahead of the rate by about 100 + milliseconds' worth of it, and then waits until the budget has refilled. Idle + time is not banked beyond that. + +Only the CPU that queries use on their workers counts. Work outside them, such +as garbage collection, JIT compilation and WAL apply, does not, so the process +can use more CPU in total than its groups' limits add up to. + +Parallel work counts against the group like the rest of the query, with two +consequences: + +- A group limited to one core or less runs a query's parallel work on the + query's own thread, so its parallel queries run single-threaded. +- Above one core, a fractional limit does not make parallel tasks wait for the + budget, because a waiting task holds up other queries' tasks on its queue. + The query repays what they used before it continues, so the limit holds on + average, but one parallel query can run above the rate for a moment. The cap + on workers held at once still applies. + +`CREATE TABLE ... AS SELECT` cannot give up its worker while it copies. In a +group with a limit it therefore runs single-threaded and keeps one of the +group's workers until it finishes. When that is the last worker the group may +hold, the group's other queries wait for the copy, under either scheduling +policy. + +Under a fractional limit a copy's CPU is recorded in full, but the debt such +statements leave the group is capped at what its limit refills in 10 seconds. +After a long copy the group therefore waits at most about 10 seconds, instead of +however long its limit would take to repay the whole copy: about 7 hours for a +one-hour copy under a limit of 0.14 cores. A group that runs long copies back to back can use far more +than its limit as a result: in one measurement on 14 cores, 100-second copies +under `cpu_limit = '1%'` used about 6.5% of the node, close to a whole core. +Under a whole-core limit there is no budget, and a copy only keeps its worker. + +`INSERT ... SELECT` gives up its worker like any query, so none of this applies +to it. Any statement that waits for the budget keeps its locks while it waits, +though, including the table writer of an `INSERT ... SELECT`. + +### The scheduling policy divides a group between its users + +```questdb-sql title="Split the group evenly between its busy users" +CREATE RESOURCE GROUP research WITH (scheduling_policy = 'fair'); +``` + +Scheduling policies are available from QuestDB Enterprise 4.2.0; earlier +releases always serve a group in arrival order. The policy decides which query +of a group gets the next worker the group is entitled to: + +- `fifo`, the default, serves the group's work in arrival order. A long query + keeps its workers while later queries wait behind it, which finishes batch + work soonest. A parallel query can hold several places in that order, so + there is no promise of equal CPU between queries. +- `fair` divides the group by user first, then by query. A freed worker goes to + the user holding the fewest of the group's workers in that worker pool, and + then to that user's query holding the fewest. On a tie, a user or query that + has not run in the pool yet goes first, so a new query starts promptly. At + the end of each CPU slice, a running query yields its worker to a waiting + user, or to another query of the same user, that holds fewer workers. + +Under `fair`, busy users split the group evenly, a user's unused part stays +inside the group, and one user alone can use all of it. Dividing by user first +stops one user from taking ten parts by sending ten queries, and dividing by +query second keeps the queries of an application that uses a single account +from queuing behind each other in arrival order. + +Admission follows the same rule. When a `fair` group is at +`max_active_queries`, the waiting user with the fewest admitted queries goes +next, and a tie goes to the user who has waited longest since their last +admission. One user's queue therefore does not keep everyone else out, and with +`max_active_queries = 1` users take turns. + +The user is the principal that logged in. With access control disabled it is +the login name the client used, so clients that share one login count as one +user and `fair` alternates between their queries. There are no weights between +users inside a group; a user who needs a different part needs a group of its +own, which then no longer shares the group's total. ### Memory limits use batched accounting @@ -230,21 +381,24 @@ and other groups alone, and its CPU is still charged to its group. ### When scheduling engages Slicing happens only while CPU scheduling is engaged, and that requires a second -resource group to exist. While `DEFAULT` is the only resource group, scheduling -stays disengaged: no CPU is sampled, no query yields, and every query holds its -worker exactly as it does with the feature disabled. Registration, admission and -memory accounting still run, so this is not free, but the cost is a fixed few +resource group, or a group with a CPU limit or the `fair` scheduling policy. +While `DEFAULT` is the only resource group and has neither, scheduling stays +disengaged: no CPU is sampled, no query yields, and every query holds its worker +exactly as it does with the feature disabled. Registration, admission and memory +accounting still run, so this is not free, but the cost is a fixed few microseconds per query. -Scheduling engages when a second group is created and disengages once the last -other group has been dropped and its queries have finished. A query that is -already running when a group is created stays outside scheduling until it next -suspends or finishes; the new policy applies to queries that start or resume -after the change. +Scheduling engages when a second group is created, or when any group, `DEFAULT` +included, is given a CPU limit or the `fair` policy. It disengages once none of +these holds any longer and the queries of dropped groups have finished. A query +that is already running when scheduling engages stays outside scheduling until +it next suspends or finishes; the new policy applies to queries that start or +resume after the change. Once scheduling is engaged, a query whose group is alone still keeps its worker: at each checkpoint it renews its grant in place and yields only when another -query is waiting for its worker. +query is waiting for its worker, or when its group's CPU limit or `fair` policy +requires it. Queries are assigned to a group throughout, whether or not scheduling is engaged. Disengaged scheduling means no CPU slicing, not that the feature @@ -308,6 +462,12 @@ Mapping principals: - [ALTER SERVICE ACCOUNT SET RESOURCE GROUP](/docs/query/sql/acl/alter-service-account-set-resource-group/) and [UNSET](/docs/query/sql/acl/alter-service-account-unset-resource-group/) +Choosing a group per session or request: + +- [SET RESOURCE GROUP](/docs/query/sql/acl/set-resource-group/) +- [GRANT USE ON RESOURCE GROUP](/docs/query/sql/acl/grant/#grant-use-of-resource-groups) + and [REVOKE](/docs/query/sql/acl/revoke/#revoke-use-of-resource-groups) + Inspecting: - [`resource_groups()`](/docs/query/functions/meta/#resource_groups) diff --git a/documentation/configuration/resource-groups.md b/documentation/configuration/resource-groups.md index 838eef819..ae3a5f582 100644 --- a/documentation/configuration/resource-groups.md +++ b/documentation/configuration/resource-groups.md @@ -14,8 +14,8 @@ Resource groups are [Enterprise](/enterprise/) only. [Resource groups](/docs/concepts/resource-groups/) isolate competing query workloads inside one instance. These settings are instance-wide. The per-group -policy that decides admission, CPU share and memory budgets is set in SQL, not -here. See [Configure and use resource groups](/docs/operations/resource-groups/) +policy that decides admission, CPU share, CPU limit, scheduling policy and +memory budgets is set in SQL, not here. See [Configure and use resource groups](/docs/operations/resource-groups/) for those statements. None of these settings are reloadable: changing any of them requires a restart. diff --git a/documentation/connect/compatibility/rest-api.md b/documentation/connect/compatibility/rest-api.md index 467f565d6..689ad2ac2 100644 --- a/documentation/connect/compatibility/rest-api.md +++ b/documentation/connect/compatibility/rest-api.md @@ -186,6 +186,7 @@ parameters. `POST` is not supported and returns `405`. | `timings` | No | `false` | `true` or `false`. When set to `true`, QuestDB will also include a `timings` property in the response which gives details about the execution times. | | `explain` | No | `false` | `true` or `false`. When set to `true`, QuestDB will also include an `explain` property in the response which gives details about the execution plan. | | `quoteLargeNum` | No | `false` | `true` or `false`. When set to `true`, QuestDB will surround `LONG` type numbers with double quotation marks that will make them parsed as strings. | +| `resource_group` | No | | QuestDB Enterprise 4.2.0 and later. Runs the query in this [resource group](/docs/concepts/resource-groups/), which takes the `USE RESOURCE GROUP` permission unless it is the group the principal is mapped to. The HTTP counterpart of [`SET RESOURCE GROUP`](/docs/query/sql/acl/set-resource-group/), for this request only. | The parameters must be URL encoded. diff --git a/documentation/operations/logging-metrics.md b/documentation/operations/logging-metrics.md index 31a96a6dd..3875ba0f0 100644 --- a/documentation/operations/logging-metrics.md +++ b/documentation/operations/logging-metrics.md @@ -484,11 +484,12 @@ endpoint exposes one series per group, labelled with `resource_group`: | `questdb_resource_group_admission_timeouts_total` | counter | Queries that timed out while queued | `cpu_nanos_total` counts only CPU that managed scheduling measured, so treat it -as a floor rather than a full account. While `DEFAULT` is the only group, CPU -scheduling is disengaged and nothing is sampled, so the series reads `0` however -busy the instance is. It also undercounts once scheduling is engaged: a query -already running when a second group was created stays outside scheduling until -it next suspends, and a degraded scheduler stops sampling altogether. +as a floor rather than a full account. While `DEFAULT` is the only group and has +no CPU limit or `fair` policy, CPU scheduling is disengaged and nothing is +sampled, so the series reads `0` however busy the instance is. It also +undercounts once scheduling is engaged: a query already running when scheduling +engaged stays outside it until it next suspends, and a degraded scheduler stops +sampling altogether. A flat counter therefore does not imply an idle group. Check `questdb_resource_groups_cpu_managed_dispatch` and diff --git a/documentation/operations/resource-groups.md b/documentation/operations/resource-groups.md index 46410f604..2e061b6f3 100644 --- a/documentation/operations/resource-groups.md +++ b/documentation/operations/resource-groups.md @@ -25,12 +25,17 @@ siblings. - QuestDB Enterprise. - Access control enabled (`acl.enabled=true`). Groups can be created without it, but mapping statements require it, since mappings attach to ACL principals. + Without it, a session can still choose a group with + [`SET RESOURCE GROUP`](/docs/query/sql/acl/set-resource-group/). - The worker pools that execute SQL must run in Fiber mode, which is the default. - The [`RESOURCE GROUP ADMIN`](/docs/security/rbac/#permissions) permission for - group management, mappings and instance-wide inspection through - `resource_groups()`. Ordinary users need no permission to call - `current_resource_group()` and check their own query's group. + group management, mappings, `GRANT USE ON RESOURCE GROUP` and instance-wide + inspection through `resource_groups()`. Ordinary users need no permission to + call `current_resource_group()` and check their own query's group. +- The `USE RESOURCE GROUP` permission for a principal that chooses a group other + than its own for a session or a request. See + [SET RESOURCE GROUP](/docs/query/sql/acl/set-resource-group/#permissions). Mapping a principal to a resource group grants it nothing by itself. The user still needs `HTTP` or `PGWIRE` to connect and `SELECT` on the tables it queries, @@ -74,7 +79,9 @@ Three things are worth knowing before you change policy on a running system: - **Changes apply online.** An `ALTER` does not cancel anything running at that moment. Slots already held are kept, an already queued request keeps its - deadline, and only subsequent allocations check a new memory budget. See + deadline, and only subsequent allocations check a new memory budget. A new CPU + limit reaches running queries at their next CPU slice, and a new scheduling + policy re-queues the work waiting for CPU. See [effect on queries already running](/docs/query/sql/acl/alter-resource-group/#effect-on-queries-already-running). - **A drop is refused while principals are still mapped.** Unmap them first. Once unmapped, the group can be dropped while its queries are still running, and @@ -98,12 +105,25 @@ The accepted values and their defaults are in the What matters when picking them: - **An unset parameter is not always "unlimited".** `cpu_weight` falls back to - 100 and `queue_timeout` to 30 seconds, while the two admission counts really - are unlimited when unset. + 100, `queue_timeout` to 30 seconds and `scheduling_policy` to `fifo`, while + the two admission counts and the CPU limit really are unlimited when unset. - **Weights are only meaningful relative to other groups.** A group at `cpu_weight = 50` gets a third of query CPU while `DEFAULT` also has work, and all of it when `DEFAULT` is idle. Setting a weight on a lone group does nothing. +- **A weight shares, a limit caps.** A weight decides the split while groups + compete and lets a group use what the others leave idle. `cpu_limit` holds a + group to a fixed part of the node even when the rest is idle, so leave it unset + unless the group must never use more. Below its limit a group still competes + by weight. +- **A small limit changes how queries run.** A group limited to one core or less + runs parallel queries single-threaded, and a `CREATE TABLE ... AS SELECT` + keeps one of the group's workers until it finishes. Leave room for short + queries beside a group's copies. See + [A CPU limit is a ceiling](/docs/concepts/resource-groups/#a-cpu-limit-is-a-ceiling-not-a-share). +- **`fair` is opt-in.** `fifo` finishes long batch queries soonest. Switch a + group to `fair` when its users, or its queries, must make progress side by + side. - **No group memory ceiling does not mean unlimited memory.** A principal's own limit, `cairo.query.memory.limit.bytes` and the process budget all still apply, and a group ceiling only ever lowers the result. See @@ -136,7 +156,8 @@ ALTER USER analyst SET RESOURCE GROUP adhoc; ``` `questdb_resource_groups_cpu_managed_dispatch` reports `1` while scheduling is -engaged, which is whenever a group besides `DEFAULT` exists. A query that +engaged, which is whenever a group besides `DEFAULT` exists or any group has a +CPU limit or the `fair` policy. A query that started before the second group was created keeps its worker until it next suspends or finishes, and a query that never reaches a checkpoint holds its worker either way, so this does not remove every cause of an unresponsive @@ -256,6 +277,85 @@ ALTER USER lead_analyst SET RESOURCE GROUP dashboards; those are one-to-one and have nothing to break a tie between. Confirm any of this from the client's own session with `SELECT current_resource_group();`. +### A tenant must never use more than its part of the node + +Capacity sold by the core, or performance that must not change with the +neighbours' load, needs a ceiling rather than a share: + +```questdb-sql +CREATE RESOURCE GROUP tenant_a WITH (cpu_limit = '25%'); +CREATE RESOURCE GROUP tenant_b WITH (cpu_limit = '25%'); + +ALTER SERVICE ACCOUNT tenant_a_app SET RESOURCE GROUP tenant_a; +ALTER SERVICE ACCOUNT tenant_b_app SET RESOURCE GROUP tenant_b; +``` + +Each tenant uses at most a quarter of the node's CPUs on average, even while +the rest of the node is idle, and `cpu_limit_cores` in +[`resource_groups()`](/docs/query/functions/meta/#resource_groups) shows what +that comes to on this node. Below their limits the tenants still compete by +weight. A limit also leaves the remaining CPU to work outside resource groups, +such as ingestion. + +Size the limit for the tenant's heaviest statements. A +`CREATE TABLE ... AS SELECT` keeps one of the group's workers until it +finishes, and a limit of one core or less runs every parallel query of the +group single-threaded. See +[A CPU limit is a ceiling](/docs/concepts/resource-groups/#a-cpu-limit-is-a-ceiling-not-a-share). + +### One user's queries crowd out the rest of a team + +In the default `fifo` order, a user who starts several long queries holds the +group's workers while everyone else's queries wait behind them. Divide the +group between its users instead: + +```questdb-sql +ALTER RESOURCE GROUP analysts SET (scheduling_policy = 'fair'); +``` + +Busy users now split the group evenly, and one user alone can still use all of +it. With `max_active_queries` set, admission also takes the user with the fewest +admitted queries first, so one user's queue no longer keeps the others out. See +[the scheduling policy](/docs/concepts/resource-groups/#the-scheduling-policy-divides-a-group-between-its-users). + +### One account sends both urgent and routine queries + +A monitoring account that evaluates alert rules and serves dashboards needs the +alerts to win, while its mapping gives it one group. Let the account choose: + +```questdb-sql +CREATE RESOURCE GROUP alerts WITH (cpu_weight = 400); +CREATE RESOURCE GROUP dashboards WITH (cpu_weight = 100); + +ALTER USER monitoring SET RESOURCE GROUP dashboards; +GRANT USE ON RESOURCE GROUP alerts TO monitoring; +``` + +The connections that evaluate alert rules run `SET RESOURCE GROUP alerts` once +after connecting, and an HTTP client sends `resource_group=alerts` with each +alert query instead. Everything else stays in `dashboards`. Other users cannot +choose `alerts` without the same grant, so the heavier group stays reserved for +the work you grant it to. A connection pooler that resets sessions with +`DISCARD ALL` or `RESET ALL` clears the choice as well. See +[SET RESOURCE GROUP](/docs/query/sql/acl/set-resource-group/). + +### Operators need a protected share + +Give operators an ordinary group with a small weight: + +```questdb-sql +CREATE RESOURCE GROUP ops WITH (cpu_weight = 5); + +ALTER USER dba SET RESOURCE GROUP ops; +``` + +While every group is busy, `ops` receives its percentage of all weights, which +`cpu_min_share_pct` shows, and more when other groups are idle. The built-in +admin needs no grant to run `SET RESOURCE GROUP ops`. Management statements do +not depend on the share at all: only queries are managed, so statements such as +`ALTER RESOURCE GROUP` and `CANCEL QUERY` never wait for a group's admission or +CPU. + ## Inspecting [`resource_groups()`](/docs/query/functions/meta/#resource_groups) returns one @@ -268,6 +368,40 @@ that matter day to day: is busy. - `admission_rejections` and `admission_timeouts` for work already turned away. - `memory_used_bytes` against `memory_limit_bytes` for headroom. +- `cpu_min_share_pct` for the share of query CPU each group can count on while + every group has work, and `cpu_limit_pct`, `cpu_limit_cores` and + `scheduling_policy` for its CPU limit and policy. + +Weights are relative, so they need not add up to 100, but weights that do read +directly as percentages: + +```questdb-sql title="A share scheme in percent" +ALTER RESOURCE GROUP DEFAULT SET (cpu_weight = 1); +CREATE RESOURCE GROUP ops WITH (cpu_weight = 5); +CREATE RESOURCE GROUP trading WITH ( + cpu_weight = 45, + scheduling_policy = 'fair' +); +CREATE RESOURCE GROUP research WITH (cpu_weight = 49, cpu_limit = '75%'); + +SELECT name, cpu_weight, cpu_min_share_pct, cpu_limit_pct, cpu_limit_cores, + scheduling_policy +FROM resource_groups() +ORDER BY name; +``` + +On a node with 16 CPUs: + +| name | cpu_weight | cpu_min_share_pct | cpu_limit_pct | cpu_limit_cores | scheduling_policy | +| -------- | ---------- | ----------------- | ------------- | --------------- | ----------------- | +| DEFAULT | 1 | 1.0 | 0 | 0.0 | fifo | +| ops | 5 | 5.0 | 0 | 0.0 | fifo | +| research | 49 | 49.0 | 75 | 12.0 | fifo | +| trading | 45 | 45.0 | 0 | 0.0 | fair | + +Weights start at 1, so `DEFAULT` takes at least one point of a scheme that adds +up to 100. `research` can use idle CPU up to 12 cores, while the other groups can +use all of it. Mappings are attributes of the principals themselves. `SHOW USERS` and `SHOW SERVICE ACCOUNTS` carry a `resource_group` column, and `SHOW GROUPS` @@ -326,19 +460,54 @@ settings are rejecting work the application expects to succeed. | `query memory limit exceeded` | A single-query, group or process memory limit rejected an allocation | `scope` in the message names the level: `query`, `group` or `process`. Reduce memory use or raise that limit | | `Resource Group is assigned to an ACL entity` | `DROP RESOURCE GROUP` while principals are still mapped | `UNSET RESOURCE GROUP` on those principals first; the message names one of them in `[entity=...]` | | `built-in Resource Group cannot be dropped` / `cannot be renamed` | `DROP` or `RENAME` on `DEFAULT` | Alter it instead | +| `Access denied for [USE RESOURCE GROUP on ]` | The session or request chose a group the principal may not use, or the permission was revoked since | `GRANT USE ON RESOURCE GROUP`, or `RESET RESOURCE GROUP` to return to the mapped group | +| `Resource Group does not exist [name=...]` | `SET RESOURCE GROUP` named a group that does not exist | Correct the name | +| `Resource Group chosen by SET RESOURCE GROUP or the resource_group parameter does not exist` | The session's group was dropped, or the `resource_group` parameter names no group | `SET RESOURCE GROUP` to an existing group, `RESET RESOURCE GROUP`, or correct the parameter | +| `Resource Group switching needs a session, ...` | `SET RESOURCE GROUP` sent over HTTP or another connection without a session | Send the `resource_group` parameter with the HTTP request | +| `SET LOCAL RESOURCE GROUP is not supported, ...` | `SET LOCAL` used for a group, which applies to the whole session | Use `SET RESOURCE GROUP` | ## Troubleshooting **A group's CPU share is not what I configured.** Weights only apply while groups compete. Check `active_queries` on both groups at the same moment: if one -is idle, the other is expected to use everything. A query that started before -the second group was created stays outside CPU scheduling until it next suspends -or finishes; every other query starts sharing at its next checkpoint. Also +is idle, the other is expected to use everything, unless it has a CPU limit. A +query that started before CPU scheduling engaged stays outside it until it next +suspends or finishes; every other query starts sharing at its next checkpoint. +Also confirm the work you are watching is managed at all, since ingestion, WAL apply and view refresh are outside the feature. `query_activity()` shows the group each running query belongs to, which is the quickest way to tell whether the load you are watching is attributed where you expect. +**A group with a CPU limit waits while the node is idle.** That is the +difference between a limit and a weight: a limit holds even when nothing else +runs. Compare the group's use with `cpu_limit_cores`. If the group should use +idle CPU, raise the limit or remove it with `RESET (cpu_limit)` and rely on its +weight instead. + +**A group uses more CPU than its limit.** The limit counts the CPU that queries +use on their workers, so process-level tools also show garbage collection, JIT +compilation and WAL apply, which no group is charged for. Within the group, +under a fractional limit, a `CREATE TABLE ... AS SELECT` leaves at most about +10 seconds of the limit's CPU to repay however long it ran, so back-to-back +copies can keep a group close to a whole core, and a parallel query above one +core can run past the rate for a moment before it repays it. Compare the growth of `cpu_nanos_total` over a +minute or more with `cpu_limit_cores` rather than reading an instant. + +**A short query waits behind a copy in a group with a limit.** A +`CREATE TABLE ... AS SELECT` keeps one of the group's workers until it finishes, +so when it holds the last one the group may have, the group's other queries wait +for it under either scheduling policy. Raise the limit so the group can hold +more than one worker, or copy with `INSERT ... SELECT` into an existing table, +which gives up its worker like any query. + +**Queries fail after `SET RESOURCE GROUP` succeeded.** The group and the +permission to use it are checked again at the start of every managed query, so +a revoke fails the session's next query. The session remembers the group by +name, so dropping or renaming the group does the same. Choose the group again, +under its new name if it was renamed, or run `RESET RESOURCE GROUP`. See +[errors clients see](#errors-clients-see). + **Queries on a fresh replica are not limited.** Until the catalog has replicated, a replica runs queries unmanaged and counts them in `questdb_resource_groups_catalog_lag_unmanaged_queries_total`. The counter stops @@ -387,6 +556,32 @@ running. - Principal mapping changes affect new queries. Group budgets change online; dropping a group retains its runtime state for existing queries until they finish. See [changing a live instance](#changing-a-live-instance). +- A CPU limit holds on average, not at every instant. A fractional limit lets a + group run about 100 milliseconds of its rate ahead, a parallel query above + one core can run past the rate before it repays it, and while every running + query of a group is a statement that cannot give up its worker, such as a + `CREATE TABLE ... AS SELECT`, the group may run one parallel task beyond its + limit so that work already handed out does not hold up other groups. See + [A CPU limit is a ceiling](/docs/concepts/resource-groups/#a-cpu-limit-is-a-ceiling-not-a-share). +- In a group with a CPU limit, a `CREATE TABLE ... AS SELECT` runs + single-threaded and keeps its worker until it finishes. Under a fractional + limit it leaves the group at most about 10 seconds of the limit's CPU to + repay, so back-to-back copies can keep a group close to a whole core however + small its limit. In a group without a limit, its parallel tasks are not + charged to the group. +- A statement waiting for its group's CPU budget keeps its locks, such as the + table writer of an `INSERT ... SELECT`. +- `fair` has no weights between users, and `cpu_limit` applies to a whole group, + not to one user. A user who needs a different share or a cap of its own needs + its own group. +- With resource groups enabled, the instance keeps as many reduce queues + reserved for groups with a CPU limit as it has shared ones, at about 2.3 KB of + native memory per queue slot: about 150 KB with 4 query workers, and about 2.3 + MB at the largest default queue size. Each group takes the next reserved queue + the first time it runs a query under a limit and keeps it, so groups start to + share reserved queues once more groups have taken one than there are queues, + counting groups that were dropped since. A parallel query that started before + its group had a limit stays on a shared queue until it finishes. ## See also @@ -395,5 +590,6 @@ running. - [CREATE RESOURCE GROUP](/docs/query/sql/acl/create-resource-group/) - [ALTER RESOURCE GROUP](/docs/query/sql/acl/alter-resource-group/) - [DROP RESOURCE GROUP](/docs/query/sql/acl/drop-resource-group/) +- [SET RESOURCE GROUP](/docs/query/sql/acl/set-resource-group/) - [Role-based access control](/docs/security/rbac/) - [Logging and metrics](/docs/operations/logging-metrics/) diff --git a/documentation/operations/upgrade.md b/documentation/operations/upgrade.md index 9063c94d5..b23cfc5cc 100644 --- a/documentation/operations/upgrade.md +++ b/documentation/operations/upgrade.md @@ -120,6 +120,23 @@ QuestDB Enterprise 4.2.0 adds - Going back to 4.1.0 or earlier after 4.2.0 has run is limited, see [Downgrade to an earlier release](/docs/concepts/durability/#downgrade). +It also adds [CPU limits](/docs/concepts/resource-groups/#a-cpu-limit-is-a-ceiling-not-a-share), +[fair scheduling](/docs/concepts/resource-groups/#the-scheduling-policy-divides-a-group-between-its-users) +and [per-session group choice](/docs/query/sql/acl/set-resource-group/) to +resource groups: + +- Existing groups keep `fifo` order and no CPU limit, so nothing changes until + you set the new parameters. CPU sharing between groups now holds its weights + over time: a group that used CPU the others left idle no longer pays for it + when they return, which on earlier releases could stall it for longer the + longer the instance had run. +- With resource groups enabled, the instance keeps reduce queues reserved for + groups with a CPU limit, at about 150 KB to 2.3 MB of additional native + memory. See [Limitations](/docs/operations/resource-groups/#limitations). +- The primary adds the `cpu_limit_pct` and `scheduling_policy` columns to the + resource group catalog. A replica upgraded before its primary reads the + catalog without them until the primary has migrated it. + ### Upgrading to 4.1.0 QuestDB Enterprise 4.1.0 hides tables and views from principals that hold no diff --git a/documentation/query/functions/access-control.md b/documentation/query/functions/access-control.md index 7be2bf1d6..821536422 100644 --- a/documentation/query/functions/access-control.md +++ b/documentation/query/functions/access-control.md @@ -47,7 +47,10 @@ groups, use [`active_permissions()`](#active_permissions). - `table_name` (`STRING`): table the permission is granted on. `null` for a permission granted at database level: a database permission such as `CREATE TABLE`, or a grant on all tables such as - `GRANT SELECT ON ALL TABLES`. + `GRANT SELECT ON ALL TABLES`. For `USE RESOURCE GROUP` granted on one group + with + [`GRANT USE ON RESOURCE GROUP`](/docs/query/sql/acl/grant/#grant-use-of-resource-groups), + the group's current name. - `column_name` (`STRING`): column the permission is granted on. `null` for a permission granted on a whole table or at database level. - `grant_option` (`BOOLEAN`): `true` if the entity can grant the permission at diff --git a/documentation/query/functions/meta.md b/documentation/query/functions/meta.md index a7f57935d..0f310e8fd 100644 --- a/documentation/query/functions/meta.md +++ b/documentation/query/functions/meta.md @@ -137,7 +137,10 @@ group, while `null` says the feature was not in force for that query. The group is resolved when the query starts and stays fixed for its lifetime, including across the pages of a suspended cursor. Changing a mapping affects the -next query, never one already running. +next query, never one already running. A session that chose a group with +[`SET RESOURCE GROUP`](/docs/query/sql/acl/set-resource-group/), or a request +that sent the `resource_group` parameter, sees the chosen group instead of the +mapped one. **Confirming a mapping end to end:** @@ -723,12 +726,27 @@ Returns a table with these columns: | `cpu_wait_nanos_total` | `LONG` | Cumulative time queries spent waiting for CPU, in nanoseconds | | `admission_rejections` | `LONG` | Cumulative queue-full rejections | | `admission_timeouts` | `LONG` | Cumulative admission timeouts | +| `cpu_min_share_pct` | `DOUBLE` | `cpu_weight` as a percentage of the weights of all groups: the share of query CPU the group can count on while every group has work | +| `cpu_limit_pct` | `INT` | CPU limit as a percentage of the node's CPUs; `0` when the group sets none | +| `cpu_limit_cores` | `DOUBLE` | What `cpu_limit_pct` comes to in cores on this node; `0.0` when the group sets no limit | +| `scheduling_policy` | `VARCHAR` | How the group divides its CPU between its users and queries: `fifo` or `fair` | The policy columns do not all report the same thing. `max_active_queries` and `max_queued_queries` show what the group itself sets, and are `null` when it sets -nothing. `memory_limit_bytes`, `queue_timeout_millis` and `cpu_weight` show the -effective value after instance defaults and the process budget have been applied, -so they are never `null`. +nothing. `memory_limit_bytes`, `queue_timeout_millis`, `cpu_weight` and +`scheduling_policy` show the effective value after instance defaults and the +process budget have been applied, so they are never `null`. `cpu_limit_pct` and +`cpu_limit_cores` report `0` for a group without a CPU limit. + +The `cpu_min_share_pct`, `cpu_limit_pct`, `cpu_limit_cores` and +`scheduling_policy` columns are available from QuestDB Enterprise 4.2.0. They +follow the existing columns, so a client that reads columns by position keeps +working. + +`cpu_limit_cores` is computed from the CPUs available to the QuestDB process, +so the same percentage reads differently on nodes of different sizes, or in a +container with a CPU limit. `cpu_min_share_pct` changes whenever a group is +created, dropped or reweighted, because it is relative to all weights. **Inspecting group policy:** @@ -775,16 +793,39 @@ A high `queued_queries` with a rising `oldest_queue_wait_millis` means work is being held at the admission gate rather than by a busy machine, which is the signal that distinguishes a concurrency limit from a slow query. +**Inspecting CPU policy:** + +```questdb-sql title="Each group's guaranteed share, ceiling and scheduling policy" +SELECT name, cpu_weight, cpu_min_share_pct, cpu_limit_pct, cpu_limit_cores, + scheduling_policy +FROM resource_groups() +ORDER BY name; +``` + +With the `reporting` group above and a `tenant_a` group created with +`cpu_limit = '25%'` and `scheduling_policy = 'fair'`, on a node with 16 CPUs: + +| name | cpu_weight | cpu_min_share_pct | cpu_limit_pct | cpu_limit_cores | scheduling_policy | +| --------- | ---------- | ----------------- | ------------- | --------------- | ----------------- | +| DEFAULT | 100 | 40.0 | 0 | 0.0 | fifo | +| reporting | 50 | 20.0 | 0 | 0.0 | fifo | +| tenant_a | 100 | 40.0 | 25 | 4.0 | fair | + +While all three groups have work, `reporting` can count on a fifth of query +CPU. `tenant_a` uses at most 4 cores on average, even when the other groups are +idle. + **Constraints and edge cases:** - Counters describe the current runtime. They reset when the instance restarts, and recreating a group under the same name starts it from zero. - `cpu_nanos_total` counts only CPU that managed scheduling actually measured, so it is a floor rather than a full account of query CPU. While `DEFAULT` is the - only group, scheduling is disengaged and nothing is sampled, so the column sits - at `0` however busy the instance is. It also undercounts once scheduling is - engaged: a query already running when a second group was created stays outside - scheduling until it next suspends or finishes, and a scheduler that has + only group and has no CPU limit or `fair` policy, scheduling is disengaged and + nothing is sampled, so the column sits at `0` however busy the instance is. It + also undercounts once scheduling is engaged: a query already running when + scheduling engaged stays outside it until it next suspends or finishes, and a + scheduler that has degraded after an internal fault stops sampling from then on, which `questdb_resource_groups_cpu_scheduler_degraded` reports as `1`. - `memory_used_bytes` can lag real usage, because workers accumulate allocation diff --git a/documentation/query/sql/acl/alter-group-set-resource-group.md b/documentation/query/sql/acl/alter-group-set-resource-group.md index fb5eaf70d..f789d9472 100644 --- a/documentation/query/sql/acl/alter-group-set-resource-group.md +++ b/documentation/query/sql/acl/alter-group-set-resource-group.md @@ -32,6 +32,12 @@ Mapping an ACL group is how you cover a team without naming each member. It requires the [`RESOURCE GROUP ADMIN`](/docs/security/rbac/#permissions) permission, and affects queries that start after the change rather than one already running. +The mapping decides the group a member's sessions start in. A member can still +run a session's queries in another group with +[`SET RESOURCE GROUP`](/docs/query/sql/acl/set-resource-group/) given +`USE RESOURCE GROUP` on it, which can be granted to the ACL group to cover every +member. + This is workload mapping: it decides how much of the instance the group's queries may consume. It is unrelated to [`WITH EXTERNAL ALIAS`](/docs/query/sql/acl/alter-group-with-external-alias/), diff --git a/documentation/query/sql/acl/alter-resource-group.md b/documentation/query/sql/acl/alter-resource-group.md index a659915e1..cf3e64d5a 100644 --- a/documentation/query/sql/acl/alter-resource-group.md +++ b/documentation/query/sql/acl/alter-resource-group.md @@ -2,9 +2,9 @@ title: ALTER RESOURCE GROUP reference sidebar_label: ALTER RESOURCE GROUP description: - "ALTER RESOURCE GROUP changes a group's admission, CPU weight and memory - policy, clears parameters, or renames the group. Applies to QuestDB - Enterprise." + "ALTER RESOURCE GROUP changes a group's admission, CPU weight, CPU limit, + scheduling and memory policy, clears parameters, or renames the group. + Applies to QuestDB Enterprise." --- import { EnterpriseNote } from "@site/src/components/EnterpriseNote" @@ -38,15 +38,17 @@ ALTER RESOURCE GROUP groupName RENAME TO newName; The parameters are the same ones [`CREATE RESOURCE GROUP`](/docs/query/sql/acl/create-resource-group/#parameters) -accepts: `cpu_weight`, `max_active_queries`, `max_queued_queries`, -`queue_timeout` and `memory_limit`. +accepts: `cpu_limit`, `cpu_weight`, `max_active_queries`, `max_queued_queries`, +`memory_limit`, `queue_timeout` and `scheduling_policy`. ## Description `SET` changes only the parameters named; anything else the group already sets is left alone. `RESET` clears a parameter so it falls back to the instance default, which is not always "unlimited": `RESET (cpu_weight)` returns the group to a -weight of 100, and `RESET (queue_timeout)` returns it to 30 seconds. +weight of 100, `RESET (queue_timeout)` returns it to 30 seconds, and +`RESET (scheduling_policy)` returns it to `fifo`. `RESET (cpu_limit)` removes +the CPU limit, as `SET (cpu_limit = '0%')` does. The statement requires the [`RESOURCE GROUP ADMIN`](/docs/security/rbac/#permissions) permission. @@ -64,22 +66,41 @@ moment `ALTER` executes: | Change | Effect on existing work | | ---------------------- | ------------------------------------------------------------------------------------------------- | +| `cpu_limit` | Running and waiting queries are held to the new limit from their next CPU slice | | `cpu_weight` | Subsequent scheduling uses the new policy | | `max_active_queries` | Existing slots are retained; subsequent admission, including a resumed cursor, uses the new limit | | `max_queued_queries`, `queue_timeout` | New admission requests use the new settings; an already queued request keeps its deadline | | `memory_limit` | Subsequent allocations check the new budget; existing memory is released normally | +| `scheduling_policy` | Work waiting for CPU is re-queued under the new policy in arrival order; subsequent admission uses the new policy | Lowering `memory_limit` below current usage does not fail running queries retroactively, but it can make their subsequent allocations fail. The single-query ceiling is captured when a query starts, so changing the group budget does not replace a principal's own limit. +A query that starts under a CPU limit puts its parallel work on reduce queues +reserved for limited groups, so waiting for its group's budget does not hold up +the queries of groups without a limit. A parallel query that was already running +when the limit appeared stays on the shared queue it started on until it +finishes, and can hold up other queries there while it waits. + ## Examples ```questdb-sql title="Raise the weight and cap concurrency" ALTER RESOURCE GROUP analytics SET (cpu_weight = 300, max_active_queries = 8); ``` +```questdb-sql title="Cap the group at half the node and share it fairly between its users" +ALTER RESOURCE GROUP analytics SET ( + cpu_limit = '50%', + scheduling_policy = 'fair' +); +``` + +```questdb-sql title="Remove the CPU limit and return to arrival order" +ALTER RESOURCE GROUP analytics RESET (cpu_limit, scheduling_policy); +``` + ```questdb-sql title="Remove the group's memory ceiling" ALTER RESOURCE GROUP reporting SET (memory_limit = UNLIMITED); ``` diff --git a/documentation/query/sql/acl/alter-service-account-set-resource-group.md b/documentation/query/sql/acl/alter-service-account-set-resource-group.md index b5312cdb7..fce597d8c 100644 --- a/documentation/query/sql/acl/alter-service-account-set-resource-group.md +++ b/documentation/query/sql/acl/alter-service-account-set-resource-group.md @@ -39,6 +39,12 @@ The statement requires the [`RESOURCE GROUP ADMIN`](/docs/security/rbac/#permissions) permission, and affects queries that start after the change rather than one already running. +The mapping decides the group the account's sessions start in. A session can +still run its queries in another group with +[`SET RESOURCE GROUP`](/docs/query/sql/acl/set-resource-group/), or an HTTP +request with the `resource_group` parameter, if the account holds +`USE RESOURCE GROUP` on it. The mapped group needs no such grant. + This governs the queries the account runs. It does not throttle ingestion, which resource groups do not manage. diff --git a/documentation/query/sql/acl/alter-user-set-resource-group.md b/documentation/query/sql/acl/alter-user-set-resource-group.md index a7627b114..b4defd623 100644 --- a/documentation/query/sql/acl/alter-user-set-resource-group.md +++ b/documentation/query/sql/acl/alter-user-set-resource-group.md @@ -39,6 +39,12 @@ The statement requires the [`RESOURCE GROUP ADMIN`](/docs/security/rbac/#permissions) permission, and affects queries that start after the change rather than one already running. +The mapping decides the group the user's sessions start in. A session can still +run its queries in another group with +[`SET RESOURCE GROUP`](/docs/query/sql/acl/set-resource-group/), or an HTTP +request with the `resource_group` parameter, if the user holds +`USE RESOURCE GROUP` on it. The mapped group needs no such grant. + ## Examples ```questdb-sql diff --git a/documentation/query/sql/acl/create-resource-group.md b/documentation/query/sql/acl/create-resource-group.md index 877fc04f3..11d59a72e 100644 --- a/documentation/query/sql/acl/create-resource-group.md +++ b/documentation/query/sql/acl/create-resource-group.md @@ -3,7 +3,8 @@ title: CREATE RESOURCE GROUP reference sidebar_label: CREATE RESOURCE GROUP description: "CREATE RESOURCE GROUP creates a query workload policy setting admission, CPU - weight and memory limits. Applies to QuestDB Enterprise." + weight, CPU limit, scheduling policy and memory limits. Applies to QuestDB + Enterprise." --- import { EnterpriseNote } from "@site/src/components/EnterpriseNote" @@ -32,13 +33,15 @@ CREATE RESOURCE GROUP [IF NOT EXISTS] groupName Every parameter is optional. An unset parameter falls back to the instance default, which is not always "unlimited": -| Parameter | Accepted values | Unset behaviour | -| -------------------- | --------------------------------------------------------------------- | ---------------- | -| `cpu_weight` | integer, 1 to 10000 | 100 | -| `max_active_queries` | integer, 1 or more | unlimited | -| `max_queued_queries` | integer, 0 or more | unlimited | -| `queue_timeout` | whole milliseconds, or a duration such as `'15s'` or `'2m'` | 30 seconds | -| `memory_limit` | a byte size such as `'8G'`, or `0` or `UNLIMITED` for no group ceiling | no group ceiling | +| Parameter | Accepted values | Unset behaviour | +| -------------------- | --------------------------------------------------------------------------------------- | ---------------- | +| `cpu_limit` | a quoted whole-number percentage of the node's CPUs, `'1%'` to `'100%'`, or `'0%'` for none | no limit | +| `cpu_weight` | integer, 1 to 10000 | 100 | +| `max_active_queries` | integer, 1 or more | unlimited | +| `max_queued_queries` | integer, 0 or more | unlimited | +| `memory_limit` | a byte size such as `'8G'`, or `0` or `UNLIMITED` for no group ceiling | no group ceiling | +| `queue_timeout` | whole milliseconds, or a duration such as `'15s'` or `'2m'` | 30 seconds | +| `scheduling_policy` | `'fifo'` or `'fair'`, in any case | `fifo` | ## Description @@ -55,11 +58,31 @@ statement fails, unless `IF NOT EXISTS` is included. The statement requires the [`RESOURCE GROUP ADMIN`](/docs/security/rbac/#permissions) permission. -Creating a second resource group engages CPU scheduling for the whole instance. -While `DEFAULT` is the only group there is no CPU slicing at all, so weights -have no effect until a second group exists. See +Creating a second resource group engages CPU scheduling for the whole instance, +and so does a CPU limit or the `fair` policy on any group. Until then there is +no CPU slicing at all, so weights have no effect while `DEFAULT` is the only +group. See [when scheduling engages](/docs/concepts/resource-groups/#when-scheduling-engages). +`cpu_limit` is a ceiling: the group gets at most that share of the node's CPUs +on average, even while the rest of the node is idle. The percentage +is of the CPUs available to the QuestDB process, and +[`resource_groups()`](/docs/query/functions/meta/#resource_groups) shows what it +comes to on this node in `cpu_limit_cores`. A value without the `%` sign fails +with `CPU limit must be a percentage of the node's CPUs, for example '50%'`, and +a percentage above 100 or with a fraction fails with +`invalid Resource Group policy value`. How the limit is enforced, and when a +group can briefly exceed it, is described in +[A CPU limit is a ceiling](/docs/concepts/resource-groups/#a-cpu-limit-is-a-ceiling-not-a-share). + +`scheduling_policy` decides how the group divides its CPU between its own users +and queries: `fifo` serves them in arrival order, and `fair` divides the group +by user first, then by query. An unknown name fails with +`unknown scheduling policy, expected 'fifo' or 'fair'`. See +[the scheduling policy](/docs/concepts/resource-groups/#the-scheduling-policy-divides-a-group-between-its-users). + +`cpu_limit` and `scheduling_policy` are available from QuestDB Enterprise 4.2.0. + A group ceiling only ever lowers what a query may use. `memory_limit` is capped by `resource.groups.process.memory.limit.bytes`, and it never raises a limit set on the principal or by `cairo.query.memory.limit.bytes`. @@ -85,24 +108,34 @@ CREATE RESOURCE GROUP IF NOT EXISTS exports WITH ( ); ``` +```questdb-sql title="A tenant capped at a quarter of the node, shared fairly by its users" +CREATE RESOURCE GROUP tenant_a WITH ( + cpu_limit = '25%', + scheduling_policy = 'fair' +); +``` + Verify with [`resource_groups()`](/docs/query/functions/meta/#resource_groups): ```questdb-sql -SELECT name, cpu_weight, max_active_queries, memory_limit_bytes +SELECT name, cpu_weight, cpu_limit_pct, scheduling_policy, + max_active_queries, memory_limit_bytes FROM resource_groups() ORDER BY name; ``` -| name | cpu_weight | max_active_queries | memory_limit_bytes | -| --------- | ---------- | ------------------ | ------------------ | -| DEFAULT | 100 | null | 0 | -| analytics | 100 | null | 0 | -| exports | 10 | 1 | 0 | -| reporting | 50 | 4 | 2147483648 | - -`max_active_queries` is `null` when the group sets no admission limit, and -`memory_limit_bytes` is `0` when it sets no memory ceiling. `cpu_weight` always -reports an effective value, so a group that sets none shows `100`. +| name | cpu_weight | cpu_limit_pct | scheduling_policy | max_active_queries | memory_limit_bytes | +| --------- | ---------- | ------------- | ----------------- | ------------------ | ------------------ | +| DEFAULT | 100 | 0 | fifo | null | 0 | +| analytics | 100 | 0 | fifo | null | 0 | +| exports | 10 | 0 | fifo | 1 | 0 | +| reporting | 50 | 0 | fifo | 4 | 2147483648 | +| tenant_a | 100 | 25 | fair | null | 0 | + +`max_active_queries` is `null` when the group sets no admission limit, +`memory_limit_bytes` is `0` when it sets no memory ceiling, and `cpu_limit_pct` +is `0` when it sets no CPU limit. `cpu_weight` and `scheduling_policy` always +report an effective value, so a group that sets neither shows `100` and `fifo`. ## See also diff --git a/documentation/query/sql/acl/grant.md b/documentation/query/sql/acl/grant.md index 5ae6be5fe..93a21042f 100644 --- a/documentation/query/sql/acl/grant.md +++ b/documentation/query/sql/acl/grant.md @@ -44,6 +44,10 @@ table's current columns with an optional `EXCLUDE` list: | * [EXCLUDE (columnName [, columnName ...])] } ``` +```questdb-sql title="Resource group scope" +GRANT USE ON RESOURCE GROUP groupName TO entityName; +``` + ## Description - `GRANT [permissions] TO entity` - grant database level permissions on database @@ -56,6 +60,8 @@ table's current columns with an optional `EXCLUDE` list: permissions on column level to an entity - `GRANT [permissions] ON [table(*)] TO entity` - grant column level permissions on all of the table's current columns, with an optional `EXCLUDE` list +- `GRANT USE ON RESOURCE GROUP [group] TO entity` - allow an entity to run its + queries in one resource group ### Grant database level permissions @@ -194,6 +200,58 @@ timestamp keeps that permission as an ::: +### Grant use of resource groups + +`USE RESOURCE GROUP` lets an entity run its queries in a +[resource group](/docs/concepts/resource-groups/) other than the one it is +mapped to, chosen with +[`SET RESOURCE GROUP`](/docs/query/sql/acl/set-resource-group/) or with the +`resource_group` parameter of an HTTP request. It is available from QuestDB +Enterprise 4.2.0. Grant it for one group: + +```questdb-sql +GRANT USE ON RESOURCE GROUP alerts TO monitoring; +``` + +| permission | table_name | column_name | grant_option | origin | +| ------------------ | ---------- | ----------- | ------------ | ------ | +| USE RESOURCE GROUP | alerts | | f | G | + +Or grant it at database level, for every group: + +```questdb-sql +GRANT USE RESOURCE GROUP TO monitoring; +``` + +| permission | table_name | column_name | grant_option | origin | +| ------------------ | ---------- | ----------- | ------------ | ------ | +| USE RESOURCE GROUP | | | f | G | + +The database-level grant replaces the entity's grants on single groups, as a +grant on all tables replaces table grants, so `alerts` no longer has a row of its +own. + +The two forms are authorized differently: + +- `GRANT USE ON RESOURCE GROUP` takes the + [`RESOURCE GROUP ADMIN`](/docs/security/rbac/#permissions) permission. It + names one group and one entity, and accepts neither `WITH GRANT OPTION` nor + `WITH VERIFICATION`. Both must exist: unlike a table grant, it cannot be + issued ahead of the entity's creation. +- `GRANT USE RESOURCE GROUP` is an ordinary database permission. Granting it + takes the permission with the grant option, and it can itself carry + `WITH GRANT OPTION`. + +A grant to an ACL group covers its members, and the group an entity is mapped to +needs no grant at all. `SHOW PERMISSIONS`, +[`active_grants()`](/docs/query/functions/access-control/#active_grants) and +[`active_permissions()`](/docs/query/functions/access-control/#active_permissions) +show a grant on one group with the group's current name in `table_name`. The +grant follows the group, not its name, so it survives +`ALTER RESOURCE GROUP ... RENAME TO`, and `DROP RESOURCE GROUP` removes it. To +take it away, see +[REVOKE](/docs/query/sql/acl/revoke/#revoke-use-of-resource-groups). + ### Grant option If the `WITH GRANT OPTION` clause is present, then the target entity is allowed diff --git a/documentation/query/sql/acl/revoke.md b/documentation/query/sql/acl/revoke.md index 04f1a28d1..b8f2dd77c 100644 --- a/documentation/query/sql/acl/revoke.md +++ b/documentation/query/sql/acl/revoke.md @@ -40,6 +40,10 @@ table's current columns with an optional `EXCLUDE` list: | * [EXCLUDE (columnName [, columnName ...])] } ``` +```questdb-sql title="Resource group scope" +REVOKE USE ON RESOURCE GROUP groupName FROM entityName; +``` + ## Description - `REVOKE [permissions] FROM entity` - revoke database level permissions from an @@ -53,6 +57,8 @@ table's current columns with an optional `EXCLUDE` list: - `REVOKE [permissions] ON [table(*)] FROM entity` - revoke column level permissions on all of the table's current columns, with an optional `EXCLUDE` list +- `REVOKE USE ON RESOURCE GROUP [group] FROM entity` - revoke the use of one + resource group from an entity ### Revoke database level permissions @@ -117,6 +123,30 @@ permission was originally granted at table level, revoking it from a subset of columns this way triggers [permission level readjustment](#permission-level-readjustment). +### Revoke use of resource groups + +Revoke the use of one resource group, granted with +[`GRANT USE ON RESOURCE GROUP`](/docs/query/sql/acl/grant/#grant-use-of-resource-groups): + +```questdb-sql +REVOKE USE ON RESOURCE GROUP alerts FROM monitoring; +``` + +Like the grant, this form takes the +[`RESOURCE GROUP ADMIN`](/docs/security/rbac/#permissions) permission, and the +group must exist. + +`REVOKE USE RESOURCE GROUP FROM monitoring` revokes the database-level +permission, and with it every grant the entity holds on single groups. +`REVOKE ALL FROM monitoring` and dropping the entity clear them as well, and +`DROP RESOURCE GROUP` removes every grant on the dropped group. + +The permission is checked at the start of every managed query, so a revoke +reaches sessions that already chose the group: their next such query fails with +`Access denied for [USE RESOURCE GROUP on alerts]` until they choose +another group or run `RESET RESOURCE GROUP`. A query already running finishes in +its group. + ### Implicit permissions If the target table has implicit timestamp permissions, then revoking `SELECT` diff --git a/documentation/query/sql/acl/set-resource-group.md b/documentation/query/sql/acl/set-resource-group.md new file mode 100644 index 000000000..2f8a92e1f --- /dev/null +++ b/documentation/query/sql/acl/set-resource-group.md @@ -0,0 +1,177 @@ +--- +title: SET RESOURCE GROUP reference +sidebar_label: SET RESOURCE GROUP +description: + "SET RESOURCE GROUP runs the rest of a session's queries in another resource + group, and RESET RESOURCE GROUP returns to the mapped one. Applies to QuestDB + Enterprise." +--- + +import { EnterpriseNote } from "@site/src/components/EnterpriseNote" + + + Resource groups isolate competing query workloads inside a single QuestDB + instance. + + +`SET RESOURCE GROUP` runs the rest of a session's queries in a resource group +other than the one its principal is mapped to. One account can then send urgent +and routine work to groups with different policies: a monitoring account, for +example, can evaluate its alert rules in a heavily weighted group while its +dashboards stay in an ordinary one. `RESET RESOURCE GROUP` returns the session +to the mapped group. + +HTTP has no SQL session, so a request chooses its group with the +`resource_group` parameter of +[`/execute`](/docs/connect/compatibility/rest-api/#execute) instead, under the +same rules. + +`SET RESOURCE GROUP`, `RESET RESOURCE GROUP` and the `resource_group` parameter +are available from QuestDB Enterprise 4.2.0. + +For how a query is assigned to a group otherwise, see +[who a resource group applies to](/docs/concepts/resource-groups/#who-a-resource-group-applies-to). + +--- + +## Syntax + +```questdb-sql title="Choose a group for the rest of the session" +SET [SESSION] RESOURCE GROUP groupName; +``` + +```questdb-sql title="Return to the mapped group" +RESET RESOURCE GROUP; +``` + +`SESSION` is optional and changes nothing. + +## Description + +The chosen group applies to every query the session starts afterwards, until +`RESET RESOURCE GROUP`, `RESET ALL` or `DISCARD ALL`, or until the session ends. +It replaces the principal's mapping: the group's admission, CPU and memory +policy apply exactly as they would to a principal mapped to it, and +[`current_resource_group()`](/docs/query/functions/meta/#current_resource_group) +returns its name. A query that started earlier, including a cursor that is +still being paged, keeps the group it started in. + +Like a mapping, the choice governs only the statements that resource groups +manage, such as `SELECT`. See +[which statements are managed](/docs/concepts/resource-groups/#which-statements-are-managed). + +`SET LOCAL RESOURCE GROUP` fails with +`SET LOCAL RESOURCE GROUP is not supported, use SET RESOURCE GROUP to switch the session`, +because the group applies to the whole session, not to one transaction. Any +other statement that starts with `SET RESOURCE` or `RESET RESOURCE` fails as +well, so a misspelled statement is reported instead of being accepted and +ignored like an unknown PostgreSQL setting. A setting written as +`SET resource_group = alerts` is not this statement: QuestDB accepts and ignores +it like any other unknown PostgreSQL setting, and the session's group does not +change. + +### Which connections can switch + +Only a PostgreSQL wire connection has a SQL session. On any other connection the +statement fails with +`Resource Group switching needs a session, over HTTP send the group in the resource_group parameter of /exec`. +Over HTTP, send the group with each request, as in the +[example below](#choose-the-group-for-one-http-request). + +### Permissions + +The group the principal is mapped to, or `DEFAULT` for an unmapped principal, +needs no permission. Any other group needs `USE RESOURCE GROUP` on it, granted +for one group or for all of them. That includes `DEFAULT` for a principal that +is mapped to another group. + +```questdb-sql title="Allow one group, or every group" +GRANT USE ON RESOURCE GROUP alerts TO monitoring; +GRANT USE RESOURCE GROUP TO monitoring; +``` + +The built-in admin and principals holding `DATABASE ADMIN` can use every group, +and a grant to an ACL group covers its members. In a session that has +[assumed a service account](/docs/query/sql/acl/assume-service-account/), the +user who logged in decides: both the mapped group and the permission are that +user's, not the service account's. + +Without the permission, the statement fails with +`Access denied for [USE RESOURCE GROUP on ]`. A group that +does not exist fails with `Resource Group does not exist [name=]`. + +The permission is checked again at the start of every query that resource +groups manage, not only when the group is chosen. A revoke therefore applies to +the session's next such query, which fails with the same access-denied error +until the session chooses a group it may use or returns to its own. + +The session remembers the group by name. If the group is dropped or renamed, the +next managed query fails with +`Resource Group chosen by SET RESOURCE GROUP or the resource_group parameter does not exist [name=]` +until the session runs `SET RESOURCE GROUP`, with the new name after a rename, +or `RESET RESOURCE GROUP`. A group created later under the old name would be +used instead, subject to the same permission check. + +With access control disabled nothing is checked. Mapping statements need access +control, so on such an instance choosing a group per session or request is the +only way to run queries outside `DEFAULT`. + +### Connection pools + +A connection pooler resets a session with `DISCARD ALL` or `RESET ALL` before it +hands the connection to its next client. Both statements clear the session's +resource group, so the next client starts in the mapped group instead of +inheriting the previous client's choice. + +## Examples + +### Send alerts and dashboards to different groups + +```questdb-sql title="Create the groups and let the account use the urgent one" +CREATE RESOURCE GROUP alerts WITH (cpu_weight = 400); +CREATE RESOURCE GROUP dashboards WITH (cpu_weight = 100); + +ALTER USER monitoring SET RESOURCE GROUP dashboards; +GRANT USE ON RESOURCE GROUP alerts TO monitoring; +``` + +On the connection that evaluates alert rules: + +```questdb-sql title="Run the rest of this session in the alerts group" +SET RESOURCE GROUP alerts; + +SELECT current_resource_group(); +``` + +| current_resource_group | +| ---------------------- | +| alerts | + +Connections that do not switch keep running in `dashboards`, the group +`monitoring` is mapped to. + +### Choose the group for one HTTP request + +```bash title="Run one query in the alerts group" +curl -G --data-urlencode "query=SELECT count() FROM fx_trades;" \ + --data-urlencode "resource_group=alerts" \ + -u "monitoring:my_password" \ + http://localhost:9000/api/v1/sql/execute +``` + +The parameter applies to that request only, and needs the same permission as +`SET RESOURCE GROUP`. + +### Return to the mapped group + +```questdb-sql +RESET RESOURCE GROUP; +``` + +## See also + +- [Choosing a group per session or request](/docs/concepts/resource-groups/#choosing-a-group-per-session-or-request) +- [GRANT USE ON RESOURCE GROUP](/docs/query/sql/acl/grant/#grant-use-of-resource-groups) +- [REVOKE USE ON RESOURCE GROUP](/docs/query/sql/acl/revoke/#revoke-use-of-resource-groups) +- [`current_resource_group()`](/docs/query/functions/meta/#current_resource_group) +- [Configure and use resource groups](/docs/operations/resource-groups/) diff --git a/documentation/security/rbac.md b/documentation/security/rbac.md index 8cdc503c0..47d4d0905 100644 --- a/documentation/security/rbac.md +++ b/documentation/security/rbac.md @@ -1224,6 +1224,7 @@ SELECT * FROM all_permissions(); | SYSTEM ADMIN | Database | System functions (reload_tls, reader_pool, etc.); makes objects [visible](#object-visibility) | | TRUNCATE TABLE | Database | Table | Truncate tables | | UPDATE | Database | Table | Column | Update data | +| USE RESOURCE GROUP | Database | Resource group | Run queries in a resource group chosen with [`SET RESOURCE GROUP`](/docs/query/sql/acl/set-resource-group/); see [GRANT](/docs/query/sql/acl/grant/#grant-use-of-resource-groups) | | VACUUM TABLE | Database | Table | Reclaim storage | ### User management permissions @@ -1313,6 +1314,7 @@ replication role, is an ordinary grantable permission. - [REMOVE USER](/docs/query/sql/acl/remove-user/) - [REVOKE](/docs/query/sql/acl/revoke/) - [REVOKE ASSUME SERVICE ACCOUNT](/docs/query/sql/acl/revoke-assume-service-account/) +- [SET RESOURCE GROUP](/docs/query/sql/acl/set-resource-group/) - [SHOW USER](/docs/query/sql/show/#show-user) - [SHOW USERS](/docs/query/sql/show/#show-users) - [SHOW GROUPS](/docs/query/sql/show/#show-groups) diff --git a/documentation/sidebars.js b/documentation/sidebars.js index 8cb8c72af..adc92e0aa 100644 --- a/documentation/sidebars.js +++ b/documentation/sidebars.js @@ -542,6 +542,7 @@ module.exports = { "query/sql/with", ], }, + "query/sql/acl/set-resource-group", "query/sql/show", "query/sql/snapshot", "query/sql/switch-cold-storage-role", From cd5244b9ab8e746e37ea78ada1ceffb86a82a40a Mon Sep 17 00:00:00 2001 From: victor Date: Wed, 11 Nov 2026 20:31:13 -0800 Subject: [PATCH 2/3] docs(resource-groups): let curl prompt for the password in the HTTP example --- documentation/query/sql/acl/set-resource-group.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/documentation/query/sql/acl/set-resource-group.md b/documentation/query/sql/acl/set-resource-group.md index 2f8a92e1f..987031c51 100644 --- a/documentation/query/sql/acl/set-resource-group.md +++ b/documentation/query/sql/acl/set-resource-group.md @@ -155,12 +155,12 @@ Connections that do not switch keep running in `dashboards`, the group ```bash title="Run one query in the alerts group" curl -G --data-urlencode "query=SELECT count() FROM fx_trades;" \ --data-urlencode "resource_group=alerts" \ - -u "monitoring:my_password" \ + -u monitoring \ http://localhost:9000/api/v1/sql/execute ``` -The parameter applies to that request only, and needs the same permission as -`SET RESOURCE GROUP`. +curl prompts for the password of `monitoring`. The parameter applies to that +request only, and needs the same permission as `SET RESOURCE GROUP`. ### Return to the mapped group From 4923e172e25d04e1ee4591006416ffc8af219e62 Mon Sep 17 00:00:00 2001 From: victor Date: Wed, 11 Nov 2026 21:15:07 -0800 Subject: [PATCH 3/3] docs(resource-groups): correct scope, permissions and limit guarantees - Revoking one group leaves a database-level USE RESOURCE GROUP grant in force; say so on the GRANT, REVOKE and SET RESOURCE GROUP pages. - The session or request choice does not reach COPY ... TO, /exp or QWP queries, and only connection pools that reset sessions clear it. - cpu_min_share_pct ignores CPU limits, a limit only caps, and whole-core limits have no budget; document the one-task waiver on the concept page. - A degraded scheduler stops enforcing limits and fair as well as weights, the built-in admin always runs in DEFAULT, and dropping or renaming a group affects USE grants and sessions that chose it. - Fix the CTAS charging paragraph, the COPY classification, admission slot holding, case-sensitive group names and several stale statements. --- documentation/changelog.mdx | 3 +- documentation/concepts/resource-groups.md | 108 ++++++----- .../connect/compatibility/rest-api.md | 2 +- documentation/operations/logging-metrics.md | 10 +- documentation/operations/resource-groups.md | 156 ++++++++++------ documentation/operations/upgrade.md | 23 +-- documentation/query/functions/meta.md | 12 +- .../sql/acl/alter-group-set-resource-group.md | 7 +- .../query/sql/acl/alter-resource-group.md | 16 +- .../query/sql/acl/create-resource-group.md | 55 +++--- .../query/sql/acl/drop-resource-group.md | 10 +- documentation/query/sql/acl/grant.md | 22 ++- documentation/query/sql/acl/revoke.md | 17 +- .../query/sql/acl/set-resource-group.md | 170 +++++++++++------- documentation/security/rbac.md | 4 +- 15 files changed, 393 insertions(+), 222 deletions(-) diff --git a/documentation/changelog.mdx b/documentation/changelog.mdx index 8d14cc2cf..405f08866 100644 --- a/documentation/changelog.mdx +++ b/documentation/changelog.mdx @@ -42,7 +42,8 @@ This page tracks significant updates to the QuestDB documentation. ### Updated -- [Resource groups](/docs/concepts/resource-groups/) and [Configure and use resource groups](/docs/operations/resource-groups/) - CPU scheduling also engages when any group has a CPU limit or the `fair` policy; a group that returns from idle neither gains nor owes CPU, however long the instance has run; corrected that the parallel tasks of a `CREATE TABLE ... AS SELECT` are not charged to a group without a CPU limit. Added scenarios for a tenant capped at part of the node, a team sharing a group fairly, one account sending urgent and routine queries, and a protected operator share +- [Resource groups](/docs/concepts/resource-groups/) and [Configure and use resource groups](/docs/operations/resource-groups/) - CPU scheduling also engages when any group has a CPU limit or the `fair` policy; a group that returns from idle neither gains nor owes CPU, however long the instance has run; a degraded scheduler stops enforcing CPU limits and the `fair` policy as well as weights. Corrected that the parallel tasks of a `CREATE TABLE ... AS SELECT` are not charged to a group without a CPU limit, that `COPY ... TO` exports are managed, and that a query keeps its admission slot while it waits for CPU. Added scenarios for a tenant capped at part of the node, a team sharing a group fairly, one account sending urgent and routine queries, and a protected operator share +- [DROP RESOURCE GROUP](/docs/query/sql/acl/drop-resource-group/) and [ALTER RESOURCE GROUP](/docs/query/sql/acl/alter-resource-group/) - What dropping or renaming a group does to `USE RESOURCE GROUP` grants and to sessions that chose the group, and that the built-in admin always runs in `DEFAULT` - [REINDEX](/docs/query/sql/reindex/) - Explains that `LOCK EXCLUSIVE` is required and takes the table's writer lock, and that `REINDEX` rebuilds native partitions only: it skips Parquet partitions and rejects a Parquet partition named in `PARTITION` - [CREATE MATERIALIZED VIEW](/docs/query/sql/create-mat-view/#limit-and-window-function-restrictions) - Breaking change in QuestDB 10.2.0 and QuestDB Enterprise 4.2.0: the part of a materialized view's query that reads its base table (this includes a subquery on the base table) can no longer use `LIMIT`, or a window function nested inside an expression, such as `row_number() OVER (ORDER BY timestamp) + 1`. A window function that makes up a whole column was already rejected. A `LIMIT` in a subquery over a *different* table is still allowed - [ALTER TABLE SET TYPE](/docs/query/sql/alter-table-set-type/) - A conversion to non-WAL applies the WAL first, and is refused while it cannot diff --git a/documentation/concepts/resource-groups.md b/documentation/concepts/resource-groups.md index 9e29ea2e7..eccf65dcc 100644 --- a/documentation/concepts/resource-groups.md +++ b/documentation/concepts/resource-groups.md @@ -20,7 +20,7 @@ at once: dashboards that must answer in milliseconds, an ad-hoc analyst, and a nightly report that scans a year of data. When these workloads compete without resource controls, the report can increase dashboard latency. [Common scenarios](/docs/operations/resource-groups/#common-scenarios) walks -through that case and five others as policies you can copy. +through that case and others as policies you can copy. Creating one takes two statements: [`CREATE RESOURCE GROUP`](/docs/query/sql/acl/create-resource-group/) for the @@ -125,9 +125,12 @@ SET RESOURCE GROUP alerts; ``` Choosing a group per session or request is available from QuestDB Enterprise -4.2.0. The chosen group replaces the mapping for every query the session starts -afterwards, until `RESET RESOURCE GROUP`. A group other than the principal's own -requires the `USE RESOURCE GROUP` permission, granted for one group with +4.2.0. The chosen group replaces the mapping for every managed query the session +starts afterwards, until `RESET RESOURCE GROUP`, `RESET ALL` or `DISCARD ALL`, +or until the session ends. It covers only the session's or the request's own +queries: a `COPY ... TO` export, the `/exp` endpoint and clients that query over +QWP keep the mapped group. A group other than the principal's own requires the +`USE RESOURCE GROUP` permission, granted for one group with [`GRANT USE ON RESOURCE GROUP`](/docs/query/sql/acl/grant/#grant-use-of-resource-groups) or for every group with `GRANT USE RESOURCE GROUP`, so users cannot move themselves into a heavier group. The permission is checked at the start of every @@ -143,22 +146,22 @@ Resource groups govern the statements that read data: - `SELECT` - the source query of `CREATE TABLE ... AS SELECT` and `INSERT ... SELECT` -- query exports +- query exports, including `COPY ... TO` Everything else runs outside the feature and consumes no admission slot, CPU grant or group memory budget: `EXPLAIN`, value `INSERT`, `UPDATE`, ordinary DDL, -`COPY`, transaction and session control, ILP and QWP ingestion, WAL apply, -materialized and live view refresh, and QuestDB's own internal SQL. - -For `CREATE TABLE ... AS SELECT` and `INSERT ... SELECT` the group is charged -for reading the source and producing rows, including parallel work. Where -writing a row cannot be separated from producing it, that CPU is charged to the -group as well. The commit, durability and any work handed to writer or WAL -queues are outside the guarantee. The parallel tasks of a -`CREATE TABLE ... AS SELECT` are an exception: they run outside the group and -are not charged to it, unless the group has a CPU limit, in which case the copy -runs them itself on its own thread. See -[A CPU limit is a ceiling](#a-cpu-limit-is-a-ceiling-not-a-share). +`COPY` imports, transaction and session control, ILP and QWP ingestion, WAL +apply, materialized and live view refresh, and QuestDB's own internal SQL. + +`CREATE TABLE ... AS SELECT` and `INSERT ... SELECT` charge the group for +reading the source and producing rows. For `INSERT ... SELECT` that includes its +parallel work. The parallel tasks of a `CREATE TABLE ... AS SELECT` run outside +the group and are not charged to it, unless the group has a CPU limit, in which +case the copy runs them itself on its own thread; see +[A CPU limit is a ceiling](#a-cpu-limit-is-a-ceiling-not-a-share). Where writing +a row cannot be separated from producing it, that CPU is charged to the group as +well. The commit, durability and any work handed to writer or WAL queues are +outside the guarantee. Resource groups account **tracked native query memory**. They do not represent JVM heap, resident set size, memory-mapped table pages or long-lived engine @@ -182,10 +185,13 @@ rejected immediately. A queued query that waits longer than `queue_timeout` fails, and the instance-wide `query.timeout` keeps running while it waits, so whichever of the two expires first ends the wait. -A slot is held only while the query is running on a worker. A protocol cursor -that is suspended between pages releases its slot and passes through the gate -again when the client asks for more rows, so a paging client does not hold -capacity while the application thinks. The consequence is that admission can be +A query keeps its slot for as long as it runs, including while it waits for a +worker or for its group's CPU budget, so a tight +[CPU limit](#a-cpu-limit-is-a-ceiling-not-a-share) also makes the admission +queue grow. A protocol cursor that is suspended between pages is the exception: +it releases its slot and passes through the gate again when the client asks for +more rows, so a paging client does not hold capacity while the application +thinks. The consequence is that admission can be refused on a later page: a client that received its first rows may still see the queue-full or timeout error when it asks for more, and the connection stays usable. @@ -207,13 +213,14 @@ that was running alone starts sharing at its next checkpoint. Weights are relative. 100 and 50 are the same as 2 and 1. [`resource_groups()`](/docs/query/functions/meta/#resource_groups) shows each weight as a percentage of all weights in `cpu_min_share_pct`: the share a group -can count on while every group has work. Adding a group lowers every other -group's percentage, and the column shows by how much. - -Idle CPU is not banked in either direction. A group that becomes active takes -the next free worker and then runs at its share: it gains nothing for the time -it left its share unused, and a group that used the spare CPU meanwhile owes -nothing for it. This holds however long the instance has been running. A +can count on while every group has work, up to its CPU limit if it has one. +Adding a group lowers every other group's percentage, and the column shows by +how much. + +From QuestDB Enterprise 4.2.0, idle CPU is not banked in either direction. A +group that becomes active takes the next free worker and then runs at its +share: it gains nothing for the time it left its share unused, and a group that +used the spare CPU meanwhile owes nothing for it. This holds however long the instance has been running. A group's CPU is counted once for the whole process, so its queries over HTTP and over PostgreSQL draw on the same share. @@ -231,23 +238,35 @@ CREATE RESOURCE GROUP tenant_a WITH (cpu_limit = '25%'); available to the QuestDB process, which respects a container's CPU limit. On 16 CPUs, `'25%'` is 4 cores and `'5%'` is 0.8 of a core. A weight lets a group use CPU that others leave idle; a limit does not, so the group stays at its limit -when the rest of the node has nothing to do. That makes a limit the tool for -capacity sold by the core, for performance that does not change with the -neighbours' load, and for keeping room for work outside resource groups, such as -ingestion. Below its limit a group still competes by weight as usual. CPU -limits are available from QuestDB Enterprise 4.2.0. +when the rest of the node has nothing to do. Use a limit for capacity sold by +the core, or to keep room for work outside resource groups, such as ingestion. +CPU limits are available from QuestDB Enterprise 4.2.0. + +A limit only caps. Below it the group competes by weight as usual, so while +other groups are busy it can get less than its limit. To keep a group at its +limit under contention as well, give it a weight whose `cpu_min_share_pct` is at +least its `cpu_limit_pct`. The limit holds on average over a short window, and it is enforced in two parts: - A group holds at most as many workers at once as its limit rounded up to - whole cores, across every worker pool. A limit of a whole number of cores - needs nothing more, because a worker uses at most one core. + whole cores, across every worker pool, apart from the one exception described + below. A limit that comes to a whole number of cores needs nothing more, + because a worker uses at most one core. - A fractional limit, such as 0.8 or 3.5 cores, adds a CPU budget that refills at the limit's rate. The group can run ahead of the rate by about 100 milliseconds' worth of it, and then waits until the budget has refilled. Idle time is not banked beyond that. +Only some percentages come to whole cores: `'25%'`, `'50%'`, `'75%'` and +`'100%'` on 16 CPUs, but only `'50%'` and `'100%'` on 14. `cpu_limit_cores` in +`resource_groups()` shows what a limit comes to. A whole-core limit has no +budget, so the budget behaviour described below does not apply to it: the group +cannot burst above its rate or carry debt, and only the exception for +statements that cannot give up their worker takes it past its cap. That makes a +whole-core limit the stricter choice for a hard cap. + Only the CPU that queries use on their workers counts. Work outside them, such as garbage collection, JIT compilation and WAL apply, does not, so the process can use more CPU in total than its groups' limits add up to. @@ -269,14 +288,20 @@ group's workers until it finishes. When that is the last worker the group may hold, the group's other queries wait for the copy, under either scheduling policy. +While every running query of a group is a statement like this, the group may +run one parallel task beyond its cap on workers. That task only finishes work +the group's other queries already handed out to shared queues, so that it does +not hold up other groups' queries there. This is the one exception to the cap. + Under a fractional limit a copy's CPU is recorded in full, but the debt such statements leave the group is capped at what its limit refills in 10 seconds. After a long copy the group therefore waits at most about 10 seconds, instead of however long its limit would take to repay the whole copy: about 7 hours for a -one-hour copy under a limit of 0.14 cores. A group that runs long copies back to back can use far more -than its limit as a result: in one measurement on 14 cores, 100-second copies -under `cpu_limit = '1%'` used about 6.5% of the node, close to a whole core. -Under a whole-core limit there is no budget, and a copy only keeps its worker. +one-hour copy under a limit of 0.14 cores. A group that runs long copies back to +back can use far more than its limit as a result: in one measurement on 14 +cores, 100-second copies under `cpu_limit = '1%'` used about 6.5% of the node, +close to a whole core. Under a whole-core limit there is no budget, and a copy +only keeps its worker. `INSERT ... SELECT` gives up its worker like any query, so none of this applies to it. Any statement that waits for the budget keeps its locks while it waits, @@ -372,8 +397,9 @@ engaged its CPU is still charged when the slice ends, but no cooperative limit can shorten that stretch. Faults are contained rather than escalated. If the scheduler itself hits an -internal fault it degrades: queries keep running without CPU grants, admission -and memory limits stay enforced, and +internal fault it degrades: queries keep running without CPU grants, so CPU +weights, CPU limits and the `fair` policy no longer apply, while admission and +memory limits stay enforced, and `questdb_resource_groups_cpu_scheduler_degraded` reports `1` until the instance restarts. A fault in one query affects only that query, leaving other queries and other groups alone, and its CPU is still charged to its group. diff --git a/documentation/connect/compatibility/rest-api.md b/documentation/connect/compatibility/rest-api.md index 689ad2ac2..94105a7b7 100644 --- a/documentation/connect/compatibility/rest-api.md +++ b/documentation/connect/compatibility/rest-api.md @@ -186,7 +186,7 @@ parameters. `POST` is not supported and returns `405`. | `timings` | No | `false` | `true` or `false`. When set to `true`, QuestDB will also include a `timings` property in the response which gives details about the execution times. | | `explain` | No | `false` | `true` or `false`. When set to `true`, QuestDB will also include an `explain` property in the response which gives details about the execution plan. | | `quoteLargeNum` | No | `false` | `true` or `false`. When set to `true`, QuestDB will surround `LONG` type numbers with double quotation marks that will make them parsed as strings. | -| `resource_group` | No | | QuestDB Enterprise 4.2.0 and later. Runs the query in this [resource group](/docs/concepts/resource-groups/), which takes the `USE RESOURCE GROUP` permission unless it is the group the principal is mapped to. The HTTP counterpart of [`SET RESOURCE GROUP`](/docs/query/sql/acl/set-resource-group/), for this request only. | +| `resource_group` | No | | QuestDB Enterprise 4.2.0 and later. Runs the query in this [resource group](/docs/concepts/resource-groups/). A group other than the principal's own, its mapped group or `DEFAULT` when unmapped, takes the `USE RESOURCE GROUP` permission. The name is case-sensitive except `DEFAULT`, and it is checked when the query starts, so a statement that resource groups do not manage ignores it. The HTTP counterpart of [`SET RESOURCE GROUP`](/docs/query/sql/acl/set-resource-group/#permissions), for this request only; `/exp` does not take it. | The parameters must be URL encoded. diff --git a/documentation/operations/logging-metrics.md b/documentation/operations/logging-metrics.md index 3875ba0f0..2a96e47e4 100644 --- a/documentation/operations/logging-metrics.md +++ b/documentation/operations/logging-metrics.md @@ -504,12 +504,14 @@ Instance-wide series describe the feature itself: | `questdb_resource_groups_enabled` | gauge | `1` when the feature is on | | `questdb_resource_groups_catalog_current` | gauge | `1` when the group catalog is current; `0` while a replica catches up | | `questdb_resource_groups_catalog_lag_unmanaged_queries_total` | counter | Queries that ran unmanaged because the catalog was not current yet | -| `questdb_resource_groups_cpu_managed_dispatch` | gauge | `1` while managed CPU scheduling is engaged | +| `questdb_resource_groups_cpu_managed_dispatch` | gauge | `1` while the groups and their policies require CPU scheduling | | `questdb_resource_groups_cpu_scheduler_degraded` | gauge | `1` after an internal fault has disengaged CPU scheduling | -A non-zero `questdb_resource_groups_cpu_scheduler_degraded` means CPU shares are -no longer enforced until the instance restarts. Admission and memory limits stay -enforced. +A non-zero `questdb_resource_groups_cpu_scheduler_degraded` means CPU weights, +CPU limits and the `fair` policy are no longer enforced until the instance +restarts. Admission and memory limits stay enforced. +`questdb_resource_groups_cpu_managed_dispatch` stays at `1` in that state, +because it reports whether scheduling is required, not whether it works. ### Prometheus Alertmanager diff --git a/documentation/operations/resource-groups.md b/documentation/operations/resource-groups.md index 2e061b6f3..0213322ac 100644 --- a/documentation/operations/resource-groups.md +++ b/documentation/operations/resource-groups.md @@ -80,7 +80,8 @@ Three things are worth knowing before you change policy on a running system: - **Changes apply online.** An `ALTER` does not cancel anything running at that moment. Slots already held are kept, an already queued request keeps its deadline, and only subsequent allocations check a new memory budget. A new CPU - limit reaches running queries at their next CPU slice, and a new scheduling + limit reaches running queries at their next CPU slice, or for a query that was + running before CPU scheduling engaged, when it next suspends. A new scheduling policy re-queues the work waiting for CPU. See [effect on queries already running](/docs/query/sql/acl/alter-resource-group/#effect-on-queries-already-running). - **A drop is refused while principals are still mapped.** Unmap them first. Once @@ -88,7 +89,9 @@ Three things are worth knowing before you change policy on a running system: they carry on under the settings it had. See [what happens to queries still using it](/docs/query/sql/acl/drop-resource-group/#what-happens-to-queries-still-using-it). - **`DEFAULT` is alterable but cannot be dropped or renamed.** Giving it limits - is how you bound everything that is not explicitly mapped. + is how you bound everything that is not explicitly mapped. That includes the + built-in admin, which cannot be mapped and runs in `DEFAULT` unless its + session [chooses another group](/docs/query/sql/acl/set-resource-group/). Mapping changes affect queries that start after the change, never one already running. For the resolution order, including `ASSUME SERVICE ACCOUNT`, see @@ -112,10 +115,14 @@ What matters when picking them: all of it when `DEFAULT` is idle. Setting a weight on a lone group does nothing. - **A weight shares, a limit caps.** A weight decides the split while groups - compete and lets a group use what the others leave idle. `cpu_limit` holds a - group to a fixed part of the node even when the rest is idle, so leave it unset + compete and lets a group use what the others leave idle. `cpu_limit` caps a + group at a part of the node even when the rest is idle, so leave it unset unless the group must never use more. Below its limit a group still competes - by weight. + by weight: if it must also reach its limit while others are busy, give it a + weight whose `cpu_min_share_pct` is at least its `cpu_limit_pct`. +- **Whole cores make the strictest cap.** A limit that comes to a whole number + of cores, such as `'25%'` on 16 CPUs, has no CPU budget, so the group cannot + burst above it or carry debt. `cpu_limit_cores` shows what a limit comes to. - **A small limit changes how queries run.** A group limited to one core or less runs parallel queries single-threaded, and a `CREATE TABLE ... AS SELECT` keeps one of the group's workers until it finishes. Leave room for short @@ -223,8 +230,8 @@ CREATE RESOURCE GROUP exports WITH (cpu_weight = 10, max_active_queries = 1); Under contention the job receives a tenth of the CPU that a group at the default weight of 100 receives, and it runs one query at a time. When nothing else has -work it uses the CPU that would otherwise be idle; resource groups do not hold -CPU back from a group that is alone. +work it uses the CPU that would otherwise be idle; unless it has a CPU limit, +resource groups do not hold CPU back from a group that is alone. ### One workload must not exhaust query memory @@ -279,8 +286,7 @@ this from the client's own session with `SELECT current_resource_group();`. ### A tenant must never use more than its part of the node -Capacity sold by the core, or performance that must not change with the -neighbours' load, needs a ceiling rather than a share: +Capacity sold by the core needs a ceiling rather than a share: ```questdb-sql CREATE RESOURCE GROUP tenant_a WITH (cpu_limit = '25%'); @@ -290,11 +296,14 @@ ALTER SERVICE ACCOUNT tenant_a_app SET RESOURCE GROUP tenant_a; ALTER SERVICE ACCOUNT tenant_b_app SET RESOURCE GROUP tenant_b; ``` -Each tenant uses at most a quarter of the node's CPUs on average, even while -the rest of the node is idle, and `cpu_limit_cores` in +On a node with 16 CPUs each tenant uses at most 4 cores, even while the rest of +the node is idle, and `cpu_limit_cores` in [`resource_groups()`](/docs/query/functions/meta/#resource_groups) shows what -that comes to on this node. Below their limits the tenants still compete by -weight. A limit also leaves the remaining CPU to work outside resource groups, +the limit comes to on a given node. A quarter of 16 CPUs is a whole number of +cores, so the cap has no budget to run ahead of. A limit only caps, though: with +the default weights each tenant's `cpu_min_share_pct` is about 33, above its +limit, so each tenant also gets its 4 cores while `DEFAULT` is busy. The CPU the +tenants cannot use goes to the other groups and to work outside resource groups, such as ingestion. Size the limit for the tenant's heaviest statements. A @@ -331,17 +340,22 @@ ALTER USER monitoring SET RESOURCE GROUP dashboards; GRANT USE ON RESOURCE GROUP alerts TO monitoring; ``` -The connections that evaluate alert rules run `SET RESOURCE GROUP alerts` once -after connecting, and an HTTP client sends `resource_group=alerts` with each -alert query instead. Everything else stays in `dashboards`. Other users cannot -choose `alerts` without the same grant, so the heavier group stays reserved for -the work you grant it to. A connection pooler that resets sessions with -`DISCARD ALL` or `RESET ALL` clears the choice as well. See +The connections that evaluate alert rules come from a pool of their own and run +`SET RESOURCE GROUP alerts` once after connecting. A pool shared with dashboards +would hand a switched connection to dashboard queries, unless it resets every +session with `DISCARD ALL` or `RESET ALL`. An HTTP client sends +`resource_group=alerts` with each alert query instead. Everything else stays in +`dashboards`. Other users cannot choose `alerts` without the same grant, so the +heavier group stays reserved for the work you grant it to. See [SET RESOURCE GROUP](/docs/query/sql/acl/set-resource-group/). ### Operators need a protected share -Give operators an ordinary group with a small weight: +Management statements such as `ALTER RESOURCE GROUP` and `CANCEL QUERY` are not +managed, so they never wait for a group's admission or CPU however busy the +instance is. The queries operators run to diagnose a busy instance, such as +`SELECT * FROM query_activity()` or `resource_groups()`, are managed, so give +them a group of their own: ```questdb-sql CREATE RESOURCE GROUP ops WITH (cpu_weight = 5); @@ -349,12 +363,14 @@ CREATE RESOURCE GROUP ops WITH (cpu_weight = 5); ALTER USER dba SET RESOURCE GROUP ops; ``` -While every group is busy, `ops` receives its percentage of all weights, which -`cpu_min_share_pct` shows, and more when other groups are idle. The built-in -admin needs no grant to run `SET RESOURCE GROUP ops`. Management statements do -not depend on the share at all: only queries are managed, so statements such as -`ALTER RESOURCE GROUP` and `CANCEL QUERY` never wait for a group's admission or -CPU. +While every group is busy, `ops` can count on its `cpu_min_share_pct`, and it +uses more when other groups are idle. Diagnostic queries are light, so a small +weight is enough: what matters is that they do not wait behind the workload. +Leave the group's admission limits unset, so they are not queued either. + +The built-in admin cannot be mapped. It runs in `DEFAULT` unless its session runs +`SET RESOURCE GROUP ops`, which needs no grant, so lowering the weight of +`DEFAULT` also lowers the built-in admin's share. ## Inspecting @@ -369,15 +385,15 @@ that matter day to day: - `admission_rejections` and `admission_timeouts` for work already turned away. - `memory_used_bytes` against `memory_limit_bytes` for headroom. - `cpu_min_share_pct` for the share of query CPU each group can count on while - every group has work, and `cpu_limit_pct`, `cpu_limit_cores` and - `scheduling_policy` for its CPU limit and policy. + every group has work, up to its CPU limit, and `cpu_limit_pct`, + `cpu_limit_cores` and `scheduling_policy` for its CPU limit and policy. Weights are relative, so they need not add up to 100, but weights that do read directly as percentages: ```questdb-sql title="A share scheme in percent" ALTER RESOURCE GROUP DEFAULT SET (cpu_weight = 1); -CREATE RESOURCE GROUP ops WITH (cpu_weight = 5); +CREATE RESOURCE GROUP IF NOT EXISTS ops WITH (cpu_weight = 5); CREATE RESOURCE GROUP trading WITH ( cpu_weight = 45, scheduling_policy = 'fair' @@ -399,9 +415,12 @@ On a node with 16 CPUs: | research | 49 | 49.0 | 75 | 12.0 | fifo | | trading | 45 | 45.0 | 0 | 0.0 | fair | -Weights start at 1, so `DEFAULT` takes at least one point of a scheme that adds -up to 100. `research` can use idle CPU up to 12 cores, while the other groups can -use all of it. +The smallest weight is 1, so `DEFAULT`, which also holds the built-in admin's +queries, takes at least one point of a scheme that adds up to 100. `research` +can count on 49% of query CPU, about 7.8 cores, while every group is busy, and +can use idle CPU up to its limit of 12 cores, while the other groups can use all +of it. `cpu_min_share_pct` does not account for limits: a group whose limit is +below its percentage gets only its limit, and the rest goes to the other groups. Mappings are attributes of the principals themselves. `SHOW USERS` and `SHOW SERVICE ACCOUNTS` carry a `resource_group` column, and `SHOW GROUPS` @@ -445,10 +464,13 @@ meaning is in the [metrics reference](/docs/operations/logging-metrics/#resource-group-metrics). Two signals are worth alerting on: a non-zero -`questdb_resource_groups_cpu_scheduler_degraded`, which means CPU shares are no -longer enforced until the next restart, and a steadily growing -`questdb_resource_group_admission_timeouts_total`, which means a group's queue -settings are rejecting work the application expects to succeed. +`questdb_resource_groups_cpu_scheduler_degraded`, which means CPU weights, CPU +limits and the `fair` policy are no longer enforced until the next restart, and +a steadily growing `questdb_resource_group_admission_timeouts_total`, which +means a group's queue settings are rejecting work the application expects to +succeed. `questdb_resource_groups_cpu_managed_dispatch` stays at `1` after the +scheduler degrades, because it reports whether the groups and their policies +require CPU scheduling, not whether it is working. ## Errors clients see @@ -462,7 +484,7 @@ settings are rejecting work the application expects to succeed. | `built-in Resource Group cannot be dropped` / `cannot be renamed` | `DROP` or `RENAME` on `DEFAULT` | Alter it instead | | `Access denied for [USE RESOURCE GROUP on ]` | The session or request chose a group the principal may not use, or the permission was revoked since | `GRANT USE ON RESOURCE GROUP`, or `RESET RESOURCE GROUP` to return to the mapped group | | `Resource Group does not exist [name=...]` | `SET RESOURCE GROUP` named a group that does not exist | Correct the name | -| `Resource Group chosen by SET RESOURCE GROUP or the resource_group parameter does not exist` | The session's group was dropped, or the `resource_group` parameter names no group | `SET RESOURCE GROUP` to an existing group, `RESET RESOURCE GROUP`, or correct the parameter | +| `Resource Group chosen by SET RESOURCE GROUP or the resource_group parameter does not exist` | The session's group was dropped or renamed, or the `resource_group` parameter names no group; names are case-sensitive except `DEFAULT` | `SET RESOURCE GROUP` to an existing group, `RESET RESOURCE GROUP`, or correct the parameter | | `Resource Group switching needs a session, ...` | `SET RESOURCE GROUP` sent over HTTP or another connection without a session | Send the `resource_group` parameter with the HTTP request | | `SET LOCAL RESOURCE GROUP is not supported, ...` | `SET LOCAL` used for a group, which applies to the whole session | Use `SET RESOURCE GROUP` | @@ -473,7 +495,8 @@ groups compete. Check `active_queries` on both groups at the same moment: if one is idle, the other is expected to use everything, unless it has a CPU limit. A query that started before CPU scheduling engaged stays outside it until it next suspends or finishes; every other query starts sharing at its next checkpoint. -Also +A degraded scheduler, reported by +`questdb_resource_groups_cpu_scheduler_degraded`, stops sharing altogether. Also confirm the work you are watching is managed at all, since ingestion, WAL apply and view refresh are outside the feature. `query_activity()` shows the group each running query belongs to, which is the quickest way to tell whether the @@ -485,14 +508,22 @@ runs. Compare the group's use with `cpu_limit_cores`. If the group should use idle CPU, raise the limit or remove it with `RESET (cpu_limit)` and rely on its weight instead. -**A group uses more CPU than its limit.** The limit counts the CPU that queries -use on their workers, so process-level tools also show garbage collection, JIT -compilation and WAL apply, which no group is charged for. Within the group, -under a fractional limit, a `CREATE TABLE ... AS SELECT` leaves at most about -10 seconds of the limit's CPU to repay however long it ran, so back-to-back -copies can keep a group close to a whole core, and a parallel query above one -core can run past the rate for a moment before it repays it. Compare the growth of `cpu_nanos_total` over a -minute or more with `cpu_limit_cores` rather than reading an instant. +**A group uses more CPU than its limit.** Measure over a minute or more rather +than reading an instant: sample `cpu_nanos_total` twice and divide the +difference by the elapsed nanoseconds to get the cores the group used, which +compares directly with `cpu_limit_cores`. The counter covers the CPU that +queries use on their workers; process-level tools also show garbage collection, +JIT compilation and WAL apply, which no group is charged for. Under a fractional +limit a group can also exceed its rate on purpose: a parallel query above one +core runs past it for a moment before it repays it, and back-to-back +`CREATE TABLE ... AS SELECT` copies can keep a group close to a whole core. A +limit that comes to whole cores avoids both. + +**Queries queue at admission in a group with a CPU limit.** A query keeps its +admission slot while it waits for its group's CPU budget, so under a tight limit +`queued_queries` grows although the group uses no more CPU than its limit. Raise +the limit if the wait is too long; raising `max_active_queries` only lets more +queries wait for the same budget. **A short query waits behind a copy in a group with a limit.** A `CREATE TABLE ... AS SELECT` keeps one of the group's workers until it finishes, @@ -561,27 +592,34 @@ running. one core can run past the rate before it repays it, and while every running query of a group is a statement that cannot give up its worker, such as a `CREATE TABLE ... AS SELECT`, the group may run one parallel task beyond its - limit so that work already handed out does not hold up other groups. See + cap. See [A CPU limit is a ceiling](/docs/concepts/resource-groups/#a-cpu-limit-is-a-ceiling-not-a-share). - In a group with a CPU limit, a `CREATE TABLE ... AS SELECT` runs - single-threaded and keeps its worker until it finishes. Under a fractional - limit it leaves the group at most about 10 seconds of the limit's CPU to - repay, so back-to-back copies can keep a group close to a whole core however - small its limit. In a group without a limit, its parallel tasks are not - charged to the group. + single-threaded and keeps its worker until it finishes, and under a + fractional limit back-to-back copies can keep a group close to a whole core + however small its limit. In a group without a limit, its parallel tasks are + not charged to the group. +- A group chosen per session or request does not reach `COPY ... TO` exports, + exports through `/exp`, or queries over QWP, which run in the principal's + mapped group. See + [SET RESOURCE GROUP](/docs/query/sql/acl/set-resource-group/#which-connections-can-switch). - A statement waiting for its group's CPU budget keeps its locks, such as the table writer of an `INSERT ... SELECT`. - `fair` has no weights between users, and `cpu_limit` applies to a whole group, not to one user. A user who needs a different share or a cap of its own needs its own group. - With resource groups enabled, the instance keeps as many reduce queues - reserved for groups with a CPU limit as it has shared ones, at about 2.3 KB of - native memory per queue slot: about 150 KB with 4 query workers, and about 2.3 - MB at the largest default queue size. Each group takes the next reserved queue - the first time it runs a query under a limit and keeps it, so groups start to - share reserved queues once more groups have taken one than there are queues, - counting groups that were dropped since. A parallel query that started before - its group had a limit stays on a shared queue until it finishes. + reserved for groups with a CPU limit as it has shared ones, which + [`cairo.page.frame.shard.count`](/docs/configuration/parallel-sql-execution/#cairopageframeshardcount) + sets: 4, or the number of query workers if that is smaller. They cost about + 2.3 KB of native memory per queue slot: about 150 KB with 4 query workers, and + about 2.3 MB at the largest default queue size. Each group takes the next + reserved queue the first time it runs a query under a limit and keeps it, so + groups start to share reserved queues once more groups have taken one than + there are queues, counting groups that were dropped since. Groups that share a + reserved queue can hold up each other's parallel queries while one of them + waits for its budget. A parallel query that started before its group had a + limit stays on a shared queue until it finishes. ## See also diff --git a/documentation/operations/upgrade.md b/documentation/operations/upgrade.md index b23cfc5cc..be3a5d75c 100644 --- a/documentation/operations/upgrade.md +++ b/documentation/operations/upgrade.md @@ -122,20 +122,21 @@ QuestDB Enterprise 4.2.0 adds It also adds [CPU limits](/docs/concepts/resource-groups/#a-cpu-limit-is-a-ceiling-not-a-share), [fair scheduling](/docs/concepts/resource-groups/#the-scheduling-policy-divides-a-group-between-its-users) -and [per-session group choice](/docs/query/sql/acl/set-resource-group/) to -resource groups: - -- Existing groups keep `fifo` order and no CPU limit, so nothing changes until - you set the new parameters. CPU sharing between groups now holds its weights - over time: a group that used CPU the others left idle no longer pays for it - when they return, which on earlier releases could stall it for longer the - longer the instance had run. +and [per-session and per-request group choice](/docs/query/sql/acl/set-resource-group/) +to resource groups: + +- CPU limits and fair scheduling change nothing until you set them: existing + groups keep `fifo` order and no CPU limit. One change applies on its own: CPU + sharing between groups now holds its weights over time. A group that used CPU + the others left idle no longer pays for it when they return, which on earlier + releases could stall it for a time that grew with the instance's uptime. See + [CPU weight is a share, not a reservation](/docs/concepts/resource-groups/#cpu-weight-is-a-share-not-a-reservation). - With resource groups enabled, the instance keeps reduce queues reserved for groups with a CPU limit, at about 150 KB to 2.3 MB of additional native memory. See [Limitations](/docs/operations/resource-groups/#limitations). -- The primary adds the `cpu_limit_pct` and `scheduling_policy` columns to the - resource group catalog. A replica upgraded before its primary reads the - catalog without them until the primary has migrated it. +- The primary adds two columns to the internal table that stores resource group + definitions. A replica upgraded before its primary reads that table without + them until the primary has migrated it. ### Upgrading to 4.1.0 diff --git a/documentation/query/functions/meta.md b/documentation/query/functions/meta.md index 0f310e8fd..bba7770c0 100644 --- a/documentation/query/functions/meta.md +++ b/documentation/query/functions/meta.md @@ -726,7 +726,7 @@ Returns a table with these columns: | `cpu_wait_nanos_total` | `LONG` | Cumulative time queries spent waiting for CPU, in nanoseconds | | `admission_rejections` | `LONG` | Cumulative queue-full rejections | | `admission_timeouts` | `LONG` | Cumulative admission timeouts | -| `cpu_min_share_pct` | `DOUBLE` | `cpu_weight` as a percentage of the weights of all groups: the share of query CPU the group can count on while every group has work | +| `cpu_min_share_pct` | `DOUBLE` | `cpu_weight` as a percentage of the weights of all groups: the share of query CPU the group can count on while every group has work, up to its CPU limit | | `cpu_limit_pct` | `INT` | CPU limit as a percentage of the node's CPUs; `0` when the group sets none | | `cpu_limit_cores` | `DOUBLE` | What `cpu_limit_pct` comes to in cores on this node; `0.0` when the group sets no limit | | `scheduling_policy` | `VARCHAR` | How the group divides its CPU between its users and queries: `fifo` or `fair` | @@ -746,7 +746,9 @@ working. `cpu_limit_cores` is computed from the CPUs available to the QuestDB process, so the same percentage reads differently on nodes of different sizes, or in a container with a CPU limit. `cpu_min_share_pct` changes whenever a group is -created, dropped or reweighted, because it is relative to all weights. +created, dropped or reweighted, because it is relative to all weights, and it +does not account for CPU limits: a group whose limit is below its percentage +gets only its limit, and the rest goes to the other groups. **Inspecting group policy:** @@ -795,7 +797,7 @@ signal that distinguishes a concurrency limit from a slow query. **Inspecting CPU policy:** -```questdb-sql title="Each group's guaranteed share, ceiling and scheduling policy" +```questdb-sql title="Each group's share under contention, ceiling and scheduling policy" SELECT name, cpu_weight, cpu_min_share_pct, cpu_limit_pct, cpu_limit_cores, scheduling_policy FROM resource_groups() @@ -813,7 +815,9 @@ With the `reporting` group above and a `tenant_a` group created with While all three groups have work, `reporting` can count on a fifth of query CPU. `tenant_a` uses at most 4 cores on average, even when the other groups are -idle. +idle. That limit is below its 40% share, which would be 6.4 of the 16 CPUs, so +while every group is busy it gets its 4 cores and the rest of its share goes to +`DEFAULT` and `reporting`. **Constraints and edge cases:** diff --git a/documentation/query/sql/acl/alter-group-set-resource-group.md b/documentation/query/sql/acl/alter-group-set-resource-group.md index f789d9472..5ff8c458c 100644 --- a/documentation/query/sql/acl/alter-group-set-resource-group.md +++ b/documentation/query/sql/acl/alter-group-set-resource-group.md @@ -34,9 +34,10 @@ and affects queries that start after the change rather than one already running. The mapping decides the group a member's sessions start in. A member can still run a session's queries in another group with -[`SET RESOURCE GROUP`](/docs/query/sql/acl/set-resource-group/) given -`USE RESOURCE GROUP` on it, which can be granted to the ACL group to cover every -member. +[`SET RESOURCE GROUP`](/docs/query/sql/acl/set-resource-group/), or an HTTP +request with the `resource_group` parameter, given `USE RESOURCE GROUP` on it, +which can be granted to the ACL group to cover every member. The group a member +resolves to through its mappings needs no such grant. This is workload mapping: it decides how much of the instance the group's queries may consume. It is unrelated to diff --git a/documentation/query/sql/acl/alter-resource-group.md b/documentation/query/sql/acl/alter-resource-group.md index cf3e64d5a..e19e5330f 100644 --- a/documentation/query/sql/acl/alter-resource-group.md +++ b/documentation/query/sql/acl/alter-resource-group.md @@ -56,8 +56,13 @@ The statement requires the `DEFAULT` can be altered but not renamed. `ALTER RESOURCE GROUP DEFAULT RENAME TO` fails with `built-in Resource Group cannot be renamed`. -Renaming preserves the policy and every principal mapping, because mappings -attach to the group's identity rather than its name. +Renaming preserves the policy, every principal mapping and every +`USE RESOURCE GROUP` grant on the group, because they attach to the group's +identity rather than its name. A session that chose the group with +[`SET RESOURCE GROUP`](/docs/query/sql/acl/set-resource-group/), or an HTTP +client that sends its name in the `resource_group` parameter, refers to it by +name instead: its next managed query fails until it uses the new name or, for a +session, runs `RESET RESOURCE GROUP`. ### Effect on queries already running @@ -66,12 +71,12 @@ moment `ALTER` executes: | Change | Effect on existing work | | ---------------------- | ------------------------------------------------------------------------------------------------- | -| `cpu_limit` | Running and waiting queries are held to the new limit from their next CPU slice | +| `cpu_limit` | Running and waiting queries are held to the new limit from their next CPU slice. A query that was running before CPU scheduling engaged is reached when it next suspends | | `cpu_weight` | Subsequent scheduling uses the new policy | | `max_active_queries` | Existing slots are retained; subsequent admission, including a resumed cursor, uses the new limit | | `max_queued_queries`, `queue_timeout` | New admission requests use the new settings; an already queued request keeps its deadline | | `memory_limit` | Subsequent allocations check the new budget; existing memory is released normally | -| `scheduling_policy` | Work waiting for CPU is re-queued under the new policy in arrival order; subsequent admission uses the new policy | +| `scheduling_policy` | Work waiting for CPU is re-queued in arrival order and then served under the new policy; subsequent admission uses the new policy | Lowering `memory_limit` below current usage does not fail running queries retroactively, but it can make their subsequent allocations fail. The @@ -116,7 +121,8 @@ ALTER RESOURCE GROUP analytics RENAME TO reporting; ``` `DEFAULT` takes limits like any other group, which is how you bound everything -that is not explicitly mapped: +that is not explicitly mapped, including the built-in admin, which cannot be +mapped: ```questdb-sql title="Cap the default workload" ALTER RESOURCE GROUP DEFAULT SET (max_active_queries = 16); diff --git a/documentation/query/sql/acl/create-resource-group.md b/documentation/query/sql/acl/create-resource-group.md index 11d59a72e..cb51b5fcc 100644 --- a/documentation/query/sql/acl/create-resource-group.md +++ b/documentation/query/sql/acl/create-resource-group.md @@ -14,7 +14,8 @@ import { EnterpriseNote } from "@site/src/components/EnterpriseNote" instance. -`CREATE RESOURCE GROUP` creates a query workload policy. +`CREATE RESOURCE GROUP` creates a query workload policy that bounds the +admission, CPU and memory of the principals mapped to it. For what the limits actually guarantee, see [resource groups](/docs/concepts/resource-groups/). @@ -49,11 +50,12 @@ default, which is not always "unlimited": the group alone changes nothing: map a user, ACL group or service account to it with [`ALTER USER`](/docs/query/sql/acl/alter-user-set-resource-group/), [`ALTER GROUP`](/docs/query/sql/acl/alter-group-set-resource-group/) or -[`ALTER SERVICE ACCOUNT`](/docs/query/sql/acl/alter-service-account-set-resource-group/) before it -governs anything. +[`ALTER SERVICE ACCOUNT`](/docs/query/sql/acl/alter-service-account-set-resource-group/) +before it governs anything. -The name must be unique across resource groups. If it is already taken the -statement fails, unless `IF NOT EXISTS` is included. +The name must be unique across resource groups, and names are case-sensitive, +except `DEFAULT`. If the name is already taken the statement fails, unless +`IF NOT EXISTS` is included. The statement requires the [`RESOURCE GROUP ADMIN`](/docs/security/rbac/#permissions) permission. @@ -64,20 +66,21 @@ no CPU slicing at all, so weights have no effect while `DEFAULT` is the only group. See [when scheduling engages](/docs/concepts/resource-groups/#when-scheduling-engages). -`cpu_limit` is a ceiling: the group gets at most that share of the node's CPUs -on average, even while the rest of the node is idle. The percentage -is of the CPUs available to the QuestDB process, and +`cpu_limit` is a ceiling: the group gets at most that percentage of the node's +CPUs on average, even while the rest of the node is idle. The percentage is of +the CPUs available to the QuestDB process, and [`resource_groups()`](/docs/query/functions/meta/#resource_groups) shows what it comes to on this node in `cpu_limit_cores`. A value without the `%` sign fails with `CPU limit must be a percentage of the node's CPUs, for example '50%'`, and -a percentage above 100 or with a fraction fails with +a percentage above 100 or not a whole number, such as `'2.5%'`, fails with `invalid Resource Group policy value`. How the limit is enforced, and when a group can briefly exceed it, is described in [A CPU limit is a ceiling](/docs/concepts/resource-groups/#a-cpu-limit-is-a-ceiling-not-a-share). `scheduling_policy` decides how the group divides its CPU between its own users and queries: `fifo` serves them in arrival order, and `fair` divides the group -by user first, then by query. An unknown name fails with +by user first, then by query, both for CPU and for admission. An unknown name +fails with `unknown scheduling policy, expected 'fifo' or 'fair'`. See [the scheduling policy](/docs/concepts/resource-groups/#the-scheduling-policy-divides-a-group-between-its-users). @@ -115,27 +118,37 @@ CREATE RESOURCE GROUP tenant_a WITH ( ); ``` -Verify with [`resource_groups()`](/docs/query/functions/meta/#resource_groups): +Map a principal so that the group governs its queries: + +```questdb-sql title="Run the tenant application's queries in tenant_a" +ALTER SERVICE ACCOUNT tenant_a_app SET RESOURCE GROUP tenant_a; +``` + +Verify with [`resource_groups()`](/docs/query/functions/meta/#resource_groups), +which also reports the admission settings and live counters: ```questdb-sql -SELECT name, cpu_weight, cpu_limit_pct, scheduling_policy, +SELECT name, cpu_weight, cpu_limit_pct, cpu_limit_cores, scheduling_policy, max_active_queries, memory_limit_bytes FROM resource_groups() ORDER BY name; ``` -| name | cpu_weight | cpu_limit_pct | scheduling_policy | max_active_queries | memory_limit_bytes | -| --------- | ---------- | ------------- | ----------------- | ------------------ | ------------------ | -| DEFAULT | 100 | 0 | fifo | null | 0 | -| analytics | 100 | 0 | fifo | null | 0 | -| exports | 10 | 0 | fifo | 1 | 0 | -| reporting | 50 | 0 | fifo | 4 | 2147483648 | -| tenant_a | 100 | 25 | fair | null | 0 | +On a node with 16 CPUs: + +| name | cpu_weight | cpu_limit_pct | cpu_limit_cores | scheduling_policy | max_active_queries | memory_limit_bytes | +| --------- | ---------- | ------------- | --------------- | ----------------- | ------------------ | ------------------ | +| DEFAULT | 100 | 0 | 0.0 | fifo | null | 0 | +| analytics | 100 | 0 | 0.0 | fifo | null | 0 | +| exports | 10 | 0 | 0.0 | fifo | 1 | 0 | +| reporting | 50 | 0 | 0.0 | fifo | 4 | 2147483648 | +| tenant_a | 100 | 25 | 4.0 | fair | null | 0 | `max_active_queries` is `null` when the group sets no admission limit, `memory_limit_bytes` is `0` when it sets no memory ceiling, and `cpu_limit_pct` -is `0` when it sets no CPU limit. `cpu_weight` and `scheduling_policy` always -report an effective value, so a group that sets neither shows `100` and `fifo`. +and `cpu_limit_cores` are `0` when it sets no CPU limit. `cpu_weight` and +`scheduling_policy` always report an effective value, so a group that sets +neither shows `100` and `fifo`. ## See also diff --git a/documentation/query/sql/acl/drop-resource-group.md b/documentation/query/sql/acl/drop-resource-group.md index c898a3dbd..a4859c397 100644 --- a/documentation/query/sql/acl/drop-resource-group.md +++ b/documentation/query/sql/acl/drop-resource-group.md @@ -57,8 +57,16 @@ Recreating a group with the same name produces a new group with fresh counters. Queries still running under the dropped group do not move to it. Map principals to the new group to place their subsequent queries under it. +The drop also removes every `USE RESOURCE GROUP` grant on the group, so a group +recreated under the same name starts with none. A session that chose the group +with [`SET RESOURCE GROUP`](/docs/query/sql/acl/set-resource-group/), or an HTTP +client that sends its name in the `resource_group` parameter, fails its next +managed query until it chooses another group. Once a group exists again under +that name it is used instead, subject to the usual permission check. + Dropping the last group other than `DEFAULT` disengages CPU scheduling for the -instance once those queries finish. See +instance once those queries finish, unless `DEFAULT` has a CPU limit or the +`fair` policy. See [when scheduling engages](/docs/concepts/resource-groups/#when-scheduling-engages). ## Examples diff --git a/documentation/query/sql/acl/grant.md b/documentation/query/sql/acl/grant.md index 93a21042f..c6d2870ac 100644 --- a/documentation/query/sql/acl/grant.md +++ b/documentation/query/sql/acl/grant.md @@ -2,8 +2,9 @@ title: GRANT reference sidebar_label: GRANT description: - "GRANT SQL keywords reference documentation. Applies to RBAC in QuestDB - Enterprise." + "GRANT gives a user, group or service account permissions on the database, + tables, columns or resource groups, optionally with the grant option. Applies + to RBAC in QuestDB Enterprise." --- import { EnterpriseNote } from "@site/src/components/EnterpriseNote" @@ -44,6 +45,9 @@ table's current columns with an optional `EXCLUDE` list: | * [EXCLUDE (columnName [, columnName ...])] } ``` +The `USE RESOURCE GROUP` permission can also be granted on a single resource +group: + ```questdb-sql title="Resource group scope" GRANT USE ON RESOURCE GROUP groupName TO entityName; ``` @@ -236,14 +240,20 @@ The two forms are authorized differently: - `GRANT USE ON RESOURCE GROUP` takes the [`RESOURCE GROUP ADMIN`](/docs/security/rbac/#permissions) permission. It names one group and one entity, and accepts neither `WITH GRANT OPTION` nor - `WITH VERIFICATION`. Both must exist: unlike a table grant, it cannot be - issued ahead of the entity's creation. + `WITH VERIFICATION`. The group and the entity must both exist: unlike other + grants, this form cannot be issued before the user, group or service account + it names is created. - `GRANT USE RESOURCE GROUP` is an ordinary database permission. Granting it takes the permission with the grant option, and it can itself carry `WITH GRANT OPTION`. -A grant to an ACL group covers its members, and the group an entity is mapped to -needs no grant at all. `SHOW PERMISSIONS`, +Because the database-level grant covers every group, revoking one group from an +entity that holds it changes nothing, see +[REVOKE](/docs/query/sql/acl/revoke/#revoke-use-of-resource-groups). + +A grant to an ACL group covers its members, and the group an entity is mapped +to, or `DEFAULT` for an unmapped entity, needs no grant at all. +`SHOW PERMISSIONS`, [`active_grants()`](/docs/query/functions/access-control/#active_grants) and [`active_permissions()`](/docs/query/functions/access-control/#active_permissions) show a grant on one group with the group's current name in `table_name`. The diff --git a/documentation/query/sql/acl/revoke.md b/documentation/query/sql/acl/revoke.md index b8f2dd77c..7766105e3 100644 --- a/documentation/query/sql/acl/revoke.md +++ b/documentation/query/sql/acl/revoke.md @@ -2,7 +2,8 @@ title: REVOKE reference sidebar_label: REVOKE description: - "REVOKE SQL keywords reference documentation. Applies to RBAC in QuestDB + "REVOKE takes permissions on the database, tables, columns or resource groups + away from a user, group or service account. Applies to RBAC in QuestDB Enterprise." --- @@ -40,6 +41,8 @@ table's current columns with an optional `EXCLUDE` list: | * [EXCLUDE (columnName [, columnName ...])] } ``` +The `USE RESOURCE GROUP` permission on a single resource group is revoked with: + ```questdb-sql title="Resource group scope" REVOKE USE ON RESOURCE GROUP groupName FROM entityName; ``` @@ -136,13 +139,23 @@ Like the grant, this form takes the [`RESOURCE GROUP ADMIN`](/docs/security/rbac/#permissions) permission, and the group must exist. +It removes only the grant on that group. An entity that also holds the +database-level `USE RESOURCE GROUP`, directly or through an ACL group, can still +use the group afterwards, because +[permission level readjustment](#permission-level-readjustment) does not apply +to resource groups: revoking one group never splits the database-level grant +into grants on the others. To take every group away, revoke the database-level +permission. + `REVOKE USE RESOURCE GROUP FROM monitoring` revokes the database-level permission, and with it every grant the entity holds on single groups. `REVOKE ALL FROM monitoring` and dropping the entity clear them as well, and `DROP RESOURCE GROUP` removes every grant on the dropped group. The permission is checked at the start of every managed query, so a revoke -reaches sessions that already chose the group: their next such query fails with +reaches sessions that already chose the group with +[`SET RESOURCE GROUP`](/docs/query/sql/acl/set-resource-group/): their next such +query fails with `Access denied for [USE RESOURCE GROUP on alerts]` until they choose another group or run `RESET RESOURCE GROUP`. A query already running finishes in its group. diff --git a/documentation/query/sql/acl/set-resource-group.md b/documentation/query/sql/acl/set-resource-group.md index 987031c51..7b75e97fa 100644 --- a/documentation/query/sql/acl/set-resource-group.md +++ b/documentation/query/sql/acl/set-resource-group.md @@ -1,6 +1,6 @@ --- title: SET RESOURCE GROUP reference -sidebar_label: SET RESOURCE GROUP +sidebar_label: SET / RESET RESOURCE GROUP description: "SET RESOURCE GROUP runs the rest of a session's queries in another resource group, and RESET RESOURCE GROUP returns to the mapped one. Applies to QuestDB @@ -14,24 +14,28 @@ import { EnterpriseNote } from "@site/src/components/EnterpriseNote" instance. -`SET RESOURCE GROUP` runs the rest of a session's queries in a resource group -other than the one its principal is mapped to. One account can then send urgent -and routine work to groups with different policies: a monitoring account, for -example, can evaluate its alert rules in a heavily weighted group while its -dashboards stay in an ordinary one. `RESET RESOURCE GROUP` returns the session -to the mapped group. +`SET RESOURCE GROUP` runs the rest of a PostgreSQL session's queries in a +resource group other than the one its principal is mapped to. One account can +then send urgent and routine work to groups with different policies: a +monitoring account, for example, can evaluate its alert rules in a heavily +weighted group while its dashboards stay in an ordinary one. +`RESET RESOURCE GROUP` returns the session to the mapped group. HTTP has no SQL session, so a request chooses its group with the `resource_group` parameter of [`/execute`](/docs/connect/compatibility/rest-api/#execute) instead, under the -same rules. +same permission rules. + +The choice lasts for one session or one request. To change the group that a +principal's queries run in by default, map the principal with +[`ALTER USER`](/docs/query/sql/acl/alter-user-set-resource-group/), +[`ALTER GROUP`](/docs/query/sql/acl/alter-group-set-resource-group/) or +[`ALTER SERVICE ACCOUNT`](/docs/query/sql/acl/alter-service-account-set-resource-group/) +`... SET RESOURCE GROUP`. `SET RESOURCE GROUP`, `RESET RESOURCE GROUP` and the `resource_group` parameter are available from QuestDB Enterprise 4.2.0. -For how a query is assigned to a group otherwise, see -[who a resource group applies to](/docs/concepts/resource-groups/#who-a-resource-group-applies-to). - --- ## Syntax @@ -44,73 +48,99 @@ SET [SESSION] RESOURCE GROUP groupName; RESET RESOURCE GROUP; ``` -`SESSION` is optional and changes nothing. +`SESSION` is optional and changes nothing. `groupName` is case-sensitive, except +`DEFAULT`, which matches in any case, and it may be quoted. + +:::caution + +`SET resource_group = alerts`, written like a PostgreSQL setting, is not this +statement. QuestDB accepts and ignores it like any unknown PostgreSQL setting, +so the session's group does not change. Write `SET RESOURCE GROUP alerts`. + +::: ## Description -The chosen group applies to every query the session starts afterwards, until -`RESET RESOURCE GROUP`, `RESET ALL` or `DISCARD ALL`, or until the session ends. -It replaces the principal's mapping: the group's admission, CPU and memory -policy apply exactly as they would to a principal mapped to it, and +The chosen group applies to every managed query the session starts afterwards, +until `RESET RESOURCE GROUP`, `RESET ALL` or `DISCARD ALL`, or until the session +ends. Managed queries are the statements that resource groups govern, such as +`SELECT`; see +[which statements are managed](/docs/concepts/resource-groups/#which-statements-are-managed). +For them the chosen group replaces the principal's mapping: its admission, CPU +and memory policy apply exactly as they would to a principal mapped to it, and [`current_resource_group()`](/docs/query/functions/meta/#current_resource_group) returns its name. A query that started earlier, including a cursor that is still being paged, keeps the group it started in. -Like a mapping, the choice governs only the statements that resource groups -manage, such as `SELECT`. See -[which statements are managed](/docs/concepts/resource-groups/#which-statements-are-managed). +The choice covers only the session's own queries. A `COPY ... TO` export started +from the session runs as a background job in the principal's mapped group. + +Two related statements fail instead of doing something unexpected: -`SET LOCAL RESOURCE GROUP` fails with -`SET LOCAL RESOURCE GROUP is not supported, use SET RESOURCE GROUP to switch the session`, -because the group applies to the whole session, not to one transaction. Any -other statement that starts with `SET RESOURCE` or `RESET RESOURCE` fails as -well, so a misspelled statement is reported instead of being accepted and -ignored like an unknown PostgreSQL setting. A setting written as -`SET resource_group = alerts` is not this statement: QuestDB accepts and ignores -it like any other unknown PostgreSQL setting, and the session's group does not -change. +- `SET LOCAL RESOURCE GROUP` fails with + `SET LOCAL RESOURCE GROUP is not supported, use SET RESOURCE GROUP to switch the session`, + because the group applies to the whole session, not to one transaction. +- Any other statement that starts with `SET RESOURCE` or `RESET RESOURCE` fails, + so a misspelling is reported instead of being ignored. ### Which connections can switch -Only a PostgreSQL wire connection has a SQL session. On any other connection the -statement fails with -`Resource Group switching needs a session, over HTTP send the group in the resource_group parameter of /exec`. -Over HTTP, send the group with each request, as in the -[example below](#choose-the-group-for-one-http-request). +Only a PostgreSQL wire connection has a SQL session. A PostgreSQL connection +parameter cannot set the group, so send `SET RESOURCE GROUP` after connecting. +On any other connection, `SET RESOURCE GROUP` and `RESET RESOURCE GROUP` fail +with +`Resource Group switching needs a session, over HTTP send the group in the resource_group parameter of /exec`, +where `/exec` is the older name of `/execute`: + +- Over HTTP, send the group with each request to `/execute`, as in the + [example below](#choose-the-group-for-one-http-request). The export endpoint + `/exp` does not take the parameter, so its exports run in the mapped group. +- Clients that query over QWP have neither a session nor a parameter, so their + queries always run in the principal's mapped group. ### Permissions -The group the principal is mapped to, or `DEFAULT` for an unmapped principal, -needs no permission. Any other group needs `USE RESOURCE GROUP` on it, granted -for one group or for all of them. That includes `DEFAULT` for a principal that -is mapped to another group. +Choosing the group the principal is mapped to, or `DEFAULT` for an unmapped +principal, needs no permission. Any other group, including `DEFAULT` for a +principal that is mapped elsewhere, needs `USE RESOURCE GROUP` on it, granted +for one group or for all of them with +[`GRANT`](/docs/query/sql/acl/grant/#grant-use-of-resource-groups): ```questdb-sql title="Allow one group, or every group" GRANT USE ON RESOURCE GROUP alerts TO monitoring; GRANT USE RESOURCE GROUP TO monitoring; ``` -The built-in admin and principals holding `DATABASE ADMIN` can use every group, -and a grant to an ACL group covers its members. In a session that has +Granting `USE ON RESOURCE GROUP` takes the +[`RESOURCE GROUP ADMIN`](/docs/security/rbac/#permissions) permission. The +built-in admin and principals holding `DATABASE ADMIN` can use every group, and +a grant to an ACL group covers its members. In a session that has [assumed a service account](/docs/query/sql/acl/assume-service-account/), the user who logged in decides: both the mapped group and the permission are that user's, not the service account's. -Without the permission, the statement fails with -`Access denied for [USE RESOURCE GROUP on ]`. A group that -does not exist fails with `Resource Group does not exist [name=]`. - -The permission is checked again at the start of every query that resource -groups manage, not only when the group is chosen. A revoke therefore applies to -the session's next such query, which fails with the same access-denied error -until the session chooses a group it may use or returns to its own. - -The session remembers the group by name. If the group is dropped or renamed, the -next managed query fails with -`Resource Group chosen by SET RESOURCE GROUP or the resource_group parameter does not exist [name=]` -until the session runs `SET RESOURCE GROUP`, with the new name after a rename, -or `RESET RESOURCE GROUP`. A group created later under the old name would be -used instead, subject to the same permission check. +`SET RESOURCE GROUP` checks the group and the permission when it runs. A group +that does not exist fails with `Resource Group does not exist [name=]`, +and a group the principal may not use fails with +`Access denied for [USE RESOURCE GROUP on ]`. + +Both are checked again at the start of every managed query, which is the only +check the HTTP parameter gets: + +- A revoke applies to the session's next managed query, which fails with the + access-denied error until the session chooses a group it may use or returns + to its own. Revoking one group from a principal that holds the database-level + `USE RESOURCE GROUP` changes nothing, see + [REVOKE](/docs/query/sql/acl/revoke/#revoke-use-of-resource-groups). +- The session remembers the group by name. If the group is dropped or renamed, + the next managed query fails with + `Resource Group chosen by SET RESOURCE GROUP or the resource_group parameter does not exist [name=]` + until the session runs `SET RESOURCE GROUP`, with the new name after a + rename, or `RESET RESOURCE GROUP`. A group created later under the old name + would be used instead, subject to the same permission check. +- An HTTP request that names a group that does not exist fails with that same + message when its query starts. A request whose statement is not managed, such + as `INSERT ... VALUES`, does not check the parameter at all. With access control disabled nothing is checked. Mapping statements need access control, so on such an instance choosing a group per session or request is the @@ -118,10 +148,14 @@ only way to run queries outside `DEFAULT`. ### Connection pools -A connection pooler resets a session with `DISCARD ALL` or `RESET ALL` before it -hands the connection to its next client. Both statements clear the session's -resource group, so the next client starts in the mapped group instead of -inheriting the previous client's choice. +`DISCARD ALL` and `RESET ALL` clear the session's group. A pooler that resets +each connection with one of them before handing it to the next client, such as +PgBouncer in session pooling mode, starts every client in its mapped group. +Many pools do not reset sessions: PgBouncer in transaction pooling mode, and +application-side pools such as HikariCP, hand the connection on with the group +still chosen, so the next client's queries run in that group too. Give the work +that switches groups a pool or connection of its own, and switch once after it +connects. ## Examples @@ -135,7 +169,7 @@ ALTER USER monitoring SET RESOURCE GROUP dashboards; GRANT USE ON RESOURCE GROUP alerts TO monitoring; ``` -On the connection that evaluates alert rules: +On the connection that evaluates alert rules, which has a pool of its own: ```questdb-sql title="Run the rest of this session in the alerts group" SET RESOURCE GROUP alerts; @@ -162,16 +196,30 @@ curl -G --data-urlencode "query=SELECT count() FROM fx_trades;" \ curl prompts for the password of `monitoring`. The parameter applies to that request only, and needs the same permission as `SET RESOURCE GROUP`. -### Return to the mapped group +### Take the group away again -```questdb-sql +```questdb-sql title="Return the session to its mapped group" RESET RESOURCE GROUP; + +SELECT current_resource_group(); ``` +| current_resource_group | +| ---------------------- | +| dashboards | + +```questdb-sql title="Stop the account from choosing the alerts group" +REVOKE USE ON RESOURCE GROUP alerts FROM monitoring; +``` + +A session that is still in `alerts` when the revoke runs fails its next managed +query until it runs `RESET RESOURCE GROUP`. + ## See also - [Choosing a group per session or request](/docs/concepts/resource-groups/#choosing-a-group-per-session-or-request) - [GRANT USE ON RESOURCE GROUP](/docs/query/sql/acl/grant/#grant-use-of-resource-groups) - [REVOKE USE ON RESOURCE GROUP](/docs/query/sql/acl/revoke/#revoke-use-of-resource-groups) +- [ALTER USER SET RESOURCE GROUP](/docs/query/sql/acl/alter-user-set-resource-group/) - [`current_resource_group()`](/docs/query/functions/meta/#current_resource_group) - [Configure and use resource groups](/docs/operations/resource-groups/) diff --git a/documentation/security/rbac.md b/documentation/security/rbac.md index 47d4d0905..79a908eea 100644 --- a/documentation/security/rbac.md +++ b/documentation/security/rbac.md @@ -1207,7 +1207,7 @@ SELECT * FROM all_permissions(); | REMOVE STORAGE POLICY | Database | Table | Remove storage policies | | RENAME COLUMN | Database | Table | Column | Rename columns | | RENAME TABLE | Database | Table | Rename tables | -| RESOURCE GROUP ADMIN | Database | Manage and map resource groups, read `resource_groups()` | +| RESOURCE GROUP ADMIN | Database | Manage and map resource groups, grant and revoke `USE ON RESOURCE GROUP`, read `resource_groups()` | | RESUME WAL | Database | Table | Resume WAL processing | | SELECT | Database | Table | Column | Read data | | SET PARQUET SETTINGS | Database | Table | Set column Parquet encoding and compression | @@ -1224,7 +1224,7 @@ SELECT * FROM all_permissions(); | SYSTEM ADMIN | Database | System functions (reload_tls, reader_pool, etc.); makes objects [visible](#object-visibility) | | TRUNCATE TABLE | Database | Table | Truncate tables | | UPDATE | Database | Table | Column | Update data | -| USE RESOURCE GROUP | Database | Resource group | Run queries in a resource group chosen with [`SET RESOURCE GROUP`](/docs/query/sql/acl/set-resource-group/); see [GRANT](/docs/query/sql/acl/grant/#grant-use-of-resource-groups) | +| USE RESOURCE GROUP | Database | Run queries in a resource group chosen with [`SET RESOURCE GROUP`](/docs/query/sql/acl/set-resource-group/) or the `resource_group` HTTP parameter; also grantable on one group, see [GRANT](/docs/query/sql/acl/grant/#grant-use-of-resource-groups) | | VACUUM TABLE | Database | Table | Reclaim storage | ### User management permissions