Skip to content

Commit 637848e

Browse files
authored
Merge pull request #18 from typetorch/feat/analytics-positions
analytics: positions on events (px/py/pz) and recordSeconds
2 parents 14db82d + 1feeab8 commit 637848e

14 files changed

Lines changed: 497 additions & 36 deletions

‎README.md‎

Lines changed: 16 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -511,6 +511,7 @@ import { AnalyticsEngine } from "@typetorch/framework";
511511
// A server module (onInit): the sink comes from the signed settings' `analytics` (kernel 0.3.8).
512512
const analytics = new AnalyticsEngine();
513513
analytics.track(player, "quest_done", { quest: "tutorial" }); // custom
514+
analytics.track(player, "down", { by: "fall" }, { position: true }); // + px, py, pz of the player's character
514515
analytics.step(player, "onboarding", 3, "opened_shop"); // funnels
515516
analytics.purchase(player, { product: 1234, robux: 99, where: "shop" }); // after the receipt is granted
516517
analytics.currency(player, "coins", 50, "round_reward"); // economy in (+) and out (-)
@@ -539,6 +540,14 @@ const variant = analytics.experiment("onboarding", ["short", "long"]); // same a
539540
`TTScreen`), `recording` (the first-ever session in detail), `fleet` (kernel 0.3.2 heartbeats and deploy reports),
540541
`identity` (one `{ pid, uid }` row per session to the dev's own server, below). `settings` (server only) replaces the
541542
signed settings' `analytics`, for tests, Studio and kernels before 0.3.8.
543+
- **Positions on events** (for map layers): `px`, `py`, `pz` props (studs, rounded to 0.1) from a character's root
544+
part. Per call: `track(player, name, props, { position: true })` (the event's player; on the client the local
545+
player) or `{ position: otherPlayer }`. Per event name: `new AnalyticsEngine({ positions: ["down", "death_final",
546+
"round_result", "product"] })` (code), or the settings' `positions` (live, added to the code's list): every
547+
`track`, `step`, `purchase` and `currency` event with that name gets the event player's position (a purchase is
548+
named by its `kind`, `product` by default). No character or root part: nothing is added. Props that already have
549+
`px`, `py` or `pz` are left alone. One property read per such event, nothing per frame. Server-only events (no
550+
player) only get one with `{ position: somePlayer }`.
542551
- **Every row** carries the time (server clock), a random player id (never the UserId), the session, the server
543552
(JobId, type, place), the artifact (id, seq, branch, channel), the device, new vs returning, the player's state
544553
(`zone:Lobby|screen:Shop|activity:round`) and experiment variants. The exact rows: `src/analytics/SCHEMA.md`.
@@ -550,8 +559,11 @@ const variant = analytics.experiment("onboarding", ["short", "long"]); // same a
550559
experiment weights | settle | stop | resume | clear | force | unforce`.
551560
- **First-ever session:** for new players (a share of them, `recordShare`), the client records character and camera
552561
about 10 times a second, every input (never while a TextBox or the chat has focus; text boxes only say which box was
553-
used), buttons pressed and hovered, screens, prompts and deaths, from the join until 60 s after the first input.
554-
Packed into small binary chunks (10-20 KB a player) and sent through the server.
562+
used), buttons pressed and hovered, screens, prompts and deaths, from the join until `recordSeconds` (the settings,
563+
default 60, 10..600) after the first input, and at most 10 minutes in all. Packed into small binary chunks and sent
564+
through the server: about 13 KB a minute for an active player (18 KB as stored base64), under 1 KB for an idle one;
565+
the per-recording caps (256 KB, 80 chunks) still apply, and 10 minutes of an active player fit inside them. Set
566+
`recordSeconds` to the length of your first round (e.g. 300) to record it whole.
555567
- **Never collected:** chat or anything typed, usernames and display names (error texts have them replaced). No event
556568
row carries a UserId.
557569
- **Identities** (option `identity`, default on): once the pid is known, one row `{ pid, uid, t }` (the UserId, nothing
@@ -587,7 +599,7 @@ const variant = analytics.experiment("onboarding", ["short", "long"]); // same a
587599
when the player is alone) intersected with the players there, not a web call per player.
588600

589601
**Settings, framework 0.4.0 / kernel 0.4.0 (plans/21):** the record's `backend` = `{ url, key, analytics?: { flushSeconds,
590-
recordShare, joinLaunchPrefix, joinData } }` (`typetorch backend setup`) is the whole sink: DuckDB at `<url>/v1/ingest` with the one key (Basin
602+
recordShare, recordSeconds, positions, joinLaunchPrefix, joinData } }` (`typetorch backend setup`) is the whole sink: DuckDB at `<url>/v1/ingest` with the one key (Basin
591603
identities to `<url>/v1/identity`). The old `analytics` value below is read while `backend` is missing, and stays the
592604
way to a Basin sink. The engine also tells the kernel each player's pid (`setAnalyticsId`: the kernel's error reports
593605
count affected players by pid, never by name) and counts its own DataStore and HTTP requests for the budget view (dev
@@ -602,7 +614,7 @@ there are no settings unless the game passes `new AnalyticsEngine({ settings })`
602614
```json
603615
{ "backend": "basin", "events": "https://<stream-id>.ingest.cloudflare.com",
604616
"recordings": "https://<stream-id>.ingest.cloudflare.com", "token": "<write-only token>",
605-
"flushSeconds": 15, "recordShare": 1, "techEvery": 60,
617+
"flushSeconds": 15, "recordShare": 1, "recordSeconds": 60, "positions": ["round_result"], "techEvery": 60,
606618
"experiments": { "onboarding": { "weights": [1, 1] } } }
607619
```
608620

‎scripts/test-analytics-client.luau‎

Lines changed: 54 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -320,7 +320,7 @@ end
320320

321321
-- Start --------------------------------------------------------------------------------------------------------------
322322
local trove = Trove.new()
323-
local client = ClientAnalytics.new({}, dispatcher, trove)
323+
local client = ClientAnalytics.new({ positions = { "down" } }, dispatcher, trove)
324324
task.wait(0.05)
325325
local hello = messages("hello")[1]
326326
check("hello sent", hello ~= nil)
@@ -335,6 +335,7 @@ raw["__tt/an"]("hi", {
335335
rec = true,
336336
tech = 60,
337337
exps = { onboarding = { variant = "long" } },
338+
pos = { "round_result" },
338339
})
339340
local events = heldEvents()
340341
check("hi releases held events", #events >= 2, #events)
@@ -353,6 +354,29 @@ client:experiment("onboarding", { "short", "long" })
353354
check("exp sent once", #messages("exp") == 1 and messages("exp")[1][2] == "onboarding")
354355
check("bad experiment = control", client:experiment("bad name!", { "a", "b" }) == "a")
355356

357+
-- Positions: the local player's character root (10, 3, -5) as px/py/pz, by options, by the hello's list, on request.
358+
client:track("custom", "down", nil)
359+
client:track("custom", "round_result", { a = 1 })
360+
client:track("custom", "down", { px = 5 })
361+
client:track("custom", "tap", nil)
362+
client:track("custom", "tap_at", nil, localPlayer)
363+
localPlayer.Character = nil
364+
client:track("custom", "down", { nochar = true })
365+
localPlayer.Character = character
366+
client:flush()
367+
local positioned = {}
368+
for _, event in heldEvents() do
369+
positioned[event[3]] = positioned[event[3]] or {}
370+
table.insert(positioned[event[3]], serde.decode("json", event[4]))
371+
end
372+
local downEvents = positioned.down or {}
373+
check("client position by options.positions", downEvents[1] and downEvents[1].px == 10 and downEvents[1].py == 3 and downEvents[1].pz == -5)
374+
check("client position by the hello's positions", positioned.round_result and positioned.round_result[1].pz == -5 and positioned.round_result[1].a == 1)
375+
check("client never overrides the game's px", downEvents[2] and downEvents[2].px == 5 and downEvents[2].py == nil)
376+
check("client: unlisted event has none", positioned.tap and positioned.tap[1].px == nil)
377+
check("client position on request", positioned.tap_at and positioned.tap_at[1].px == 10)
378+
check("client: no character, no position", downEvents[3] and downEvents[3].nochar == true and downEvents[3].px == nil)
379+
356380
-- Recorder -----------------------------------------------------------------------------------------------------------
357381
for _ = 1, 5 do
358382
root.Position += Vector3.new(1, 0, 0)
@@ -487,6 +511,35 @@ check("activity once", activities == 1)
487511
check("load only once", messages("hello")[1][2].load == nil)
488512
trove2:clean()
489513

514+
-- recordSeconds: the hello's window (rsec) replaces the 60 s; clamped to 10..600.
515+
local recordWindow = loadAnalytics("client").recordWindow
516+
check("window default 60", recordWindow(nil) == 60 and recordWindow("x") == 60 and recordWindow(0 / 0) == 60)
517+
check("window longer", recordWindow(180) == 180)
518+
check("window clamped", recordWindow(5000) == 600 and recordWindow(2) == 10)
519+
persist["__typetorch/analytics-client.v1"] = nil
520+
sent = {}
521+
local trove3 = Trove.new()
522+
ClientAnalytics.new({}, dispatcher, trove3)
523+
raw["__tt/an"]("hi", { pid = string.rep("cd", 16), newp = true, rec = true, tech = 60, exps = {}, rsec = 120 })
524+
step(0.1)
525+
services.UserInputService.InputBegan:Fire({ UserInputType = Enum.UserInputType.Keyboard, KeyCode = Enum.KeyCode.W, Position = Vector3.new() }, false)
526+
local inputAt = fakeNow
527+
fakeNow = inputAt + 61
528+
step(0.5)
529+
local function ended()
530+
for _, chunk in messages("rec") do
531+
if chunk[6] == true then
532+
return chunk[7]
533+
end
534+
end
535+
return nil
536+
end
537+
check("a 120 s window still records at 61 s", ended() == nil, ended())
538+
fakeNow = inputAt + 120
539+
step(0.5)
540+
check("a 120 s window ends at 120 s", ended() == "window", ended())
541+
trove3:clean()
542+
490543
print(`analytics client: {passed} passed, {failed} failed`)
491544
if failed > 0 then
492545
process.exit(1)

‎scripts/test-analytics-server.luau‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -489,8 +489,11 @@ local options = {
489489
token = "TKN-secret",
490490
flushSeconds = 5,
491491
experiments = { qa = { active = false, players = { ["2"] = "b" } } },
492+
recordSeconds = 180,
493+
positions = { "round_result" },
492494
},
493495
zones = false,
496+
positions = { "down" },
494497
}
495498
local trove1 = Trove.new()
496499
local core1 = ServerAnalytics.new(options, { trove = trove1, server = kernel }, trove1)
@@ -508,6 +511,8 @@ local hiReg = hiFor(regular)
508511
check("hi: new player", hiNew ~= nil and hiNew.pid == newbiePid and hiNew.newp == true and hiNew.rec == true, hiNew and hiNew.pid)
509512
check("hi: returning player", hiReg ~= nil and hiReg.newp == false and hiReg.rec == false)
510513
check("hi: tech interval", hiNew.tech == 60)
514+
check("hi: recording window (recordSeconds)", hiNew.rsec == 180, hiNew.rsec)
515+
check("hi: the settings' position names", hiNew.pos ~= nil and #hiNew.pos == 1 and hiNew.pos[1] == "round_result")
511516
-- Per-player overrides: each hello carries only its own player's entry, never the others' ids.
512517
check("hi: own forced variant only", hiReg.exps.qa ~= nil and hiReg.exps.qa.player == "b" and hiReg.exps.qa.players == nil and hiReg.exps.qa.active == false)
513518
check("hi: no entry, no player", hiNew.exps.qa ~= nil and hiNew.exps.qa.player == nil and hiNew.exps.qa.players == nil)
@@ -625,6 +630,37 @@ core1:track(newbie, "custom", "after_exp", nil)
625630
local rows = store().events.rows
626631
local quest = rowsNamed(rows, "custom", "quest_done")[1]
627632
check("track: row", quest and quest.pid == newbiePid and quest.props == '{"quest":"tutorial"}' and quest.src == "server")
633+
-- Positions: px/py/pz of the character root, rounded to 0.1, on request or by event name; never over the game's own.
634+
local newbieRoot = { Position = roblox.Vector3.new(10.04, 3.06, -5.56) }
635+
function newbieRoot:IsA(class)
636+
return class == "BasePart"
637+
end
638+
newbie.Character = {}
639+
function newbie.Character:FindFirstChild(name)
640+
return if name == "HumanoidRootPart" then newbieRoot else nil
641+
end
642+
core1:track(newbie, "custom", "tapped", { a = 1 }, newbie)
643+
core1:track(newbie, "custom", "down", { by = "fall" })
644+
core1:track(newbie, "custom", "round_result", nil)
645+
core1:track(newbie, "custom", "down", { px = 1, py = 2, pz = 3 })
646+
core1:track(newbie, "custom", "seen_regular", nil, regular) -- the regular has no character
647+
core1:track(nil, "custom", "down", nil) -- no player: nothing to read
648+
core1:track(newbie, "funnel", "down", { i = 1 })
649+
local function propsOf(name, index, kind)
650+
local row = rowsNamed(store().events.rows, kind or "custom", name)[index or 1]
651+
return row and serde.decode("json", row.props) or {}, row and row.props
652+
end
653+
local tapped, tappedText = propsOf("tapped")
654+
check("position on request: rounded", tapped.px == 10 and tapped.py == 3.1 and tapped.pz == -5.6 and tapped.a == 1, tappedText)
655+
local downs = rowsNamed(store().events.rows, "custom", "down")
656+
check("position by options.positions", #downs == 3 and serde.decode("json", downs[1].props).pz == -5.6 and serde.decode("json", downs[1].props).by == "fall", downs[1] and downs[1].props)
657+
check("position by the settings' positions", propsOf("round_result").py == 3.1)
658+
check("position never overrides the game's px/py/pz", downs[2] and downs[2].props == '{"px":1,"py":2,"pz":3}' or false, downs[2] and downs[2].props)
659+
check("position: none without a character", propsOf("seen_regular").px == nil and select(2, propsOf("seen_regular")) == "{}")
660+
check("position: none for a server-only event", downs[3] and downs[3].props == "{}" and downs[3].pid == "", downs[3] and downs[3].props)
661+
check("position on other game-code kinds (funnel) by name", propsOf("down", 1, "funnel").px == 10)
662+
check("quest_done untouched (not listed)", rowsNamed(store().events.rows, "custom", "quest_done")[1].props == '{"quest":"tutorial"}')
663+
newbie.Character = nil
628664
local serverThing = rowsNamed(rows, "custom", "server_thing")[1]
629665
check("server-only event", serverThing and serverThing.pid == "" and serverThing.sid == "" and serverThing.dev == "unknown" and serverThing.props == "{}")
630666
check("activity rows per player", #rowsNamed(rows, "state", "activity") == 2)
@@ -691,6 +727,8 @@ check("recording data", buffer.tostring(C.fromBase64(recs[1].data)) == buffer.to
691727
check("recording t", math.abs(recs[1].t - (nowMs() - 1000 - 50)) < 200)
692728
local metaEnd = rowsNamed(store().events.rows, "recording_meta", "end")[1]
693729
check("recording_meta start + end", #rowsNamed(store().events.rows, "recording_meta", "start") == 1 and metaEnd and serde.decode("json", metaEnd.props).why == "window")
730+
local metaStart = rowsNamed(store().events.rows, "recording_meta", "start")[1]
731+
check("recording_meta start: share and window", metaStart and serde.decode("json", metaStart.props).secs == 180 and serde.decode("json", metaStart.props).share == 1, metaStart and metaStart.props)
694732

695733
-- Fleet rows: a heartbeat at start, the replayed reports once each.
696734
check("fleet heartbeat", #rowsNamed(store().fleet.rows, "fleet", "heartbeat") == 1)

0 commit comments

Comments
 (0)