carlos / platform Public

usage: the per-instance day family and its keys

InstanceDay, InstanceCount, InstanceBucket, key builders and parser,
DecodeInstanceDay, Merge, HourDate, InstanceFrom, and EdgeFlush.Instances
(ignored by UpsertEdgeDay). Size fixture measured 128/143/283/392 bytes a
row, matching the spec table.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 1e8d79da325ded7914401ce8a17b5daf09e4ac8a parent 1b6a8b9
3 files changed, +313 −0
  • internal/usage/edge.go +3 −0
  • internal/usage/instances.go +145 −0
  • internal/usage/instances_test.go +165 −0

CI cancelled — superseded by a newer push — run details

CI log
=== gate ===
go: downloading go1.26.10 (linux/arm64)
go version go1.26.10 linux/arm64
opentofu: arm64, tofu 1.13.9, aws 6.73.0, archive 2.8.1
  tofu: downloading https://carlos-ci-mirror-640012953448.s3.eu-west-1.amazonaws.com/opentofu/tofu_1.13.9_linux_arm64.tar.gz
  tofu: downloaded, digest verified
  aws: downloading https://carlos-ci-mirror-640012953448.s3.eu-west-1.amazonaws.com/opentofu/terraform-provider-aws_6.73.0_linux_arm64.zip
  aws: downloaded, digest verified
  archive: downloading https://carlos-ci-mirror-640012953448.s3.eu-west-1.amazonaws.com/opentofu/terraform-provider-archive_2.8.1_linux_arm64.zip
  archive: downloaded, digest verified
  installed in /tmp/carlos-opentofu-rEGl20
.amadan/test-gate.sh
go: downloading github.com/aws/aws-sdk-go-v2/service/cloudwatch v1.68.0
go: downloading github.com/aws/aws-sdk-go-v2/service/costexplorer v1.67.5
go: downloading golang.org/x/crypto/x509roots/fallback v0.0.0-20260209214922-2f26647a795e
go: downloading golang.org/x/net v0.62.0
go: downloading modernc.org/sqlite v1.55.0
go: downloading golang.org/x/sys v0.49.0
go: downloading golang.org/x/mod v0.41.0
go: downloading golang.org/x/crypto v0.58.0
go: downloading github.com/aws/aws-sdk-go-v2/service/ec2 v1.324.0
go: downloading github.com/pierrec/lz4/v4 v4.1.22
go: downloading github.com/beorn7/perks v1.0.1
go: downloading github.com/cespare/xxhash/v2 v2.3.0
go: downloading github.com/prometheus/common v0.45.0
go: downloading github.com/prometheus/procfs v0.12.0
go: downloading google.golang.org/protobuf v1.36.10
go: downloading github.com/aws/aws-sdk-go-v2/service/internal/s3shared v1.19.31
go: downloading github.com/pion/dtls/v3 v3.1.4
go: downloading github.com/klauspost/compress v1.20.2
go: downloading github.com/wlynxg/anet v0.0.5
go: downloading github.com/matttproud/golang_protobuf_extensions/v2 v2.0.0
go: downloading golang.org/x/text v0.43.0
go: downloading modernc.org/sqlite v1.55.0
go: downloading github.com/klauspost/compress v1.20.2
go: downloading github.com/aws/aws-sdk-go-v2/service/ecs v1.91.0
go: downloading github.com/pierrec/lz4/v4 v4.1.22
go: downloading modernc.org/libc v1.74.1
go: downloading modernc.org/libc v1.74.1
go: downloading modernc.org/mathutil v1.7.1
go: downloading modernc.org/memory v1.11.0
go: downloading github.com/google/uuid v1.6.0
go: downloading github.com/dustin/go-humanize v1.0.1
go: downloading modernc.org/mathutil v1.7.1
go: downloading github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec

amadan: job cancelled — a newer push superseded it
diff --git a/internal/usage/edge.go b/internal/usage/edge.go
index e1104b6bc..839a50afe 100644
--- a/internal/usage/edge.go
+++ b/internal/usage/edge.go
@@ -114,6 +114,9 @@ func AddGroup(groups map[string]int64, group string, n int64) {
type EdgeFlush struct {
Rows map[string]EdgeRow
Guard map[string]GuardDelta
+ // Instances is the per-instance meter's drain. UpsertEdgeDay ignores it:
+ // it belongs to the usage/instances/ family, not the old day file.
+ Instances map[InstanceBucket]InstanceCount
}
// SetOwner labels the row with the route's current account and app. When
diff --git a/internal/usage/instances.go b/internal/usage/instances.go
new file mode 100644
index 000000000..f88a0b357
--- /dev/null
+++ b/internal/usage/instances.go
@@ -0,0 +1,145 @@
+package usage
+
+import (
+ "encoding/json"
+ "errors"
+ "fmt"
+ "strings"
+ "time"
+)
+
+// InstancesPrefix is the family of per-instance day objects, outside
+// usage/edge/ so the economics sweep's box discovery never sees it.
+const InstancesPrefix = "usage/instances/"
+
+// InstanceFromKey is the attribution start. "@" is allowed in no box label,
+// so it never collides with a box directory.
+const InstanceFromKey = "usage/instances/@from.json"
+
+// InstanceBucket is one meter key: the Unix hour (seconds/3600) the
+// exchange completed in, and the route row's owner and instance host.
+type InstanceBucket struct {
+ Hour int64
+ Account, App, Instance string
+}
+
+// InstanceCount is one instance's counts. The hop fields are the existing
+// subset annotation: inside the totals, never added to them.
+type InstanceCount struct {
+ Requests int64 `json:"requests"`
+ BytesOut int64 `json:"bytes_out"`
+ HopRequests int64 `json:"hop_requests,omitempty"`
+ HopBytesOut int64 `json:"hop_bytes_out,omitempty"`
+}
+
+// Add sums o into c.
+func (c *InstanceCount) Add(o InstanceCount) {
+ c.Requests += o.Requests
+ c.BytesOut += o.BytesOut
+ c.HopRequests += o.HopRequests
+ c.HopBytesOut += o.HopBytesOut
+}
+
+// InstanceDay is one app's counts on one box and date.
+type InstanceDay struct {
+ V int `json:"v"` // 1
+ Box string `json:"box"`
+ Date string `json:"date"`
+ Account string `json:"account"`
+ App string `json:"app"`
+ Applied map[string]string `json:"applied"` // writer id -> last batch id
+ Instances map[string]InstanceCount `json:"instances"` // host -> counts; "" = unattributable
+}
+
+// ErrInstanceKey is returned for a key built from an unsafe segment or date.
+var ErrInstanceKey = errors.New("usage: not a safe instance usage key")
+
+// ErrInstanceDayMismatch is returned when a day's body disagrees with its key.
+var ErrInstanceDayMismatch = errors.New("usage: instance day does not match its key")
+
+const instanceDateLayout = "2006-01-02"
+
+// instanceSegment reports whether s is one plain key segment: not empty, not
+// "." or "..", no slash (the console's keySegment rule).
+func instanceSegment(s string) bool {
+ return s != "" && s != "." && s != ".." && !strings.Contains(s, "/")
+}
+
+// InstanceDayKey is usage/instances/<box>/<date>/<account>/<app>.json.
+func InstanceDayKey(box, date, account, app string) (string, error) {
+ for _, s := range []string{box, date, account, app} {
+ if !instanceSegment(s) {
+ return "", ErrInstanceKey
+ }
+ }
+ if _, err := time.Parse(instanceDateLayout, date); err != nil {
+ return "", ErrInstanceKey
+ }
+ return InstancesPrefix + box + "/" + date + "/" + account + "/" + app + ".json", nil
+}
+
+// ParseInstanceDayKey is the inverse of InstanceDayKey.
+func ParseInstanceDayKey(key string) (box, date, account, app string, ok bool) {
+ rest, found := strings.CutPrefix(key, InstancesPrefix)
+ if !found {
+ return "", "", "", "", false
+ }
+ rest, found = strings.CutSuffix(rest, ".json")
+ if !found {
+ return "", "", "", "", false
+ }
+ parts := strings.Split(rest, "/")
+ if len(parts) != 4 {
+ return "", "", "", "", false
+ }
+ box, date, account, app = parts[0], parts[1], parts[2], parts[3]
+ if got, err := InstanceDayKey(box, date, account, app); err != nil || got != key {
+ return "", "", "", "", false
+ }
+ return box, date, account, app, true
+}
+
+// DecodeInstanceDay parses raw and checks it names the same box, date,
+// account and app as key.
+func DecodeInstanceDay(key string, raw []byte) (InstanceDay, error) {
+ var d InstanceDay
+ if err := json.Unmarshal(raw, &d); err != nil {
+ return InstanceDay{}, fmt.Errorf("usage: parse %s: %w", key, err)
+ }
+ box, date, account, app, ok := ParseInstanceDayKey(key)
+ if !ok {
+ return InstanceDay{}, fmt.Errorf("%w: %s", ErrInstanceKey, key)
+ }
+ if d.V != 1 || d.Box != box || d.Date != date || d.Account != account || d.App != app {
+ return InstanceDay{}, fmt.Errorf("%w: %s", ErrInstanceDayMismatch, key)
+ }
+ return d, nil
+}
+
+// Merge sums counts into the day and records batch as writer's last batch.
+// It never removes another writer's marker.
+func (d *InstanceDay) Merge(writer, batch string, counts map[string]InstanceCount) {
+ if d.Applied == nil {
+ d.Applied = map[string]string{}
+ }
+ if d.Instances == nil {
+ d.Instances = map[string]InstanceCount{}
+ }
+ for host, c := range counts {
+ cur := d.Instances[host]
+ cur.Add(c)
+ d.Instances[host] = cur
+ }
+ d.Applied[writer] = batch
+}
+
+// HourDate is the UTC date of a Unix hour.
+func HourDate(hour int64) string {
+ return time.Unix(hour*3600, 0).UTC().Format(instanceDateLayout)
+}
+
+// InstanceFrom is the attribution start object.
+type InstanceFrom struct {
+ From string `json:"from"` // first day of a UTC month, "2006-01-02"
+ Activation time.Time `json:"activation"` // HostsState.At when written
+}
diff --git a/internal/usage/instances_test.go b/internal/usage/instances_test.go
new file mode 100644
index 000000000..7a464dfaa
--- /dev/null
+++ b/internal/usage/instances_test.go
@@ -0,0 +1,165 @@
+package usage
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "reflect"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/carlosframework/platform/internal/release"
+)
+
+func TestInstanceDayKeyRoundTrip(t *testing.T) {
+ key, err := InstanceDayKey("box-1", "2026-11-30", "bab", "patrix-sites")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if want := "usage/instances/box-1/2026-11-30/bab/patrix-sites.json"; key != want {
+ t.Fatalf("key = %q, want %q", key, want)
+ }
+ box, date, account, app, ok := ParseInstanceDayKey(key)
+ if !ok || box != "box-1" || date != "2026-11-30" || account != "bab" || app != "patrix-sites" {
+ t.Fatalf("parse = %q %q %q %q %v", box, date, account, app, ok)
+ }
+ if _, _, _, _, ok := ParseInstanceDayKey(InstanceFromKey); ok {
+ t.Fatal("@from.json parsed as a day key")
+ }
+}
+
+func TestInstanceDayKeyRefusesUnsafe(t *testing.T) {
+ for _, bad := range []string{"", ".", "..", "a/b"} {
+ args := [][4]string{
+ {bad, "2026-11-30", "bab", "app"},
+ {"box", bad, "bab", "app"},
+ {"box", "2026-11-30", bad, "app"},
+ {"box", "2026-11-30", "bab", bad},
+ }
+ for _, a := range args {
+ if _, err := InstanceDayKey(a[0], a[1], a[2], a[3]); !errors.Is(err, ErrInstanceKey) {
+ t.Errorf("%q: err = %v, want ErrInstanceKey", a, err)
+ }
+ }
+ }
+ if _, err := InstanceDayKey("box", "2026-13-01", "bab", "app"); !errors.Is(err, ErrInstanceKey) {
+ t.Fatalf("bad date: err = %v", err)
+ }
+}
+
+func TestDecodeInstanceDayChecksKey(t *testing.T) {
+ key, _ := InstanceDayKey("box-1", "2026-11-30", "bab", "shop")
+ good := InstanceDay{V: 1, Box: "box-1", Date: "2026-11-30", Account: "bab", App: "shop",
+ Instances: map[string]InstanceCount{"": {Requests: 1}}}
+ raw, _ := json.Marshal(good)
+ got, err := DecodeInstanceDay(key, raw)
+ if err != nil || got.Instances[""].Requests != 1 {
+ t.Fatalf("good: %+v %v", got, err)
+ }
+ for name, mut := range map[string]func(*InstanceDay){
+ "v": func(d *InstanceDay) { d.V = 2 },
+ "box": func(d *InstanceDay) { d.Box = "box-2" },
+ "date": func(d *InstanceDay) { d.Date = "2026-11-29" },
+ "account": func(d *InstanceDay) { d.Account = "bdk" },
+ "app": func(d *InstanceDay) { d.App = "other" },
+ } {
+ d := good
+ mut(&d)
+ raw, _ := json.Marshal(d)
+ if _, err := DecodeInstanceDay(key, raw); !errors.Is(err, ErrInstanceDayMismatch) {
+ t.Errorf("%s: err = %v, want ErrInstanceDayMismatch", name, err)
+ }
+ }
+ if _, err := DecodeInstanceDay(key, []byte("{")); err == nil || errors.Is(err, ErrInstanceDayMismatch) {
+ t.Errorf("bad json: err = %v", err)
+ }
+}
+
+func TestMergeKeepsEveryMarker(t *testing.T) {
+ var d InstanceDay
+ d.Merge("A", "1", map[string]InstanceCount{"h": {Requests: 1, BytesOut: 10}, "": {Requests: 1}})
+ d.Merge("B", "1", map[string]InstanceCount{"h": {Requests: 2, BytesOut: 20, HopRequests: 1, HopBytesOut: 5}})
+ d.Merge("A", "2", map[string]InstanceCount{"h": {Requests: 4, BytesOut: 40}})
+ if want := map[string]string{"A": "2", "B": "1"}; !reflect.DeepEqual(d.Applied, want) {
+ t.Fatalf("Applied = %v, want %v", d.Applied, want)
+ }
+ if want := (InstanceCount{Requests: 7, BytesOut: 70, HopRequests: 1, HopBytesOut: 5}); d.Instances["h"] != want {
+ t.Fatalf("h = %+v, want %+v", d.Instances["h"], want)
+ }
+ if d.Instances[""].Requests != 1 {
+ t.Fatalf("unattributable = %+v", d.Instances[""])
+ }
+}
+
+// Pins behaviour: UpsertEdgeDay never looked at Instances, so this passes as
+// soon as EdgeFlush has the field.
+func TestUpsertEdgeDayIgnoresInstances(t *testing.T) {
+ s := release.NewDirStore(t.TempDir())
+ f := EdgeFlush{Instances: map[InstanceBucket]InstanceCount{
+ {Hour: 1, Account: "bab", App: "shop", Instance: "a.example.com"}: {Requests: 1},
+ }}
+ at := time.Date(2026, 11, 30, 9, 0, 0, 0, time.UTC)
+ if err := UpsertEdgeDay(context.Background(), s, "box1", at, f); err != nil {
+ t.Fatal(err)
+ }
+ keys, err := s.List(context.Background(), "usage/")
+ if err != nil || len(keys) != 0 {
+ t.Fatalf("keys = %v, err = %v; want none", keys, err)
+ }
+}
+
+func TestHourDate(t *testing.T) {
+ for _, c := range []struct {
+ at time.Time
+ want string
+ }{
+ {time.Date(2026, 11, 30, 23, 58, 30, 0, time.UTC), "2026-11-30"},
+ {time.Date(2026, 12, 1, 0, 3, 0, 0, time.UTC), "2026-12-01"},
+ } {
+ if got := HourDate(c.at.Unix() / 3600); got != c.want {
+ t.Errorf("HourDate(%v) = %q, want %q", c.at, got, c.want)
+ }
+ }
+}
+
+func TestInstanceDaySizeTable(t *testing.T) {
+ host := func(n int, tag byte) string { return strings.Repeat(string(tag), n) }
+ counter := func(digits int) int64 {
+ v := int64(1)
+ for i := 1; i < digits; i++ {
+ v = v*10 + 1
+ if i == 18 {
+ break
+ }
+ }
+ return v
+ }
+ size := func(n, hostLen, digits int) int {
+ d := InstanceDay{V: 1, Box: "b", Date: "2026-11-30", Account: "a", App: "p",
+ Applied: map[string]string{}, Instances: map[string]InstanceCount{}}
+ c := counter(digits)
+ for i := 0; i < n; i++ {
+ h := []byte(host(hostLen, 'h'))
+ h[0], h[1], h[2], h[3] = byte('a'+i/17576%26), byte('a'+i/676%26), byte('a'+i/26%26), byte('a'+i%26)
+ d.Instances[string(h)] = InstanceCount{Requests: c, BytesOut: c, HopRequests: c, HopBytesOut: c}
+ }
+ raw, err := json.Marshal(d)
+ if err != nil {
+ t.Fatal(err)
+ }
+ return len(raw)
+ }
+ for _, f := range []struct{ host, digits, want int }{
+ {25, 10, 128}, {32, 12, 143}, {144, 19, 283}, {253, 19, 392},
+ } {
+ per := size(11, f.host, f.digits) - size(10, f.host, f.digits)
+ if per < f.want-3 || per > f.want+3 {
+ t.Errorf("host %d digits %d: %d bytes a row, want %d +-3", f.host, f.digits, per, f.want)
+ }
+ t.Logf("host %d digits %d: %d bytes a row", f.host, f.digits, per)
+ }
+ if n := size(10000, 253, 19); n >= 8<<20 {
+ t.Errorf("10,000 rows = %d bytes, want under 8 MiB", n)
+ }
+}