Skip to content

go tools bootstrap#1

Merged
palazzem merged 6 commits into
masterfrom
palazzem/go-tools-bootstrap
Sep 9, 2016
Merged

go tools bootstrap#1
palazzem merged 6 commits into
masterfrom
palazzem/go-tools-bootstrap

Conversation

@palazzem

@palazzem palazzem commented Sep 8, 2016

Copy link
Copy Markdown
Contributor

What it does

Bootstrap the project with some initial stuff such as:

  • the glide package manager
  • a Rakefile to do almost anything
  • CircleCI integration
  • code coverage that is made available from CircleCI until we move to a public service such as Coveralls or CodeCov

@palazzem palazzem force-pushed the palazzem/go-tools-bootstrap branch from 58a7c0c to a0e70c7 Compare September 8, 2016 11:50
@palazzem palazzem force-pushed the palazzem/go-tools-bootstrap branch from a0e70c7 to 2d7232c Compare September 8, 2016 11:54
@LeoCavaille

Copy link
Copy Markdown
Member

Cool, getting started ! 👍

@palazzem

palazzem commented Sep 8, 2016

Copy link
Copy Markdown
Contributor Author

merging that so 👍

@palazzem palazzem merged commit 2d7232c into master Sep 9, 2016
@palazzem palazzem deleted the palazzem/go-tools-bootstrap branch September 9, 2016 13:34
dianashevchenko pushed a commit that referenced this pull request Apr 22, 2022
gh-worker-dd-mergequeue-cf854d Bot pushed a commit that referenced this pull request Jan 27, 2026
### What does this PR do?

This PR adds support for a `WithMaxQuerySize` method to the MongoDB package that enables truncation on the `mongodb.query` span tag.

I also ported this behavior to the new `mongo-driver.v2` package which supports the v2 release of the Mongo drivers.

Opening this PR here first for feedback from our team and then will open on the upstream repo.

The default is to not truncate query span tags, to avoid breaking changes. I'll ask in the upstream PR about whether we could truncate by default instead.

### Motivation

This reduces the memory footprint of tracing Mongo applications that write large documents.
gh-worker-dd-mergequeue-cf854d Bot pushed a commit that referenced this pull request May 19, 2026
…SpanOperation (#4766)

### What does this PR do?

Fixes a memory leak in AppSec when running under orchestrion, plus the related listener-cleanup asymmetry that compounds it. Two small, independent changes in two files:

1. **`ServiceEntrySpanOperation.Finish()` now calls `dyngo.FinishOperation`.**
   The op was pushed onto orchestrion's per-goroutine GLS stack by `StartAndRegisterOperation`, but its `Finish()` only flushed JSON tags and never invoked `dyngo.FinishOperation` — and `FinishOperation` is the **only** caller of `orchestrion.GLSPopValue`. On reused goroutines (HTTP keep-alive workers, gRPC handlers, worker pools), the parent op accumulated on the GLS stack one entry per request, retaining the span and the data-listener closures registered by `AppsecSpanTransport.OnServiceEntryStart`.

   The new call is **`defer`-ed**, not appended, so the GLS pop and `disable()` still run if a `TagSetter.SetTag` implementation panics during the tag-flush loop — otherwise the panic path would silently re-introduce the same leak.

2. **`operation.disable()` now also clears `dataBroadcaster.listeners`.**
   `disable()` cleared `eventRegister.listeners` but left its sibling `dataBroadcaster.listeners` populated — an asymmetry between two structurally identical listener maps, both populated by the same `addXListener` family. On ops that are properly finished, this only delays reclamation; combined with the GLS retention above, it amplifies the leak by keeping data-listener closures alive for every retained parent op.

### Motivation

Fixes #4763.

That issue covers fix (1) — the `ServiceEntrySpanOperation` GLS leak — and includes the same `MockGLS()`-based reproduction approach used in this PR's verification.

This PR adds fix (2) on top: the `dataBroadcaster` cleanup asymmetry was found while tracing the same retention path and is responsible for amplifying the heap impact of (1). The two are independent — (1) removes the leak on the orchestrion path; (2) removes the asymmetry that would amplify any future regression of the same shape.

### Root cause walkthrough

**Start path — both ops are registered:**

```
waf.StartContextOperation
 ├── trace.StartServiceEntrySpanOperation
 │     └── dyngo.StartAndRegisterOperation(entrySpanOp)   → GLS push #1 (parent)
 └── dyngo.StartAndRegisterOperation(contextOp)            → GLS push #2 (child)
```

**Finish path (before this PR) — only the child is unwound:**

```go
// internal/appsec/emitter/waf/context.go
func (op *ContextOperation) Finish() {
    dyngo.FinishOperation(op, ContextRes{})   // pops child from GLS
    op.ServiceEntrySpanOperation.Finish()      // flushes tags only — no FinishOperation
}
```

```go
// instrumentation/appsec/trace/service_entry_span.go (before)
func (op *ServiceEntrySpanOperation) Finish() {
    // ranges over op.jsonTags and calls span.SetTag — does NOT call dyngo.FinishOperation
}
```

Per request on the same goroutine, the GLS stack grows by one. `waf.ContextOperation.Finish()` is **unchanged** by this PR — its existing call sequence (pop child, then call parent's `Finish`) now correctly drives both lifecycles.

### Reproduction

Two reproduction tests are not bundled in the PR (kept the diff minimal at 2 files / +16 / -1), but both pass at HEAD and fail when the corresponding fix is reverted.

**Test 1 — GLS stack returns to baseline.**

A note for reviewers running this locally: `orchestrion.Enabled()` is flipped by the orchestrion source-transform tool at build time, not by `-tags orchestrion`. Under plain `go test`, `CtxWithValue` therefore skips the GLS push branch and `GLSStackDepth()` always returns 0 — a test relying on the build tag alone would pass vacuously. The repo's `orchestrion.MockGLS()` (`internal/orchestrion/mock_gls.go`) installs a real `contextStack` and flips `enabled=true` for the duration of the test, which is what #4763's reproduction also uses.

```go
package waf_test

import (
    "context"
    "testing"

    "github.com/DataDog/dd-trace-go/v2/instrumentation/appsec/trace"
    "github.com/DataDog/dd-trace-go/v2/internal/appsec/emitter/waf"
    "github.com/DataDog/dd-trace-go/v2/internal/orchestrion"
)

func TestGLSStackReturnsToBaseline(t *testing.T) {
    defer orchestrion.MockGLS()()

    ctx := context.Background()
    baseline := orchestrion.GLSStackDepth()

    const iterations = 100
    for i := 0; i < iterations; i++ {
        op, _ := waf.StartContextOperation(ctx, trace.NoopTagSetter{})
        op.Finish()
    }

    if got := orchestrion.GLSStackDepth(); got != baseline {
        t.Errorf("GLS leaked: started at %d, now %d after %d cycles", baseline, got, iterations)
    }
}
```

Observed when commit 1 of this PR is reverted: `GLS leaked: started at 0, now 100 after 100 cycles` — exactly +1 entry per request, matching the predicted leak rate. Stable at baseline with the fix applied.

**Test 2 — `disable()` must clear `dataBroadcaster`.**

```go
package dyngo

import "testing"

type repEvt struct{ val string }

func TestDataBroadcasterNotClearedOnDisable(t *testing.T) {
    op := &operation{}
    addDataListener(&op.dataBroadcaster, DataListener[repEvt](func(e repEvt) {}))
    addDataListener(&op.dataBroadcaster, DataListener[repEvt](func(e repEvt) {}))
    addDataListener(&op.dataBroadcaster, DataListener[repEvt](func(e repEvt) {}))

    op.disable()

    op.dataBroadcaster.mu.RLock()
    defer op.dataBroadcaster.mu.RUnlock()
    total := 0
    for _, ls := range op.dataBroadcaster.listeners {
        total += len(ls)
    }
    if total != 0 {
        t.Errorf("dataBroadcaster has %d listeners after disable(), want 0", total)
    }
}
```

Observed when commit 2 is reverted: `dataBroadcaster has 3 listeners after disable(), want 0`. Passes at HEAD.

Happy to include either or both tests in the PR if reviewers want — they were left out only to keep the diff narrowly scoped to the fix.

### Memory evidence

On a long-lived process with AppSec + orchestrion enabled and steady HTTP traffic:

- AppSec on, before fix: monotonic heap growth that scales with request count.
- AppSec off: flat heap.
- AppSec on, with both fixes: flat heap.

Heap-live-size profile retention path matches the GLS analysis:

```
dyngo.addDataListener
  ← dyngo.OnData
    ← AppsecSpanTransport.OnServiceEntryStart
      ← dyngo.StartAndRegisterOperation               (called once per HTTP request)
```

The path terminates in `StartAndRegisterOperation` with no matching `FinishOperation` — consistent with the GLS-pin hypothesis.

### Files touched

- `instrumentation/appsec/trace/service_entry_span.go` — +9 / -1
- `instrumentation/appsec/dyngo/operation.go` — +7 / -0

Total: 2 files, +16 / -1.

### Reviewer's Checklist

- [ ] Changed code has unit tests for its functionality at or near 100% coverage.
- [ ] [System-Tests](https://github.com/DataDog/system-tests/) covering this feature have been added and enabled with the va.b.c-dev version tag.
- [ ] There is a benchmark for any new code, or changes to existing code.
- [ ] If this interacts with the agent in a new way, a system test has been added.
- [x] New code is free of linting errors. You can check this by running `make lint` locally.
- [x] New code doesn't break existing tests. You can check this by running `make test` locally.
- [ ] Add an appropriate team label so this PR gets put in the right place for the release notes.
- [x] All generated files are up to date. You can check this by running `make generate` locally.
- [ ] Non-trivial go.mod changes, e.g. adding new modules, are reviewed by @DataDog/dd-trace-go-guild. Make sure all nested modules are up to date by running `make fix-modules` locally.


Co-authored-by: e-n-0 <flavien.darche@datadoghq.com>
Co-authored-by: dario.castane <dario.castane@datadoghq.com>
hannahkm pushed a commit that referenced this pull request May 22, 2026
…SpanOperation (#4766)

### What does this PR do?

Fixes a memory leak in AppSec when running under orchestrion, plus the related listener-cleanup asymmetry that compounds it. Two small, independent changes in two files:

1. **`ServiceEntrySpanOperation.Finish()` now calls `dyngo.FinishOperation`.**
   The op was pushed onto orchestrion's per-goroutine GLS stack by `StartAndRegisterOperation`, but its `Finish()` only flushed JSON tags and never invoked `dyngo.FinishOperation` — and `FinishOperation` is the **only** caller of `orchestrion.GLSPopValue`. On reused goroutines (HTTP keep-alive workers, gRPC handlers, worker pools), the parent op accumulated on the GLS stack one entry per request, retaining the span and the data-listener closures registered by `AppsecSpanTransport.OnServiceEntryStart`.

   The new call is **`defer`-ed**, not appended, so the GLS pop and `disable()` still run if a `TagSetter.SetTag` implementation panics during the tag-flush loop — otherwise the panic path would silently re-introduce the same leak.

2. **`operation.disable()` now also clears `dataBroadcaster.listeners`.**
   `disable()` cleared `eventRegister.listeners` but left its sibling `dataBroadcaster.listeners` populated — an asymmetry between two structurally identical listener maps, both populated by the same `addXListener` family. On ops that are properly finished, this only delays reclamation; combined with the GLS retention above, it amplifies the leak by keeping data-listener closures alive for every retained parent op.

### Motivation

Fixes #4763.

That issue covers fix (1) — the `ServiceEntrySpanOperation` GLS leak — and includes the same `MockGLS()`-based reproduction approach used in this PR's verification.

This PR adds fix (2) on top: the `dataBroadcaster` cleanup asymmetry was found while tracing the same retention path and is responsible for amplifying the heap impact of (1). The two are independent — (1) removes the leak on the orchestrion path; (2) removes the asymmetry that would amplify any future regression of the same shape.

### Root cause walkthrough

**Start path — both ops are registered:**

```
waf.StartContextOperation
 ├── trace.StartServiceEntrySpanOperation
 │     └── dyngo.StartAndRegisterOperation(entrySpanOp)   → GLS push #1 (parent)
 └── dyngo.StartAndRegisterOperation(contextOp)            → GLS push #2 (child)
```

**Finish path (before this PR) — only the child is unwound:**

```go
// internal/appsec/emitter/waf/context.go
func (op *ContextOperation) Finish() {
    dyngo.FinishOperation(op, ContextRes{})   // pops child from GLS
    op.ServiceEntrySpanOperation.Finish()      // flushes tags only — no FinishOperation
}
```

```go
// instrumentation/appsec/trace/service_entry_span.go (before)
func (op *ServiceEntrySpanOperation) Finish() {
    // ranges over op.jsonTags and calls span.SetTag — does NOT call dyngo.FinishOperation
}
```

Per request on the same goroutine, the GLS stack grows by one. `waf.ContextOperation.Finish()` is **unchanged** by this PR — its existing call sequence (pop child, then call parent's `Finish`) now correctly drives both lifecycles.

### Reproduction

Two reproduction tests are not bundled in the PR (kept the diff minimal at 2 files / +16 / -1), but both pass at HEAD and fail when the corresponding fix is reverted.

**Test 1 — GLS stack returns to baseline.**

A note for reviewers running this locally: `orchestrion.Enabled()` is flipped by the orchestrion source-transform tool at build time, not by `-tags orchestrion`. Under plain `go test`, `CtxWithValue` therefore skips the GLS push branch and `GLSStackDepth()` always returns 0 — a test relying on the build tag alone would pass vacuously. The repo's `orchestrion.MockGLS()` (`internal/orchestrion/mock_gls.go`) installs a real `contextStack` and flips `enabled=true` for the duration of the test, which is what #4763's reproduction also uses.

```go
package waf_test

import (
    "context"
    "testing"

    "github.com/DataDog/dd-trace-go/v2/instrumentation/appsec/trace"
    "github.com/DataDog/dd-trace-go/v2/internal/appsec/emitter/waf"
    "github.com/DataDog/dd-trace-go/v2/internal/orchestrion"
)

func TestGLSStackReturnsToBaseline(t *testing.T) {
    defer orchestrion.MockGLS()()

    ctx := context.Background()
    baseline := orchestrion.GLSStackDepth()

    const iterations = 100
    for i := 0; i < iterations; i++ {
        op, _ := waf.StartContextOperation(ctx, trace.NoopTagSetter{})
        op.Finish()
    }

    if got := orchestrion.GLSStackDepth(); got != baseline {
        t.Errorf("GLS leaked: started at %d, now %d after %d cycles", baseline, got, iterations)
    }
}
```

Observed when commit 1 of this PR is reverted: `GLS leaked: started at 0, now 100 after 100 cycles` — exactly +1 entry per request, matching the predicted leak rate. Stable at baseline with the fix applied.

**Test 2 — `disable()` must clear `dataBroadcaster`.**

```go
package dyngo

import "testing"

type repEvt struct{ val string }

func TestDataBroadcasterNotClearedOnDisable(t *testing.T) {
    op := &operation{}
    addDataListener(&op.dataBroadcaster, DataListener[repEvt](func(e repEvt) {}))
    addDataListener(&op.dataBroadcaster, DataListener[repEvt](func(e repEvt) {}))
    addDataListener(&op.dataBroadcaster, DataListener[repEvt](func(e repEvt) {}))

    op.disable()

    op.dataBroadcaster.mu.RLock()
    defer op.dataBroadcaster.mu.RUnlock()
    total := 0
    for _, ls := range op.dataBroadcaster.listeners {
        total += len(ls)
    }
    if total != 0 {
        t.Errorf("dataBroadcaster has %d listeners after disable(), want 0", total)
    }
}
```

Observed when commit 2 is reverted: `dataBroadcaster has 3 listeners after disable(), want 0`. Passes at HEAD.

Happy to include either or both tests in the PR if reviewers want — they were left out only to keep the diff narrowly scoped to the fix.

### Memory evidence

On a long-lived process with AppSec + orchestrion enabled and steady HTTP traffic:

- AppSec on, before fix: monotonic heap growth that scales with request count.
- AppSec off: flat heap.
- AppSec on, with both fixes: flat heap.

Heap-live-size profile retention path matches the GLS analysis:

```
dyngo.addDataListener
  ← dyngo.OnData
    ← AppsecSpanTransport.OnServiceEntryStart
      ← dyngo.StartAndRegisterOperation               (called once per HTTP request)
```

The path terminates in `StartAndRegisterOperation` with no matching `FinishOperation` — consistent with the GLS-pin hypothesis.

### Files touched

- `instrumentation/appsec/trace/service_entry_span.go` — +9 / -1
- `instrumentation/appsec/dyngo/operation.go` — +7 / -0

Total: 2 files, +16 / -1.

### Reviewer's Checklist

- [ ] Changed code has unit tests for its functionality at or near 100% coverage.
- [ ] [System-Tests](https://github.com/DataDog/system-tests/) covering this feature have been added and enabled with the va.b.c-dev version tag.
- [ ] There is a benchmark for any new code, or changes to existing code.
- [ ] If this interacts with the agent in a new way, a system test has been added.
- [x] New code is free of linting errors. You can check this by running `make lint` locally.
- [x] New code doesn't break existing tests. You can check this by running `make test` locally.
- [ ] Add an appropriate team label so this PR gets put in the right place for the release notes.
- [x] All generated files are up to date. You can check this by running `make generate` locally.
- [ ] Non-trivial go.mod changes, e.g. adding new modules, are reviewed by @DataDog/dd-trace-go-guild. Make sure all nested modules are up to date by running `make fix-modules` locally.


Co-authored-by: e-n-0 <flavien.darche@datadoghq.com>
Co-authored-by: dario.castane <dario.castane@datadoghq.com>
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