Skip to content

Add the database monitoring agent Terraform module - #123

Merged
anchoo2kewl merged 8 commits into
masterfrom
feat/database-monitoring-module
Sep 24, 2026
Merged

anchoo2kewl merged 8 commits into
masterfrom
feat/database-monitoring-module

Conversation

@anchoo2kewl

@anchoo2kewl anchoo2kewl commented Sep 24, 2026 •

Copy link
Copy Markdown
Contributor

Adds database-monitoring/terraform: the module that runs the Elastio database monitoring agent on AWS Fargate (elastio/blue-stack#17072). It is published as aws-elastio-database-monitoring-agent 0.1.0, so the registry source is terraform.cloudsmith.io/public/elastio-database-monitoring-agent/aws.

Source: deploy/terraform/aws-fargate at tag agent-v0.1.3 in the old agent repository, adapted for this repo.

Changes from the source module

  • The image default is now public.ecr.aws/elastio/elastio-database-monitoring-agent:0.1.4. That image is not published yet.
  • All customer-visible names now use the elastio-dbmon prefix:
    • log group /elastio-dbmon/agent/<name>
    • secrets elastio-dbmon/<name>/{api-key,database-url,hash-secret}-*
    • roles elastio-dbmon-<name16>-{exec,task}-*
    • EFS security group elastio-dbmon-<name16>-efs-*
    • EFS Name tag elastio-dbmon-<name>-ledger
    • access point root /elastio-dbmon
    • inline policies read-elastio-dbmon-secrets and mount-elastio-dbmon-ledger
    • container elastio-dbmon-agent
    • resource descriptions
  • The name used in IAM role prefixes is cut to 16 characters. With the new prefix, the old 20-character cut exceeded IAM's 38-character limit for name_prefix.
  • The EFS creation_token is removed and the provider generates one. The old token was built from the full name, so it broke EFS's 64-character limit for long names.
  • IAM policies are now jsonencode, not data "aws_iam_policy_document", to follow this repo's convention (Replace data "aws_iam_policy_document" with manual jsonencode #109).
  • The log driver region is now read from the log group ARN. data.aws_region's name and id are both deprecated in AWS provider 6, and required_providers is now aws >= 5.0 / random >= 3.0 (the relaxed constraints from Relax TF provider version requirements #121). required_version is ~> 1.9.
  • Kept unchanged:
    • Variable names. The Elastio Portal renders a module call from them.
    • The QUELL_* environment variable names. They are the agent binary's configuration contract.
    • The in-container ledger path /var/lib/quell. It is the image's own volume, owned by the non-root user, and the ephemeral (non-EFS) mode depends on it.
  • There is no moved {} block. Resource addresses are the same as before; only the AWS-side names changed.
  • Added examples/basic (with its lock file, as the other examples have), a names_and_image test, and a region assertion.

Checks run locally

  • terraform init -backend=false && terraform validate: valid, no warnings (AWS provider 6.66.0)
  • terraform test: 4 passed, 0 failed
  • terraform validate in examples/basic: valid
  • terraform-docs v0.19.0, then prettier --check .: clean
  • tflint --recursive (repo .tflint.hcl): clean
  • typos: clean
  • terraform fmt: clean on the new files

Task size (commit 387bdde)

  • New inputs task_cpu (default 256) and task_memory (default 512, MiB). The product renders these names. Validation accepts only pairs that Fargate runs on ARM64: 256 with 512, 1024 or 2048; 512 with 1024 to 4096; 1024 with 2048 to 8192; 2048 with 4096 to 16384. Memory above 512 MiB goes in steps of 1024.
  • GOMEMLIMIT is floor(task_memory * 0.8) MiB. The agent's budget for one open transaction is 30% of that, so the budget follows the size.
  • The default image is now agent 0.1.6 (elastio/database-monitoring-agent#2). That release judges a transaction too large to hold from its row counts instead of crashing, and reports the task memory that would have held it. It also finds its memory limit on Fargate, which 0.1.5 did not. Tag agent-v0.1.6 before this module is released.
  • README gains a Sizing section: the presets small 256/512, medium 512/1024, large 1024/2048 and xlarge 2048/4096; about how large a transaction each holds; the monthly cost in us-east-1 for ARM Fargate ($7.21 / $14.42 / $28.84 / $57.67); and "the Elastio UI tells you when to size up".
  • Tests: 14 pass. Each preset and one in-between size are planned, with their GOMEMLIMIT. Pairs Fargate does not run are refused at plan. The default image is checked as 0.1.6.
  • Checks: terraform fmt, validate (module and example), test, tflint --recursive, terraform-docs v0.19.0 plus prettier, and typos, all clean.

Release

After merge, someone with write access runs the release workflow (workflow_dispatch) on master. It publishes only modules whose name-version tag doesn't exist yet, so only this module is published.

Moves the Fargate module for the Elastio database monitoring agent
(elastio/blue-stack#17072) here from its old repository, as
aws-elastio-database-monitoring-agent 0.1.0. The image defaults to
public.ecr.aws/elastio/elastio-database-monitoring-agent:0.1.4 and every
resource name uses the elastio-dbmon prefix. The variable names are
unchanged because the Elastio Portal renders a module call from them.
Copilot AI lite review requested due to automatic review settings September 24, 2026 00:55
@anchoo2kewl anchoo2kewl self-assigned this Sep 24, 2026

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has reached their quota limit.

maksvet and others added 3 commits September 24, 2026 10:47
- Add an EFS file system policy: only the task role may mount, only
  through the access point, and only over TLS. Without it, any NFS client
  that reaches a mount target can mount the file system as root.
- Make the service depend on the IAM policies, secret versions, and the
  file system policy, so the first task does not start before it may read
  its secrets or mount the ledger, and destroy stops the task first.
- Validate that subnet_ids and security_group_ids are not empty, and that
  log_retention_days is a value CloudWatch Logs accepts.
Agent 0.1.5 reads ELASTIO_DBMON_* variables (QUELL_* still as a fallback)
and keeps its ledger under /var/lib/elastio-dbmon. The module sets the new
names, mounts the ledger there and names the path explicitly, so the EFS
access point's ledger is the same file as before. It also sets GOMEMLIMIT
to 80% of the task's memory: Go sets no memory limit from the container on
its own. The default image is 0.1.5, which this needs.
@anchoo2kewl

Copy link
Copy Markdown
Contributor Author

Pushed 98276af for agent 0.1.5 (elastio/database-monitoring-agent#1): the module now sets the ELASTIO_DBMON_* variables, mounts the ledger at /var/lib/elastio-dbmon and passes that path explicitly, so the EFS access point holds the same ledger file. It also sets GOMEMLIMIT=409MiB (80% of the 512 MiB task) and defaults the image to 0.1.5. The image needs 0.1.5 or later, since older agents read only QUELL_*. terraform test passes 5/5, and the README was regenerated with terraform-docs 0.19 and prettier.

maksvet and others added 4 commits September 24, 2026 12:02
EFS admits a client when either its identity policy or the file system
policy allows it, so an Allow alone does not keep out other roles with
EFS permissions. Add explicit Denies for every principal except the task
role and for every mount that does not use the access point.
EFS does not enforce aws:PrincipalArn for NFS clients, so the deny did not
restrict other principals and could refuse the agent itself. Keep only the
denies on the access point and TLS, which use keys EFS enforces, and state
that the EFS security group is the boundary against other roles with
their own EFS permissions.
The task was fixed at 0.25 vCPU and 512 MiB. What a larger task buys is
the largest transaction the agent holds in memory whole: agent 0.1.6
judges anything bigger from its row counts and reports an oversized
transaction with the smallest task memory that would have held it. So
the size is now two inputs, task_cpu (default 256) and task_memory
(default 512, MiB). They are validated as a pair Fargate runs on ARM64:
256 with 512, 1024 or 2048; 512 with 1024 to 4096; 1024 with 2048 to
8192; 2048 with 4096 to 16384; memory above 512 in steps of 1024.

GOMEMLIMIT follows task_memory at floor(task_memory * 0.8) MiB, so the
agent's transaction budget follows the size too. The default image is
0.1.6. The README has a Sizing section with the four sizes the product
offers, what each holds and costs in us-east-1, and how the Elastio UI
says when to size up. The tests plan each size and refuse pairs Fargate
does not run.
The comment said Fargate makes the bind mount writable for the container's
uid. It is writable when the image has a VOLUME at the ledger directory
owned by uid 65532, because ECS copies that VOLUME into the bind mount.
Also note that the task size is now configurable.

@maksvet maksvet left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Checked the 0.1.6 image (VOLUME and owner at /var/lib/elastio-dbmon) and ran this head in a test account: both ledger modes start and open the ledger, and the agent reads its limits from ECS metadata.

@anchoo2kewl
anchoo2kewl merged commit fdf264b into master Sep 24, 2026
22 checks passed
@anchoo2kewl
anchoo2kewl deleted the feat/database-monitoring-module branch September 24, 2026 17:36
greg-aligiannis pushed a commit to kelimira/support-teradata that referenced this pull request Nov 27, 2026
Prepares agent 0.1.5. Two things: nothing a customer sees says "quell"
any more, and the agent's memory use under large and steady traffic is
cut down. **Do not merge as a release.** `agent-v0.1.5` gets tagged
after review.

Terraform side: elastio/elastio-stack#123 (commit 98276af). It sets the
new variable names, mounts the ledger at `/var/lib/elastio-dbmon`, sets
`GOMEMLIMIT=409MiB`, and defaults the image to `0.1.5`.

## Customer-visible names
- Binary, `cmd/` dir, image entrypoint and OCI labels are now
`elastio-dbmon-agent`.
- Logs are one JSON object per line:
`{"time":…,"level":"INFO","msg":"…","agent":"elastio-dbmon-agent","version":"0.1.5"}`.
CloudWatch Logs Insights discovers these fields without a parse step.
`ELASTIO_DBMON_LOG_FORMAT=text` switches to logfmt.
- Config is read as `ELASTIO_DBMON_*` first and `QUELL_*` second. The
new name wins when both are set, errors name the new variables, and a
WARN line at start lists any old names still in use.
- The default ledger path is `/var/lib/elastio-dbmon/ledger`. If storage
is still mounted at `/var/lib/quell`, the agent uses it, so an
image-only upgrade keeps its ledger and hash key.
- **Unchanged:** the `X-Quell-Protocol` and `X-Quell-Agent` headers,
every JSON field, and the detector names (`quell.bulk_deletion` and the
others), because findings carry them over the wire. Internal packages
and docs keep "quell".

## Measurements (bench/run.sh: native arm64, `--cpus 0.25 --memory
512m`)
| | before (0.1.4) | after |
| --- | --- | --- |
| idle 90 s: RSS | 11.4 MiB | 13.1 MiB |
| idle: CPU of task | ~0.0% | 0.04% |
| idle: load on DB / server | 2 queries/min; 2 heartbeats, 1 retention,
1 snapshot per min | same |
| OLTP 200 txn/s × 2 min: peak RSS | 118 MiB | 102 MiB |
| OLTP: steady RSS (open window) | 97 MiB | 27 MiB |
| OLTP: CPU of task | 15.3% | 12.6% |
| OLTP: allocs per txn | 310 (24.9 KB) | 201 (17.6 KB) |
| OLTP: commit to judged | 65 s | 66 s |
| burst 250k DELETE + 150k INSERT: peak RSS | **503 MiB, OOM-killed** |
347 MiB, survived |
| burst: allocs per row | 84 (7.1 KB) | 64 (5.9 KB) |
| burst: commit to judged (DELETE / INSERT) | 66 s / 65 s, then killed
in review | 75 s / 67 s |
| image (compressed) / binary (arm64) | 3.84 MB / 7.67 MB | 3.91 MB /
7.86 MB |

Commit to judged includes the policy's 60 s idle close. At 1M + 500k
rows, 0.1.4 was OOM-killed 12 s after the DELETE committed. For that
size, see "Not done".

Profile evidence (`go run ./bench/burst`, 1M + 500k rows): peak live
heap went from 1.39 GB to 0.6 GB, and allocs per row from 94 to 43.
- Review's unbounded `Ledger.Since` was 752 MB of the 1.1 GB heap at
peak. It re-decoded the finding's window while the window it had just
judged was still held.
- `json.Decoder` copying its input was 192 MB.
- Tuple-decode and validation `Sprintf` was about 9% of CPU.

## Changes (one commit each)
1. Customer-visible rename (above).
2. **`GOMEMLIMIT` from the cgroup.** When unset, the agent sets it to
80% of the cgroup memory limit and logs GOMAXPROCS and the limit at
start. Go 1.26 already honours the CPU quota: GOMAXPROCS is 2 at 0.25
vCPU (verified in the startup log).
3. **Bench rig.** `bench/run.sh`, the `bench/stub` server, `bench/burst`
(in-process), and pprof/expvar only in `GOTAGS=dbmon_pprof` builds.
`-buildvcs=false` added to the Dockerfile.
4. **Format error text only on failure** in pgoutput tuple decode and
`Validate`. The messages are unchanged.
5. **Minimise each change as it's decoded.** A transaction is no longer
held with full rows until COMMIT. A test holds this to byte-identical
output against minimising at commit, over the captured stream.
6. **Streaming codecs.** `evidence.WriteLine` writes a record change by
change and is tested byte-identical to `MarshalLine`.
`evidence.UnmarshalCanonical` decodes indexed records without the
Decoder copy; recovery still parses strictly.
7. **Decode a window only to judge it, and bound review.**
- The ledger index now stores each record's commit time. The windower
holds only `Meta` (ordinal, time, size) while a window is open, decodes
it with `Range` at close, and releases it before review.
- Review reads only if the finding's evidence plus what followed is ≤
`Policy.MaxBytes`. Otherwise the finding is left standing and logged
once.
   - Sizes come from the index rather than re-marshalling.
8. Reuse the ledger's write buffer (a regression the rig caught in 6: 83
KB per txn).
9. Brief figures.

## Risk to the guarantees
- **Durability is unchanged.** Every `Accept` still fsyncs before it
returns, and any failed write or sync truncates back. fsync is not
batched.
- **Detection is unchanged:** the corpus, golden and published tests
pass, and `MaxBytes`, `MaxSpan` and `Idle` are untouched. One behaviour
change, deliberately in the safe direction: a finding whose evidence
plus what followed exceeds 64 MiB of canonical bytes is never
auto-explained by review. In 0.1.4 that review is what OOM-killed the
agent. Review only removes findings, so this errs toward keeping one. A
large ETL delete-and-reload now stays standing for a human to resolve.
- Reads of indexed records no longer re-check for unknown fields. Every
indexed record was parsed strictly at open or written by `Accept`.

## Not done (follow-ups)
- **A single transaction of about 600k+ rows still cannot fit in 512
MB.** A decoded change is about 300 B, mostly the Go map per key, so 1M
rows is about 300 MB decoded plus the read. On a crash-loop the slot
holds WAL on the customer's DB. Options:
  - a compact in-memory change representation
  - an explicit oversized-transaction policy (a product decision)
  - a module variable for 1–2 GB tasks
- `MaxBytes` (64 MiB) decodes to about 3–5× in memory, which is tight
for 512 MB. I left it alone because lowering it changes detection.
- Measured and deliberately not changed:
  - ledger fsync batching (the durability contract)
  - GOGC (GOMEMLIMIT covers the peak; lower GOGC costs CPU)
- the 1/min observe and snapshot interval (about 2 queries/min on the
DB)
- gzip (the shared-services receiver doesn't accept `Content-Encoding`)
  - HTTP keep-alive (already reused by the default transport)

`go test ./...` passes, including the live PostgreSQL tests and `-race`
on agent, windower, ledger, pgoutput and replication.

---------

Co-authored-by: Anshuman Biswas <[email protected]>
greg-aligiannis pushed a commit to kelimira/support-teradata that referenced this pull request Nov 27, 2026
…(#2)

Prepares agent 0.1.6. Refs elastio/blue-stack#17072. **Do not tag this
as a release on merge.** `agent-v0.1.6` gets tagged after review.

Terraform side: elastio/elastio-stack#123 (commit 387bdde) adds
`task_cpu` and `task_memory`, sets `GOMEMLIMIT` from them, and makes
0.1.6 the default image. Server side: shared-services#357 reads the
oversized finding in the shape below.

## The problem
With a single transaction of about 600k rows or more, the agent ran past
its 512 MiB task. Fargate restarted it, the slot redelivered the same
transaction, and the agent died again. All the while, the slot kept WAL
on the customer's database.

## What changes
- **A budget per open transaction.** `pgoutput.Stream` estimates each
change's in-memory size as it holds it.
`TestTheEstimateIsNotLowerThanTheHeap` measures that estimate at
1.03–1.10x the real heap, and never below it. Past **30% of the Go
memory limit** (`sizing.TransactionPercent`), the stream drops what it
holds and only counts the rest, per relation.
- Why 30% and not 50%: judging the window decodes the transaction again,
at 1.3–1.6x its held size (`bench/burst`). Meanwhile the stream may be
holding the next transaction. That worst case is about 2.6 budgets,
which is 78% of the Go limit at 30% and 130% at 50%.
- At 512 MiB the budget is 123 MiB, about 275k deleted or 170k inserted
rows.
- **What is persisted.** A counted transaction is stored as
`evidence.CountsOnly`. For each relation it has rows inserted, updated
and deleted, the number of truncates, and value bytes. It also has the
total, the held-size estimate, the budget and the memory limit. It has
no changes and no keys. A 1M-row DELETE becomes a **705-byte** ledger
record, so the next start reads nothing large.
- **Redelivery at another resolution.** A larger task can decode whole a
transaction that the smaller task counted. When either record is
counts-only, the ledger compares the transaction's identity, ref,
positions and commit time, read from a bounded prefix of the stored
record. It then keeps the record it already has. Otherwise, resizing the
task would stop the agent at the first redelivered transaction. A real
identity collision is still refused.
- **Judged from counts.**
- Proportion and declared limits still apply, so bulk deletion still
fires.
- Refill (`delete-then-refill`) and review
(`explained-by-later-activity`) are marked `applied: false`, with the
reason `transaction too large to hold in memory`.
- A counted relation is never treated as refilled, so counts can never
suppress a finding.
- Counted updates are unidentified, so rows rewritten is a floor. The
overwrite finding carries a not-applied `row-identity` check.
  - The copy detector needs only counts, so it is unaffected.
- **`quell.oversized_transaction` observation** (verdict `undecidable`,
severity `none`), one per window:
  ```json
  "oversized": {
    "rows_by_relation": {"public.bench_burst": 1000000},
    "bytes_seen": 5888896,
    "memory_limit_bytes": 536870912,
    "budget_bytes": 128849010,
    "recommended_task_memory_mib": 4096,
"transactions": [{"transaction_ref": "…", "commit_position":
"0/13A7A290", "commit_time": "…", "changes": 1000000, "bytes_seen": …,
"held_bytes": 468000000, "relations": […]}]
  }
  ```
- `recommended_task_memory_mib` is the smallest preset
(512/1024/2048/4096) whose budget holds the transaction with 25%
headroom. Above xlarge, it is the smallest multiple of 1024 that would.
  - The commit position and time are also in `observed`.
  - Every field is in the finding id.
- **Progress is unchanged.** The slot moves past the transaction once
the server accepts the window. Invariants 4 and 6 hold.
`TestAnOversizedTransactionIsJudgedFromCountsAndTheSlotMovesOn` checks
each step through the real decoder: durable, not acked while the server
refuses, a 705-byte ledger, accepted, then acked past, and the next
transaction is held whole.
- **Memory limit on Fargate (fix).** 0.1.5 read only the container's
cgroup, which reads `max` on Fargate, so it set no `GOMEMLIMIT` (seen on
UAT). `internal/limits` now tries these in order: the container cgroup,
the cgroups above it, then the ECS task metadata v4 `/task`
(`Limits.Memory`, `Limits.CPU`). `GOMAXPROCS` is set from the metadata
CPU (`max(1, ceil(cpu))`) only where Go could not see a quota. The first
log line names each source (`memory_limit_from`, `go_memory_limit_from`,
`gomaxprocs_from`). If no limit is found, the budget is that of a 512
MiB task.
- **Heartbeat** gains optional `memory_limit_bytes`, `memory_peak_bytes`
(VmHWM, resident memory) and `task_cpu_millis`. The server's
`decodeAgent` does not use `DisallowUnknownFields`, so this does **not**
need the server deployed first.

## Evidence
- `go vet`, `go test ./...` including the live PostgreSQL tests
(`QUELL_PG_DSN`, disposable), and `-race` on agent, windower, ledger,
pgoutput, replication and limits all pass.
- **The corpus replay output is byte-identical to master, and every
existing golden finding is unchanged.** Two new goldens:
`bulk-deletion-finding-from-counts`, and
`oversized-transaction-observation`.
- New tests:
  - counted vs held counts match
- under-budget transactions are byte-identical with and without a budget
  - counting is deterministic
  - the heap calibration
- ledger resolution rule, for both the file and memory implementations,
including a refused collision
  - features withhold claims for counted relations
  - `ben-12` counted is not suppressed
  - an ordinary window has no observation
- limits: cgroup v1/v2, the parent walk, the metadata endpoint via
httptest, a broken or unreachable endpoint
  - GOMAXPROCS and GOMEMLIMIT application
  - heartbeat fields present and absent

### Bench (`bench/run.sh burst`, 0.25 vCPU, 512 MiB, arm64; DELETE
1,000,000 rows, then INSERT 500,000)
| | 0.1.5 | 0.1.6 |
| --- | --- | --- |
| peak RSS | 468 MiB | 235 MiB |
| OOM-killed | **yes**, 42 s after the DELETE committed | no, running at
end |
| DELETE window | never judged | HIGH bulk_deletion + observation (446
MiB est. held, 123 MiB budget → 4096 MiB), 75 s after commit |
| INSERT window | never reached | observation (→ 2048 MiB), 69 s after
commit |
| ledger record | the whole transaction | 705 bytes |
| limits found | `cgroup` | `cgroup` (512 MiB, GOMEMLIMIT 409 MiB) |

Commit-to-judged includes the 60 s idle close. In-process (`go run
./bench/burst -memory N`), the same DELETE is held whole at 4096 MiB
(peak live heap 494 MiB) and counted at 512 MiB (peak live heap 161 MiB
vs 440 MiB unbudgeted). Bench containers were removed after each run.

## Notes
- **Rollback:** a 0.1.5 image refuses a ledger that holds a counts-only
record, because it parses strictly. That record is pruned once no
finding under review needs it, about an hour. Roll back after that, or
with an empty ledger.
- The reverse resize (a transaction held whole by a larger task, then a
smaller task) keeps the whole record. The smaller task decodes it when
it judges the window. This is stated in `docs/design/agent.md`.
- RulesetVersion and FeatureVersion are unchanged, because every
pre-existing input judges byte for byte as before.
- The stale-size false gap found on the bench is fixed in this PR; see
"Stale size samples" below.
- Docs are updated: `docs/design/agent.md` (new section), `evidence.md`,
`features.md`, `rules.md`, `ARCHITECTURE.md`, `api/agent/openapi.yaml`,
`bench/README.md`, and the brief's figures.

## Stale size samples (commit fae0cdf)
**Symptom.** On the bench rig, the INSERT window after the million-row
DELETE reported `bulk_deletion/observation_with_gap`, meaning "500,000
rows vanished with no event". Every one of those rows had left through
the stream, one window earlier. 0.1.5 does the same. It is a false
data-loss signal.

**Root cause.** The silent-collapse check (`enrich.Compare`, called from
`judge.Findings`) compares the before and after samples and credits only
this window's removals. The samples are `pg_class.reltuples`, which
changes only when the table is vacuumed or analysed.
- The DELETE window itself is judged correctly.
- The next window's before sample still reads 1,000,000.
- Autoanalyze runs during that window, so the after sample reads
500,000.
- The shrink was credited to nothing. An estimate describes the table
when PostgreSQL computed it, not when the agent read it.
- Checked against PostgreSQL 15: after `DELETE FROM t` (1,000 rows),
`reltuples` still reads 1000, and its estimate time is before the
DELETE.

**Fix.**
- The size sample now also returns when each estimate was made: the
latest of `last_vacuum`, `last_autovacuum`, `last_analyze` and
`last_autoanalyze`, from `pg_stat_user_tables`
(`sizes.Estimate.EstimatedAt`).
- The windower keeps a bounded log of what each judged window removed
per relation, and when (`windower/carried.go`). It covers a week, up to
10k entries. The agent keeps it beside the ledger as
`<ledger>.removals`, written atomically.
- Removals the stream carried after the before sample's estimate, in
earlier windows, are credited against the shrink
(`judge.Window.CarriedBefore`). A truncate counts as the whole estimate.
- Only the collapse accounting changes. Nothing about the window's own
destruction or proportion changes.
- The server's snapshot payload is unchanged (sizes only).

**Why this and not "mark the size unknown".** Marking the relation stale
and undecidable would hide a real partition drop that follows a stream
DELETE, until the next analyze. Crediting only what the stream carried,
each removal once, keeps the real loss visible with its own row count.

**Tests** (`internal/windower/stale_size_test.go`):
- The exact sequence: a big DELETE window, then an INSERT window with a
stale before sample. **It failed before the fix** with `500 rows ...
vanished`.
- The same sequence with estimate times known, for DELETE and for
TRUNCATE.
- **The real gap still fires:** 300 rows deleted through the stream,
then the partition holding the other 700 is dropped before an analyze.
The gap reports **699** rows (one row was inserted since), not 0 and not
999.
- A removal the estimate already reflects is not credited again: after a
re-analyze, the gap is still 699.
- The log survives a restart. Without it the false gap returns; that is
the negative control proving the log does the work.
- The sizes query parses estimate times, and a table never analysed has
no time.

**Unchanged:** the corpus replay output is byte-identical to master,
**and no golden finding changed**. `mal-16` still reports its gap,
because it is judged from fixture sizes with nothing carried. The full
suite passes, including the live PostgreSQL tests and `-race`.

**Bench after the fix** (same rig, 1M DELETE, then 500k INSERT): peak
RSS 243 MiB, not OOM-killed. The DELETE window is
`bulk_deletion/finding/high` plus the oversized observation. The INSERT
window is now **`bulk_deletion/no_destruction`**, where it was
`observation_with_gap`.

**Limits, stated in `docs/design/enrichment.md`:**
- It errs only toward crediting too much. A removal in a window that
straddles the estimate is credited whole. When the estimate time is
unknown, every logged removal is credited.
- On a first start with no log, the old behaviour applies to relations
not analysed since.

---------

Co-authored-by: Anshuman Biswas <[email protected]>
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.

3 participants