-- 0.4.4 -> 0.4.5 -- -- Two changes. Agents get a mark, the role agent_gate_agents (at the end of this file): the -- library uses it to refuse an agent's privileges outside the agent's session, and every agent -- already registered is given it here. And agent_gate_internal._budget(), which every commit -- calls, no longer reads the whole record. Up to 0.4.4 it computed the window's start inside -- its query with clock_timestamp(); a volatile value -- cannot be searched with an index, so each commit read every execution the gate had ever -- recorded -- 190 ms per write on a record of 865,000, and growing with it. The start is now -- computed first and handed to the sum as a parameter. What it counts does not change. -- tests/budget.sh, case 8, fails against 0.4.4 and passes here. Also a README rewritten as a -- front page, with the reference moved to docs/; see CHANGELOG.md. CREATE OR REPLACE FUNCTION agent_gate_internal._budget(p_agent text, p_lock boolean) RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, agent_gate_internal, pg_temp AS $$ DECLARE v_budget integer; v_window integer; v_since timestamptz; v_from timestamptz; v_used bigint; BEGIN PERFORM agent_gate_internal._only_the_gate(); IF p_lock THEN SELECT a.max_rows_per_window, a.window_seconds, a.budget_since INTO v_budget, v_window, v_since FROM agent_gate_internal.agents a WHERE a.name = p_agent FOR NO KEY UPDATE; ELSE SELECT a.max_rows_per_window, a.window_seconds, a.budget_since INTO v_budget, v_window, v_since FROM agent_gate_internal.agents a WHERE a.name = p_agent; END IF; IF NOT FOUND THEN RETURN NULL; END IF; -- The window's start is computed once, here, and handed to the sum as a parameter. Written -- inside the query, clock_timestamp() is volatile, so no index can be searched with it and -- every commit read the whole record (up to 0.4.4: 190 ms per write on a record of 865,000, -- and growing with it). EXECUTE plans with the value itself, so a window reads its own rows -- through executions_kept_commit_at whatever its length (tests/budget.sh, case 8). v_from := greatest(clock_timestamp() - make_interval(secs => v_window), coalesce(v_since, '-infinity')); EXECUTE 'SELECT coalesce(sum(coalesce(e.rows_moved, e.rows_affected, 0)), 0) FROM agent_gate_internal.executions e JOIN agent_gate_internal.proposals p ON p.id = e.proposal WHERE e.mode = ''commit'' AND e.outcome = ''kept'' AND e.started_at > $1 AND p.agent = $2' INTO v_used USING v_from, p_agent; RETURN jsonb_build_object('budget', v_budget, 'used', v_used, 'window_seconds', v_window); END $$; -- 0.4.5. The mark of a registered agent role. -- PostgreSQL also uses a role's rights outside its own sessions: ANALYZE and the autovacuum -- evaluate an index expression as the table's owner, a view or a rule writes with its owner's -- privileges, a SECURITY DEFINER function runs as its owner. The library refuses an agent's -- rights there (src/hooks.rs), and it knows an agent's role by its membership in this role, -- which PostgreSQL caches per backend. WITH INHERIT FALSE, SET FALSE: the membership grants -- nothing, it only marks. Roles are global, so a database that already has it uses it, as long -- as it cannot log in. DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'agent_gate_agents') THEN CREATE ROLE agent_gate_agents NOLOGIN; ELSIF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'agent_gate_agents' AND (rolcanlogin OR rolsuper)) THEN RAISE EXCEPTION 'pg_agent_gate: role agent_gate_agents exists and can log in or is a superuser' USING HINT = 'The gate uses this role only as a mark of its agents. Drop it or make it NOLOGIN NOSUPERUSER.'; END IF; END $$; -- Every role already registered gets the mark. DO $$ DECLARE r name; BEGIN FOR r IN SELECT DISTINCT a.role FROM agent_gate_internal.agents a JOIN pg_catalog.pg_roles ar ON ar.rolname = a.role LOOP EXECUTE format('GRANT agent_gate_agents TO %I WITH INHERIT FALSE, SET FALSE', r); END LOOP; END $$; -- register_agent gives the mark; the rest of it is unchanged from 0.4.1. CREATE OR REPLACE FUNCTION agent_gate.register_agent( p_name text, p_role regrole, p_description text, p_max_rows integer DEFAULT 1000, p_allow_ddl boolean DEFAULT false, p_requires_approval boolean DEFAULT false, p_max_rows_per_window integer DEFAULT NULL, p_window_seconds integer DEFAULT 3600) RETURNS jsonb LANGUAGE plpgsql SET search_path = pg_catalog, agent_gate_internal, pg_temp AS $$ DECLARE role_name name; is_super boolean; enforced text; budget integer := coalesce(p_max_rows_per_window, p_max_rows); members text; BEGIN SELECT rolname, rolsuper INTO role_name, is_super FROM pg_roles WHERE oid = p_role; IF is_super THEN RAISE EXCEPTION 'pg_agent_gate: % is a superuser, and a superuser can unset agent_gate.agent', role_name USING HINT = 'An agent role that can leave the gate is not behind it. Use a role without SUPERUSER.'; END IF; IF EXISTS (SELECT 1 FROM pg_roles WHERE oid = p_role AND (rolreplication OR rolbypassrls)) THEN RAISE EXCEPTION 'pg_agent_gate: % has REPLICATION or BYPASSRLS, which reach past the gate', role_name USING HINT = 'Use a role without REPLICATION and without BYPASSRLS.'; END IF; IF EXISTS ( WITH RECURSIVE up(r) AS ( SELECT m.roleid FROM pg_auth_members m WHERE m.member = p_role UNION SELECT m.roleid FROM pg_auth_members m JOIN up ON m.member = up.r) SELECT 1 FROM up JOIN pg_roles r ON r.oid = up.r WHERE r.rolsuper OR r.rolreplication OR r.rolbypassrls OR r.rolname IN ('pg_write_all_data', 'pg_execute_server_program', 'pg_write_server_files')) THEN RAISE EXCEPTION 'pg_agent_gate: % is a member, directly or through other roles, of a superuser or of a role that reaches past the gate', role_name USING HINT = 'An agent role must not be able to SET ROLE out from behind the gate. Revoke those memberships.'; END IF; -- And nothing can SET ROLE INTO it (0.4.1): a member of the agent role would have its -- privileges in a session the gate does not watch. SELECT string_agg(format('%I', r.rolname), ', ' ORDER BY r.rolname) INTO members FROM pg_auth_members m JOIN pg_roles r ON r.oid = m.member WHERE m.roleid = p_role; IF members IS NOT NULL THEN RAISE EXCEPTION 'pg_agent_gate: % has members (%), and a member can SET ROLE into it in a session the gate does not watch', role_name, members USING HINT = 'An agent role has no members: each agent (or each seat of a broker) logs in AS its own role. REVOKE those memberships first.'; END IF; INSERT INTO agent_gate_internal.agents (name, role, max_rows, allow_ddl, description, requires_approval, max_rows_per_window, window_seconds) VALUES (p_name, role_name, p_max_rows, p_allow_ddl, p_description, p_requires_approval, budget, p_window_seconds); EXECUTE format('ALTER ROLE %I SET agent_gate.agent = %L', role_name, p_name); EXECUTE format('GRANT agent_gate_agents TO %I WITH INHERIT FALSE, SET FALSE', role_name); IF current_setting('shared_preload_libraries') ~ '(^|,)\s*"?pg_agent_gate"?\s*(,|$)' THEN enforced := 'shared_preload_libraries'; ELSE EXECUTE format('ALTER ROLE %I SET session_preload_libraries = %L', role_name, 'pg_agent_gate'); enforced := 'session_preload_libraries, set on the role'; END IF; RETURN jsonb_build_object( 'agent', p_name, 'role', role_name, 'max_rows', p_max_rows, 'allow_ddl', p_allow_ddl, 'requires_approval', p_requires_approval, 'max_rows_per_window', budget, 'window_seconds', p_window_seconds, 'enforced_by', enforced, 'takes_effect', 'on the next connection of that role; existing connections are not behind the gate'); END $$; REVOKE EXECUTE ON FUNCTION agent_gate.register_agent(text, regrole, text, integer, boolean, boolean, integer, integer) FROM PUBLIC; -- unregister_agent takes it away, once no agent is registered with that role. CREATE OR REPLACE FUNCTION agent_gate.unregister_agent(p_name text) RETURNS jsonb LANGUAGE plpgsql SET search_path = pg_catalog, agent_gate_internal, pg_temp AS $$ DECLARE role_name name; BEGIN SELECT role INTO role_name FROM agent_gate_internal.agents WHERE name = p_name; IF NOT FOUND THEN RAISE EXCEPTION 'pg_agent_gate: no agent named %', p_name; END IF; EXECUTE format('ALTER ROLE %I RESET agent_gate.agent', role_name); DELETE FROM agent_gate_internal.agents WHERE name = p_name; IF NOT EXISTS (SELECT 1 FROM agent_gate_internal.agents WHERE role = role_name) AND EXISTS (SELECT 1 FROM pg_roles WHERE rolname = role_name) THEN EXECUTE format('REVOKE agent_gate_agents FROM %I', role_name); END IF; RETURN jsonb_build_object('agent', p_name, 'role', role_name, 'effect', 'from its next connection the role is an ordinary role; its record stays'); END $$; -- 0.4.5. The budget counts a write from the moment it is committed. Up to here it counted from when -- the verb STARTED (executions.started_at), and an agent decides how long its own verb takes and -- when its transaction commits. A verb that waited on a lock the agent held from another -- session -- its own table, a row, a transaction advisory lock -- or on pg_sleep() in its own -- statement, a queue of the agent's sessions behind its own row, or a transaction left open -- after the verb: each kept rows that the next write did not count (measured on 0.4.5 before -- this: 18 rows in one burst against a budget of 3; tests/budget.sh, cases 9 to 11). The -- library now writes one row here per agent and transaction at PRE_COMMIT -- after the deferred -- triggers, the last thing before the commit -- and the budget sums these. Append-only. CREATE TABLE agent_gate_internal.budget_spent ( agent text NOT NULL, moved bigint NOT NULL CHECK (moved >= 0), at timestamptz NOT NULL ); CREATE INDEX budget_spent_agent_at ON agent_gate_internal.budget_spent (agent, at) INCLUDE (moved); CREATE TRIGGER budget_spent_append_only BEFORE UPDATE OR DELETE ON agent_gate_internal.budget_spent FOR EACH ROW EXECUTE FUNCTION agent_gate_internal._append_only(); CREATE TRIGGER budget_spent_no_truncate BEFORE TRUNCATE ON agent_gate_internal.budget_spent FOR EACH STATEMENT EXECUTE FUNCTION agent_gate_internal._append_only(); SELECT pg_catalog.pg_extension_config_dump('agent_gate_internal.budget_spent', ''); CREATE FUNCTION agent_gate_internal._spend(p_agent text, p_moved bigint) RETURNS bigint LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, agent_gate_internal, pg_temp AS $$ BEGIN PERFORM agent_gate_internal._only_the_gate(); INSERT INTO agent_gate_internal.budget_spent (agent, moved, at) VALUES (p_agent, p_moved, clock_timestamp()); RETURN p_moved; END $$; CREATE OR REPLACE FUNCTION agent_gate_internal._budget(p_agent text, p_lock boolean) RETURNS jsonb LANGUAGE plpgsql SECURITY DEFINER SET search_path = pg_catalog, agent_gate_internal, pg_temp AS $$ DECLARE v_budget integer; v_window integer; v_since timestamptz; v_from timestamptz; v_used bigint; BEGIN PERFORM agent_gate_internal._only_the_gate(); IF p_lock THEN SELECT a.max_rows_per_window, a.window_seconds, a.budget_since INTO v_budget, v_window, v_since FROM agent_gate_internal.agents a WHERE a.name = p_agent FOR NO KEY UPDATE; ELSE SELECT a.max_rows_per_window, a.window_seconds, a.budget_since INTO v_budget, v_window, v_since FROM agent_gate_internal.agents a WHERE a.name = p_agent; END IF; IF NOT FOUND THEN RETURN NULL; END IF; -- The window's start is computed once and handed to the sum as a parameter, so the sum reads -- budget_spent_agent_at whatever the window's length (tests/budget.sh, case 8). What this -- transaction kept and has not committed yet the library adds itself. v_from := greatest(clock_timestamp() - make_interval(secs => v_window), coalesce(v_since, '-infinity')); EXECUTE 'SELECT coalesce(sum(s.moved), 0) FROM agent_gate_internal.budget_spent s WHERE s.agent = $2 AND s.at > $1' INTO v_used USING v_from, p_agent; RETURN jsonb_build_object('budget', v_budget, 'used', v_used, 'window_seconds', v_window); END $$; -- What was kept before this upgrade is charged at the end of its verb: the best this record knows. INSERT INTO agent_gate_internal.budget_spent (agent, moved, at) SELECT p.agent, coalesce(e.rows_moved, e.rows_affected, 0), e.started_at + make_interval(secs => e.duration_ms / 1000.0) FROM agent_gate_internal.executions e JOIN agent_gate_internal.proposals p ON p.id = e.proposal WHERE e.mode = 'commit' AND e.outcome = 'kept';