Skip to main content

Auto-rule and script SDK

A reference for what is available inside the code of an auto-pause rule and a user script: the ad object's fields, the functions for pausing and resuming, and the selectors for picking ads. Labels for all fields with descriptions are also available right in the rule editor — in the ad.* keys reference side panel (search by name and description).

This is the Server SDK — commands that run on the Qubix server, as opposed to the Browser SDK that runs in the visitor's browser. The Server SDK is synchronous: sql, ctx.fetch, and state return their value right away, so await gains you nothing — write the code as a plain sequence.

If you do write async/await

They work. The promise queue is drained before the run ends, so both a .then handler and the code after an await are executed. The one thing you must not do is lose an error there: an exception thrown after an await, or inside a .then with no .catch, ends the run with an error and names the reason in the run log; in the script console this is the line "Unhandled promise rejection: …" — in Russian when the script owner's panel is in Russian, in English otherwise. An endless chain of promises is cut off by the run's time limit, the same as any other endless loop.

The ad object​

In an auto-pause rule, you receive a single ad object — this is the ad the check is being run for. Through it you read all metrics and attributes. All available fields are grouped by scope.

GroupField prefixWhat's inside
Adad.spend_24h, ad.roas_24h, ad.primary_country, ad.effective_status…Metrics and attributes of the ad itself
Creativead.creo_*Metrics by creative (all ads with this creative)
Geoad.geo_*Metrics by country
Offerad.offer_*Metrics and parameters of the offer (payout, cap)
Networkad.network_*Metrics by network
Previous periodad.prev_*The same metrics for the previous period (for comparison)

The full list of metrics, time windows (_1h…_total), and the meaning of each prefix — in the Metrics and columns section.

Caution

Accessing a non-existent field (ad.something_wrong) immediately aborts the rule with an error. Check names against the reference in the editor.

Pause​

Three functions — by scope. The ad, the ad set, and the campaign.

FunctionAction
pauseAd(duration, reason?)Pause the ad being checked
pauseAd({ adId, duration, reason? })Pause another ad — for example, a neighbour from getAdset()
pauseAdset({ adsetId, duration, reason? })Pause the ad set
pauseCampaign({ campaignId, duration, reason? })Pause the campaign

For the ad being checked it's enough to pass the duration as a string; another ad, an ad set and a campaign are named in the object form with an explicit adId / adsetId / campaignId. An object named this way must be within the rule's reach — its scope, see Self-protection; an ad set or a campaign counts only when all of its ads do. Otherwise — another owner's object, an ad on an inactive ad account that Britva does not hold, or an id that does not exist — the call does nothing and leaves a warning line in the console; the rest of the rule works.

Durations (duration):

ValueMeaning
6h / 12h / 24hPause for N hours
next_day_target_geoUntil the start of the next day in the target country's time
next_day_ad_accountUntil the start of the next day in the ad account's time
permanentA permanent pause
while_matchesWhile the rule condition holds

How each duration ends — including the case when the time zone of the country or of the ad account is not known — is in Scheduling and pauses.

reason is an optional comment; if omitted, the rule name is used. The reason of an ad pause goes into the Telegram notification about the pause, while the pause's line in the Logs keeps its note for the result — empty when Facebook accepted the pause, otherwise the error. A pause of an ad set or a campaign and every return to work carry the reason in the note as reason=…. A reason, and an explicit target id, longer than 256 bytes is cut (ending in …). In one run a rule can create up to about as many actions as there are ads, ad sets and campaigns, plus a margin of 1,024; past that the run stops with an error.

Resume​

FunctionAction
activateAd({ adId, reason? })Lift this rule's pause from the ad adId
activateAdset({ adsetId, reason? })Lift this rule's pause from the ad set
activateCampaign({ campaignId, reason? })Lift this rule's pause from the campaign

A return function lifts only the pause that the same rule set: a pause held by another rule or by a script stays. Britva turns the object back on once nothing holds it any more — no rule and no script.

A rule checks running ads — and those released on the same pass — and skips an ad it holds itself; a while_matches pause is re-checked only to decide whether it stays, and the rule's other calls in that check are not carried out. That is why the short form activateAd(reason?), which addresses the ad being checked, lifts nothing: whenever the rule checks an ad, it holds no pause on it. Call activateAd({ adId }) while the rule checks another, running ad — for example, take the paused neighbour from getAdset() or getCampaign(). The same goes for an ad set and a campaign: their ads stop together with them, so the call has to come from a check of an ad outside them.

Neighboring ads​

Inside a rule, you can look at other ads in the same ad set or campaign — for example, to stop the whole ad set if only one ad dropped.

FunctionReturns
getAd(id)An ad by its ad_id
getAdset()All ads in the current ad's ad set
getCampaign()All ads in the current ad's campaign

Also available are console.log / console.warn / console.error for debug output and skipNextRules() — skip the remaining rules of the same scope (user, team or global) for this ad; rules of the other scopes still run.

Rule time limit​

Checking one ad gives a rule a short time limit; a rule that calls sql, fetch or ctx.state gets a longer one, which an administrator sets with the SQL: rule timeout, ms setting of the "Britva rule engine" job (the Services and jobs section, see Services and jobs). A rule that did not fit into its time limit is stopped: everything it managed to decide about this ad is canceled, and the ad moves on to the next rule.

The time limit also reaches code stuck inside a built-in operation: parsing a huge JSON, repeat with a huge number of repetitions, walking a huge array with empty slots with methods like forEach and map. If such an operation could not be interrupted in time, the check of this ad on the current pass ends at this rule: the decisions of the rules that triggered earlier are kept, and the rule itself is not run again until the end of the pass.

A search by a complex regular expression that could not be completed does not answer "no matches" but throws the error Regular expression match failed: …. Without a try…catch it acts like any rule error: the rule's decision about the ad is canceled. On the Test tab both cases are named in words — see Testing a rule.

A user script has one time limit for the whole run — see Time limit of a run.

Standard JavaScript​

Rules and scripts are executed by the same JavaScript engine, and their built-in objects are the same, including URL and URLSearchParams for parsing and building addresses. The list is in the Which standard JavaScript is available section. Rule code is compiled in JavaScript strict mode.

QubApp selectors (for scripts)​

In user scripts, the QubApp object is available — it selects ads, ad sets, and campaigns by conditions. Each selected element has its own statistics and pause methods.

MethodReturns a selection of
QubApp.ads()Ads
QubApp.adsets()Ad sets
QubApp.campaigns()Campaigns
QubApp.offers()Offers — see Offers below

Selection methods (chained):

MethodWhat it does
.withCondition(text)Filter by a condition — see Conditions in withCondition
.filter(fn)Filter with a function; it receives the element
.orderBy(field, dir)Sort by a numeric field ('asc' / 'desc')
.withLimit(n)Limit the number of elements
.get()Get an array of elements
.first()Get the first element

Element methods:

MethodAction
.pause({ duration, reason? })Pause — see When pause and activate take effect
.activate({ reason? })Resume
.getStatsFor(period)Metrics for a window ('1h'…'total')
.getAds()Ads inside an ad set / campaign
.getAdsets()Ad sets inside a campaign

getStatsFor returns a set of metrics for the selected window: spend, revenue, clicks, regs, deps, installs, roas, cpd, cpc, click2reg, reg2dep, ctr, i2r, i2d, c2i. Ad sets and campaigns have no ctr there.

An ad carries the fields of the ad object. The fields of an ad set and a campaign are added up from its ads: the identifiers and names (adset_id, adset_name, campaign_id, campaign_name, ad_account_id, buyer_id, team_id, traffic_source), the sums of spend, revenue, clicks, regs, deps and installs in every time window, and the ratios roas, cpd, cpc, click2reg, reg2dep, i2r, i2d, c2i counted from those sums. Unlike an ad's, these shares are plain fractions — 0.05, not 5 — and there is no ctr. Every element also has the short id and name.

Besides selections, in scripts QubApp has the QubApp.submitSpend(…) command — submitting to the reports the spend of a platform that has no export of its own into Qubix. Auto-pause rules do not have this command. More — Submitting spend: QubApp.submitSpend.

Conditions in withCondition​

The condition is a string with an expression over the fields of each element. It is written SQL-style: comparisons <, >, <=, >=, =, !=, the words AND, OR, NOT and parentheses; put spaces around =, AND and OR. A string value goes in quotes: primary_country = "BR". Under this notation lies a full expression language, so arithmetic (spend_24h > 2 * geo_avg_payout), field-to-field comparison (roas_24h < 0.5 * prev_roas_24h), a check against a list in square brackets (primary_country in ["TJ", "BR"]) and functions such as abs() work as well. The SQL-only forms IN (…), LIKE, BETWEEN, <> and IS NULL are not understood: such a condition throws an error at the .withCondition() call.

The condition sees the element's own fields by their full names — ad_name, campaign_name, spend_24h; the short id and name exist only on the element you get, not in the condition. A field the element does not have is empty, so =, < or > with it gives false — check the field name when a selection comes back empty.

When pause and activate take effect​

In a script, .pause() and .activate() of an ad, an ad set and a campaign do not act at the moment of the call: the requests are collected and carried out after the run ends — after main() and everything it left waiting. Hence:

  • the call returns undefined, and a refusal is not thrown into the code (except the action limit below): an object outside the script's data, or a network that did not take the command, is named in the run's line of the run history;
  • the new status cannot be read in the same run: the run works on a snapshot of the data taken before it;
  • what was requested before an error still goes out, even if the run then ended with an error.
  • a reason longer than 256 bytes is cut (ending in …); over the run's action limit — up to about as many pause/activate calls as there are ads, ad sets and campaigns the script sees, plus a margin — the call throws and the run ends.

duration takes the same values as in rules — the table above. Pauses for 6h, 12h, 24h and until midnight end on their own. 'permanent', 'while_matches', an empty duration, a value that is not in the table and a next_day_… pause whose time zone is not known do not: a script has no condition to re-check, and a value outside the table is not refused. Such an object stays paused until the script itself calls .activate() for it; a paused ad can also be turned back on by hand on the Paused tab. .activate() lifts only the script's own pause: while a rule or another script holds the object, it stays paused.

Which networks the actions reach​

Pauses and returns — of rules and of scripts alike — go to the ad's own network:

  • Facebook — the command goes out at once: a rule's on the same check pass, a script's right after the run, in the same queue per browser profile.
  • Google Ads — the command waits for the Qubix script in your Google Ads account and is applied when that script runs next; until then the ad keeps running.
  • TikTok — pausing and turning on are not available yet: the command ends with an error.

Offers​

QubApp.offers() gives the offers the script's owner may see. Its selection has only .get() and .first() — filter it in your own code. An offer carries id (the same as offer_id), name, state, cap, payout_value and network_id. Unlike ads, an offer's .pause() and .activate() change its status right away, at the moment of the call, and a refusal is thrown as an error — catch it with try…catch. .activate() of a paused offer that has no affiliate network is refused; .pause() of such an offer goes through.

Script context​

In scripts, the ctx object is additionally available. In auto-pause rules ctx has only ctx.state — the rule's own memory — together with the shared store ctx.state.global (below).

Field / methodPurpose
ctx.state.get/set/delete/keysPersisting state between runs
ctx.fetch(url, opts?)An HTTP request; the host must be on the allowlist (see System)
ctx.now()The current time
ctx.scriptInformation about the current script
Caution

In auto-pause rules an HTTP request is made with the global fetch(...) function, not ctx.fetch. Requests are real everywhere — in scripts, in the rule check cycle and in the rule test alike: the host must be on the allowlist.

Shared store​

Besides its private ctx.state, there is a shared store ctx.state.global, visible to every script, rule, and site handler at once.

MethodAction
ctx.state.global.get(key)Read a value
ctx.state.global.keys()List the keys
ctx.state.global.set(key, value)Write a value
ctx.state.global.delete(key)Delete a value

Any script or rule can read the shared store. Writing (set / delete) is allowed only from a script or rule owned by an administrator — otherwise the write throws an error. Handy for shared lookups: the administrator writes a value once, everyone else reads it.

Limits
  • ctx.fetch in scripts: the wait time, the response size and the number of calls are limited by the settings of the fetch limits block — Default timeout, Maximum timeout, Maximum response size and Calls per run.
  • fetch in auto-pause rules: the number of calls is limited by the fetch: max calls per tick setting of the "Britva rule engine" job; within one check pass the rules of buyers and teams share this limit, the global rules have their own limit of the same size, and one run of a rule test has the whole limit to itself.
  • sql: the number of rows in the answer to one query is limited — for scripts by the Max rows per query setting, for rules by the SQL: rows per query setting of the "Britva rule engine" job. For large selections, aggregate the data right in the query.

Script settings are on the JavaScript tab of the Qubix settings window (see System), rule settings — in the What you can configure group on the page of the "Britva rule engine" job (the Services and jobs section, see Services and jobs).

What state can store​

ctx.state and ctx.state.global save a value that fits into JSON: numbers, strings, true / false, null, arrays and plain objects. NaN, Infinity, a function, a date outside years 0–9999, an object that refers to itself and nesting deeper than 10,000 levels cannot be saved: set() throws an error right away, and the previous value under this key stays.

The error can be caught with try…catch, and the work goes on. If it is not caught:

  • in an auto-pause rule, this rule's decision about the ad is canceled — its pause or return is not performed, and the ad moves on to the next rule; the values the rule managed to save earlier stay;
  • on the Test tab, the ad goes into the count of ads with an error, and there is no decision for it;
  • in a script, the run stops with an error;
  • in a website page handler, the visitor gets an empty 500 response.

Read-only sql​

The tagged template sql`SELECT …` runs a read-only data query within the owner's permissions. It is available both in auto-pause rules (Britva) and in user scripts.

The main tables and their columns are described in Tables for sql queries; that page does not list every table a query can reach. The examples in this documentation also read v_ads_stats — one row per ad with the fields of the ad object — and hourly_insights, the hourly statistics: an hour can have several versions there, so take the latest one with argMax(…, parsed_at), as the hourly example in Script examples does.

Qubix tools: QubApp.mcp​

A rule can read the tools of this Qubix installation — the same ones an external program reaches over MCP/API — with the rights of the rule's owner: QubApp.mcp.get_dashboard({…}), QubApp.mcp.get_offers_list({…}) and every other READING tool the owner may use. A tool that changes data is refused in a rule — writing is left to a script, where the owner confirms the code it runs. Pause and resume a rule does with its own pauseAd/activateAd, not through QubApp.mcp. A team or a global rule has no person to act for, and its calls are refused. checkAd runs once per ad, so one rule may make as many calls per check cycle as the operator's limit allows — for all its ads together. The Test tab runs QubApp.mcp with the rights of whoever started the test. More — Qubix tools from code.

Your own databases — in scripts, not in rules​

User scripts (and website page handlers) also have the Qubix.db command — a connection to your own database with reading and writing; which databases it connects to is listed in Your own databases: Qubix.db. Auto-pause rules do not have this command.

What's next​