Skip to content

feat(resource_monitor): manage triggers, several notify users, and non-ACCOUNTADMIN owners - #86

Merged
noel merged 3 commits into
datacoves:mainfrom
GClunies:fix/resource-monitor-triggers-owner-notify-users
Nov 12, 2026
Merged

noel merged 3 commits into
datacoves:mainfrom
GClunies:fix/resource-monitor-triggers-owner-notify-users

Conversation

@GClunies

@GClunies GClunies commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

What

Snowcap can now manage a real resource monitor: its triggers, a list of notify users, and an owner other than ACCOUNTADMIN. A live monitor declared in YAML plans to zero changes, and changes to it apply.

Gap Before After
Triggers ResourceMonitor had no field for TRIGGERS. Notify and suspend thresholds could not be declared or read back. New triggers field: a list of {threshold, action} with action NOTIFY, SUSPEND, or SUSPEND_IMMEDIATE. The fetch reads it back from notify_at, suspend_at, and suspend_immediately_at.
Several notify users The fetch returned the SHOW string "A, B", so the plan rejected the monitor it read. The fetch splits the string into a list.
Owner The spec raised ResourceMonitors can only be created by ACCOUNTADMIN for any other owner. Create runs as ACCOUNTADMIN and transfers ownership to the declared owner. Update and drop run as the owning role.
Change and transfer in one apply Apply ran an update and the transfer of the same resource at one level, in random role order. A transfer that ran first made the ALTER fail with 003001. Apply runs each level's transfers after its other changes. This fix applies to every resource type.
Case of notify users notify_users: [alice] rendered $$alice$$, which Snowflake rejects with 090268. An unquoted name is uppercased, as Snowflake stores it. A quoted name keeps its case.
resource_monitors:
  - name: WH_MONITOR
    owner: MONITOR_ADMIN
    credit_quota: 1000
    notify_users: [ALICE, BOB]
    triggers:
      - threshold: 75
        action: NOTIFY
      - threshold: 100
        action: SUSPEND
      - threshold: 110
        action: SUSPEND_IMMEDIATE

Why

We tested each Snowflake behavior against a live account before we wrote the code.

Statement or read Result What the code does
ALTER RESOURCE MONITOR X SET CREDIT_QUOTA = 7 TRIGGERS ON ... Accepted. TRIGGERS replaces every trigger. update_resource_monitor renders SET props, then the full TRIGGERS clause.
ALTER RESOURCE MONITOR X SET TRIGGERS ON ... Syntax error. TRIGGERS is not a SET property. update__default cannot render it, so the resource has its own update function.
UNSET TRIGGERS, a bare TRIGGERS, SET TRIGGERS = (), NOTRIGGERS All rejected. No statement removes every trigger. triggers: [] raises ValueError. Omit triggers to leave them unmanaged.
TRIGGERS ON 75.5 PERCENT DO NOTIFY Syntax error 001003. A non-integer threshold raises ValueError.
TRIGGERS ON 0 PERCENT DO NOTIFY, TRIGGERS ON -5 PERCENT DO NOTIFY 0 accepted. -5 is syntax error 001003. A negative or bool threshold, or a trigger with a missing or extra key, raises ValueError.
ALTER RESOURCE MONITOR X TRIGGERS ON ..., with no SET Accepted, as ACCOUNTADMIN and as a custom owner. A triggers-only change renders this statement.
SHOW RESOURCE MONITORS notify_at A comma-separated list, for example '50%,75%'. One production account reports '100%,50%,75%,90%', which is not numeric order. Triggers are sorted by threshold and action on both sides of the diff.
SHOW RESOURCE MONITORS notify_users '' or 'A, B, C'. Split, strip, and sort.
SET NOTIFY_USERS = ($$snowcap_admin$$) for user SNOWCAP_ADMIN Error 090268, "User snowcap_admin does not exist." Unquoted names are uppercased before render and diff.
ALTER or DROP on a monitor owned by another role, run as ACCOUNTADMIN Error 003001, insufficient privileges. Update and drop run as the owner.
GRANT OWNERSHIP ON RESOURCE MONITOR X TO ROLE R as ACCOUNTADMIN Accepted, also for a monitor owned by a role outside the ACCOUNTADMIN hierarchy. Create runs as ACCOUNTADMIN with an ownership transfer when the owner differs. A later transfer also runs as ACCOUNTADMIN.

Tested

  • Unit tests: TestResourceMonitorPlanning in tests/test_blueprint.py covers the SHOW round-trip with zero changes, a trigger-only change, a quota plus trigger change, create plus transfer, lowercase and quoted notify users, and an apply that alters before it transfers. tests/test_resource_types.py covers the rejected trigger lists. The SQL and JSON fixtures carry triggers.
  • The apply-order test fails on the old apply loop for 5 of 10 PYTHONHASHSEED values (1, 2, 5, 8, 9) and passes on the new loop for all 10.
  • make lint, make typecheck, and pytest --ignore=tests/integration: 2335 passed, 1 skipped, 1 xfailed.
  • Integration: tests/integration/data_provider/test_fetch_resource_simple.py --snowflake -k ResourceMonitor passes against a live account.
  • Live end to end, with a monitor owned by a custom role:
Step SQL Snowcap ran Re-plan
Create USE ROLE ACCOUNTADMIN, CREATE RESOURCE MONITOR E2E_RM CREDIT_QUOTA = 5 TRIGGERS ON 75 PERCENT DO NOTIFY ON 100 PERCENT DO SUSPEND, GRANT OWNERSHIP ... TO ROLE PROBE_RM_OWNER COPY CURRENT GRANTS 0 changes
Change quota and triggers USE ROLE PROBE_RM_OWNER, ALTER RESOURCE MONITOR E2E_RM SET CREDIT_QUOTA = 7 TRIGGERS ON 50 PERCENT DO NOTIFY ON 90 PERCENT DO SUSPEND ON 110 PERCENT DO SUSPEND_IMMEDIATE 0 changes
Drop with sync_resources USE ROLE PROBE_RM_OWNER, DROP RESOURCE MONITOR IF EXISTS E2E_RM 0 changes

A second live run used Blueprint.apply with threads=8 under PYTHONHASHSEED 1, 2, and 5. The owner roles were outside the ACCOUNTADMIN hierarchy, and the config named the notify user in lowercase (snowcap_admin).

Step Plan Re-plan
Create, owner PROBE86_A CreateResource 0 changes. SHOW reports notify_users: SNOWCAP_ADMIN.
New triggers and owner PROBE86_B UpdateResource {triggers} + TransferOwnership 0 changes for all 3 seeds. Owner PROBE86_B, notify_at: 50%, suspend_at: 90%.

Known gap, not changed here

CREATE RESOURCE MONITOR ... FREQUENCY = MONTHLY without START_TIMESTAMP fails with error 090259, "Must specify frequency and start time together." A monitor that declares frequency must also declare start_timestamp. This behavior predates this PR.

Fixes #102

…n-ACCOUNTADMIN owners

A live resource monitor could not be declared and planned to zero changes:

- The class had no field for TRIGGERS, so notify and suspend thresholds
  could not be declared or read back.
- The fetch returned the SHOW notify_users string ("A, B") instead of a
  list, so a monitor with several notify users failed to plan.
- The spec refused any owner except ACCOUNTADMIN, although ACCOUNTADMIN can
  hand a monitor to another role, and after that only that role can alter
  or drop it.

Add a `triggers` field (threshold + NOTIFY / SUSPEND / SUSPEND_IMMEDIATE)
rendered and parsed by TriggersProp, read it back from notify_at /
suspend_at / suspend_immediately_at, and sort triggers and notify users so
order never diffs. Updates emit SET props followed by the TRIGGERS clause.
Create runs as ACCOUNTADMIN and transfers to a declared owner; update and
drop run as the owning role.
@noel

noel commented Oct 18, 2026

Copy link
Copy Markdown
Contributor

Reviewed this PR (10 files). Checked out the head, read every hunk against the surrounding code (execution_strategy_for_change, diff / _diff_resource_data, the apply loop in Blueprint.apply, Props.render, _coerce_resource_field), ran the full unit suite (2234 passed), and probed the new code paths in a REPL to confirm each failure mode.

Five findings.

  1. Medium. blueprint.py:2598, the owner split breaks the ordering assumption that made it safe. UpdateResource now returns the monitor's owner while TransferOwnership still falls through to ACCOUNTADMIN. Confirmed: update gives OLD_OWNER, transfer gives ACCOUNTADMIN. Both changes share one URN, so Blueprint.apply puts them at the same dependency level, and process_commands iterates roles_set, a plain set whose order is hash-randomized per process.

    Change a monitor's credit_quota or triggers and its owner in one apply, and the GRANT OWNERSHIP can run first. The subsequent USE ROLE OLD_OWNER; ALTER RESOURCE MONITOR ... then fails with the exact 003001 this PR documents. The comment in owner_for_change ("TRANSFER actions occur strictly after CHANGE actions") held while both ran as ACCOUNTADMIN, and no longer does. Routing TransferOwnership to change.from_owner, which is what the generic branch does, or forcing the transfer to a later level, restores the ordering.

  2. Medium. data_provider.py:3689, notify_users is split but never case-normalized. SHOW returns user names uppercased, while the resource's own docstring and the generated YAML example use lowercase (user1, user2). Reproduced: config notify_users: [alice, bob] against a monitor whose SHOW row reads "ALICE, BOB" plans UpdateResource {'notify_users': ['alice', 'bob']} on every run. The ALTER ... SET NOTIFY_USERS = ($$alice$$, $$bob$$) succeeds, Snowflake stores ALICE, BOB, and the next plan shows the same change forever. Typing the field as list[ResourceName], or uppercasing unquoted names in __post_init__, makes it converge.

  3. Low. resource_monitor.py:59, trigger validation has holes. trigger["threshold"] and trigger["action"] are indexed without guarding the keys, so a YAML typo like triggers: [{action: NOTIFY}] raises a bare KeyError: 'threshold' instead of the clean ValueError the sibling checks produce, and extra keys are silently dropped by the dict rebuild. Separately, isinstance(True, int) is True, so threshold: yes passes validation and renders ON True PERCENT DO NOTIFY, failing at apply time. Zero and negative thresholds are unchecked too.

  4. Low. lifecycle.py:457, a triggers-only delta emits ALTER with no SET. When the delta carries only triggers, which is the most common edit (moving a threshold), set_data is empty and the statement becomes ALTER RESOURCE MONITOR X TRIGGERS ON .... Every live statement in the PR's evidence table exercised SET <props> TRIGGERS .... This no-SET shape is asserted only as a string in test_a_changed_trigger_replaces_the_whole_set_as_the_owner and was never run against Snowflake, and the same table records TRIGGERS outside a well-formed SET context being rejected in other forms. Worth a live check before merge.

  5. Low. docs/resources/resource_monitor.md is stale. docs/resources/*.md is generated from the class docstring by tools/generate_resource_docs.py. The docstring was updated, the doc wasn't regenerated. The published page still says "Note: Resource monitors can only be owned by ACCOUNTADMIN", which is now false and the opposite of this PR's headline change, and it omits the triggers field entirely.

Checked and cleared, for the record: TriggersProp parsing (Keyword("SUSPEND") correctly does not swallow SUSPEND_IMMEDIATE, since _ is an identifier char); trigger sort keys match on both sides of the diff, so the unordered notify_at Snowflake returns round-trips to zero changes; _diff_resource_data skips None manifest values, so triggers: None leaves remote triggers unmanaged and no UNSET-plus-TRIGGERS delta can reach update_resource_monitor; to_dict serializes the nested action enum to a string; remote state passes through spec(**data) in fetch_remote_state, so fetched triggers sort the same way as the manifest; and process_commands still raises a clear MissingPrivilegeException when the new owner-role execution path names a role the session lacks.

@noel

noel commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

@GClunies checking in, quiet since my Oct 18 review.

Open from my side are the two mediums: finding 1, the owner split breaking the ordering assumption in owner_for_change so a GRANT OWNERSHIP can run before the ALTER and fail with the exact 003001 this PR documents, and finding 2, notify_users never being case-normalized so a lowercase config plans the same change forever. Finding 4, the triggers-only delta emitting ALTER with no SET, is the one I'd want a live check on before merge rather than a code change.

One scheduling note: #93 and #97 merged today and #93 touched props.py, lifecycle.py and data_provider.py, including how values get single-quoted. GitHub still reports this branch mergeable, but worth rebasing and re-running before you push, since finding 2's $$alice$$ rendering goes through quote_value.

Are you planning to pick these up?

GClunies and others added 2 commits November 10, 2026 18:14
… users

- Apply runs each level's ownership transfers after its other changes. An
  update runs as the current owner and shares a level with the transfer of
  the same resource, so a transfer that ran first made the ALTER fail with
  003001. The old loop failed 5 of 10 hash seeds in the new unit test.
- notify_users are named as Snowflake stores them: an unquoted name is
  uppercased, a quoted name keeps its case. Snowflake matches the
  NOTIFY_USERS string exactly, so `$$alice$$` failed with 090268.
- Triggers with a missing or extra key, a bool threshold, or a negative
  threshold raise ValueError. A threshold of 0 is valid in Snowflake.
- The class docstring fields are one line each, so the docs generator
  parses the class again. docs/resources/resource_monitor.md documents
  triggers and owner and drops the ACCOUNTADMIN-only note.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011dXsGMQktcy3n6S92p5Cmv
@GClunies

Copy link
Copy Markdown
Contributor Author

@noel Thanks for the review. All five findings are addressed in 419712f. I merged main (with #93 and #97) into the branch first, without a rebase, so the push is a fast-forward.

# Finding Resolution Evidence
1 Transfer can run before the ALTER process_commands now runs each level's TransferOwnership changes after the other changes at that level. Routing the transfer to from_owner alone does not fix the race, because one role's changes at one level also run in parallel in the thread pool. The transfer stays on ACCOUNTADMIN. Live, ACCOUNTADMIN can GRANT OWNERSHIP on a monitor owned by a role outside its hierarchy. It cannot ALTER that monitor (003001). The new test test_a_change_and_a_new_owner_in_one_apply_alter_before_the_transfer fails on the old loop for PYTHONHASHSEED 1, 2, 5, 8, and 9, and passes on the new loop for 0 to 9. A live Blueprint.apply that changes triggers and owner together re-plans to 0 changes under seeds 1, 2, and 5.
2 notify_users case The spec stores each name as ResourceName(user).unquoted. An unquoted name is uppercased, and a quoted name keeps its case. The fetch quotes a non-uppercase name from SHOW, so a quoted lowercase user round-trips. This was worse than a plan loop. Live, SET NOTIFY_USERS = ($$snowcap_admin$$) fails with 090268, "User snowcap_admin does not exist". With the fix, config snowcap_admin applies and re-plans to 0 changes.
3 Trigger validation Raises ValueError for a missing or extra key, a bool threshold, or a negative threshold. A non-mapping trigger already raises TypeError from the field type check. Live, ON 0 PERCENT is accepted, so 0 stays valid. ON -5 PERCENT is syntax error 001003.
4 Triggers-only ALTER with no SET No code change. Live, ALTER RESOURCE MONITOR X TRIGGERS ON 50 PERCENT DO NOTIFY ON 90 PERCENT DO SUSPEND is accepted as ACCOUNTADMIN and as a custom owner. The finding 1 end-to-end run applied this statement through Snowcap.
5 Stale docs The generator rejected the class because of its multi-line field descriptions. Those descriptions are now one line each. The generator now rewrites every page against the hand edits from #100, so I edited docs/resources/resource_monitor.md by hand. The page now documents triggers and owner, and the ACCOUNTADMIN-only note is gone. tools/generate_resource_docs.py parses ResourceMonitor with no error.

make lint, make typecheck, and the unit suite pass (2335 passed, 1 skipped, 1 xfailed). The live test_fetch_resource_simple.py --snowflake -k ResourceMonitor also passes.

@noel
noel merged commit 5ee0c22 into datacoves:main Nov 12, 2026
6 checks passed
GClunies added a commit to GClunies/snowcap that referenced this pull request Nov 21, 2026
Rerun live_audit.py on every object at snowcap 6ce5c12, so FINDINGS.md
reflects current main, as the review asked.

main changed three things that the inventory had to follow:
- RESOURCE MONITOR: triggers is a field now (datacoves#86). The truth query joins
  SHOW's notify_at, suspend_at, and suspend_immediately_at columns, and
  the row has samples. It passes L2 to L5.
- SECURITY INTEGRATION:saml2: SAML2SecurityIntegration models it now.
  The object has create_args, truth queries, and samples for 11 rows.
  The rows without a sample say why. The x509 samples are self-signed
  test certificates with no private key.
- EXTERNAL FUNCTION: fqn now carries the argument signature (datacoves#90), so
  the DESCRIBE in the truth query doubled it and failed. The query names
  the function without a signature now.

NOTEBOOK now fails L2, because Snowflake disabled new Legacy Notebooks
on the test account (BCR: no Legacy Notebook activity in the 60 days
before November 1, 2026). snowcap's Notebook renders only the legacy
CREATE NOTEBOOK, so the finding is correct for current snowcap.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011dXsGLBEG2amgh6CdUmCP5
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Apply: a resource change and its ownership transfer run in random order

2 participants