CodeSampleX

Пример

tracing 0.1.41: tracing::span::Attributes

Проверенный пример — cargo tracing 0.1.41: tracing::span::Attributes. Контракт выполнен на rust 1 · linux alpine/x64 · docker и пройден.

sha256:17383e862c2fd47be865765ea75978380b8fbc4bd6c8c51d082a30e1581f6d31

Эта сеть предлагает одно: образец, который собирается. Она запустила его в песочнице и сохранила подписанную квитанцию. Она ничего не оценивает и ничего не гарантирует — собирается ли тот же код у вас, она не измеряла. Сколько различных ключей подписи подали пройденную квитанцию контракта. Один — только автор; больше одного — значит, кто-то ещё тоже собрал. Ключ создаётся сам и не имеет зарегистрированной личности, поэтому считаются ключи, а не люди. MIT-0

Свидетельства выполнения

Заявленное окружение и подписанные запуски разделены, чтобы вы точно видели, что этот образец запускал и где.

Основа свидетельства
Подписанный контракт пройден
Квитанции проверки
1
Ключи подписи, собравшие его
1
Заявленная среда linux · musl x64 cargo

Среды запусков проверки

Окружение Контракт Этапы Запуск
rust 1 · linux alpine/x64 · docker ed25519:c1973797be207ac4 PASS compile:SKIPPED · contract:PASS · load:PASS · resolve:PASS
CONTAINER_RUN · cargo@1rust:1-alpine@sha256:a10e64dd139b…
2026-11-02

Кейс

HOW
Цель
verify tracing::span::Attributes in pkg:cargo/tracing@0.1.41
Пакеты
Символы
  • tracing::span::Attributes
Создан
2026-11-02T16:55:45Z

Контракт

  1. Attributes::metadata() returns the static Metadata for the span being created
  2. Attributes::record(&mut visitor) visits each initialized field value and skips field::Empty
  3. Attributes::is_root() returns true when created with parent: None and false for contextual or explicit child spans
  4. Attributes::is_contextual() returns true when parent is determined contextually and false when parent is None or explicit
  5. Attributes::parent() returns Some(&Id) for an explicit parent span and None for root or contextual spans
  6. Attributes::is_empty() returns true when no fields are defined on the span and false when fields are present
  7. Attributes::contains(&field) returns true for fields belonging to this span's FieldSet and false for fields from another span's FieldSet

Файлы

  • Cargo.lock
  • Cargo.toml
  • PROMPT.md
  • csx.json
  • spec.json
  • src/main.rs
  • test/contract.sh
  • tests/contract.rs

Скачать артефакт с исходным кодом (tar.gz)

Исходный код

Cargo.lock
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 4

[[package]]
name = "once_cell"
version = "1.21.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"

[[package]]
name = "pin-project-lite"
version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"

[[package]]
name = "proc-macro2"
version = "1.0.107"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"
dependencies = [
 "unicode-ident",
]

[[package]]
name = "quote"
version = "1.0.47"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001"
dependencies = [
 "proc-macro2",
]

[[package]]
name = "sample"
version = "0.1.0"
dependencies = [
 "tracing",
]

[[package]]
name = "syn"
version = "2.0.119"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
dependencies = [
 "proc-macro2",
 "quote",
 "unicode-ident",
]

[[package]]
name = "tracing"
version = "0.1.41"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "784e0ac535deb450455cbfa28a6f0df145ea1bb7ae51b821cf5e7927fdcfbdd0"
dependencies = [
 "pin-project-lite",
 "tracing-attributes",
 "tracing-core",
]

[[package]]
name = "tracing-attributes"
version = "0.1.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
dependencies = [
 "proc-macro2",
 "quote",
 "syn",
]

[[package]]
name = "tracing-core"
version = "0.1.36"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
dependencies = [
 "once_cell",
]

[[package]]
name = "unicode-ident"
version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"
Cargo.toml
[package]
name = "sample"
version = "0.1.0"
edition = "2021"

[dependencies]
tracing = "=0.1.41"
PROMPT.md
Clean-room public code sample — generation instructions

Write a brand-new, minimal, self-contained code sample in this clean-room directory.
Do not copy, paraphrase, or reference any existing project source. Work only from this spec.

A csx.json manifest scaffold already exists. Do not recreate it from memory. Preserve its case.goal, packages and symbols; fill its empty case.contract with exact assertions and correct its environment, commands and verifierAdapter for the files you generate.

Goal: verify tracing::span::Attributes in pkg:cargo/tracing@0.1.41
Kind: HOW

Use EXACTLY these public packages and versions:
  - pkg:cargo/tracing@0.1.41
Demonstrate these symbols/APIs:
  - tracing::span::Attributes

Rules:
  - One focused purpose; the smallest project that proves the goal.
  - Include a contract test (test/contract.*) that runs OFFLINE and exits 0 exactly when the goal behavior works.
  - Pin every dependency with a lockfile so resolution is reproducible.
  - No secrets, credentials, or tokens. No real URLs (only example.com or localhost). No absolute paths.
  - No personal names, emails, company names, or project identifiers of any kind.
  - No binaries and no generated output (node_modules, dist, target, venv, .git, .env).
  - Keep it under 200 files and 256KB packed.
csx.json
{"case":{"caseId":"case:sha256:7dbefc60aec8ed6d90287473f0d20142ff6fb571ee284bc1063dc2c048386ff9","contract":["Attributes::metadata() returns the static Metadata for the span being created","Attributes::record(\u0026mut visitor) visits each initialized field value and skips field::Empty","Attributes::is_root() returns true when created with parent: None and false for contextual or explicit child spans","Attributes::is_contextual() returns true when parent is determined contextually and false when parent is None or explicit","Attributes::parent() returns Some(\u0026Id) for an explicit parent span and None for root or contextual spans","Attributes::is_empty() returns true when no fields are defined on the span and false when fields are present","Attributes::contains(\u0026field) returns true for fields belonging to this span's FieldSet and false for fields from another span's FieldSet"],"goal":"verify tracing::span::Attributes in pkg:cargo/tracing@0.1.41","kind":"HOW","packages":["pkg:cargo/tracing@0.1.41"],"schemaVersion":1,"symbols":["tracing::span::Attributes"]},"contractCommand":["cargo","run","--offline"],"environment":{"arch":"x64","ecosystem":"cargo","libc":"musl","os":"linux","packageManager":"cargo","schemaVersion":1},"license":"MIT-0","packages":["pkg:cargo/tracing@0.1.41"],"schemaVersion":1,"subject":"pkg:cargo/tracing@0.1.41","symbols":["tracing::span::Attributes"],"verifierAdapter":"cargo@1"}
spec.json
{
  "schemaVersion": 1,
  "goal": "verify tracing::span::Attributes in pkg:cargo/tracing@0.1.41",
  "kind": "HOW",
  "packages": [
    "pkg:cargo/tracing@0.1.41"
  ],
  "symbols": [
    "tracing::span::Attributes"
  ]
}
src/main.rs
use std::fmt;
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::{Arc, Mutex};
use tracing::field::{Field, Visit};
use tracing::span::{Attributes, Id, Record};
use tracing::{Event, Metadata, Subscriber};

struct AttrVisitor {
    fields: Vec<(String, String)>,
}

impl Visit for AttrVisitor {
    fn record_debug(&mut self, field: &Field, value: &dyn fmt::Debug) {
        self.fields
            .push((field.name().to_string(), format!("{:?}", value)));
    }
}

#[derive(Clone, Default)]
struct CapturedSpan {
    name: String,
    is_root: bool,
    is_contextual: bool,
    parent_id: Option<u64>,
    is_empty: bool,
    contains_own_user: bool,
    contains_other_field: bool,
    fields: Vec<(String, String)>,
}

struct TestSubscriber {
    next_id: AtomicU64,
    captured: Arc<Mutex<Vec<CapturedSpan>>>,
    other_field: Arc<Mutex<Option<Field>>>,
}

impl Subscriber for TestSubscriber {
    fn enabled(&self, _metadata: &Metadata<'_>) -> bool {
        true
    }

    fn new_span(&self, attrs: &Attributes<'_>) -> Id {
        let mut visitor = AttrVisitor { fields: Vec::new() };
        attrs.record(&mut visitor);

        let metadata = attrs.metadata();
        let fields_set = metadata.fields();

        if let Some(f) = fields_set.field("other") {
            *self.other_field.lock().unwrap() = Some(f);
        }

        let contains_own_user = fields_set
            .field("user")
            .map(|f| attrs.contains(&f))
            .unwrap_or(false);

        let contains_other_field = self
            .other_field
            .lock()
            .unwrap()
            .as_ref()
            .map(|f| attrs.contains(f))
            .unwrap_or(false);

        let span_info = CapturedSpan {
            name: metadata.name().to_string(),
            is_root: attrs.is_root(),
            is_contextual: attrs.is_contextual(),
            parent_id: attrs.parent().map(|id| id.into_u64()),
            is_empty: attrs.is_empty(),
            contains_own_user,
            contains_other_field,
            fields: visitor.fields,
        };

        self.captured.lock().unwrap().push(span_info);
        let id = self.next_id.fetch_add(1, Ordering::Relaxed);
        Id::from_u64(id)
    }

    fn record(&self, _span: &Id, _values: &Record<'_>) {}
    fn record_follows_from(&self, _span: &Id, _follows: &Id) {}
    fn event(&self, _event: &Event<'_>) {}
    fn enter(&self, _span: &Id) {}
    fn exit(&self, _span: &Id) {}
}

fn main() {
    let captured = Arc::new(Mutex::new(Vec::new()));
    let subscriber = TestSubscriber {
        next_id: AtomicU64::new(1),
        captured: captured.clone(),
        other_field: Arc::new(Mutex::new(None)),
    };

    tracing::subscriber::with_default(subscriber, || {
        // Record another span first to capture a Field belonging to a different Callsite's FieldSet
        let _other = tracing::info_span!("other_op", other = 1);

        let root_span = tracing::info_span!(
            parent: None,
            "root_op",
            user = "alice",
            count = 42,
            deferred = tracing::field::Empty
        );
        let _guard = root_span.enter();

        let _contextual_span = tracing::info_span!("contextual_op");
        let _explicit_child = tracing::info_span!(parent: &root_span, "explicit_child");
    });

    let spans = captured.lock().unwrap();
    assert_eq!(spans.len(), 4);

    // 1. Root span with parent: None and populated attributes
    let root = &spans[1];
    assert_eq!(root.name, "root_op");
    assert!(root.is_root);
    assert!(!root.is_contextual);
    assert_eq!(root.parent_id, None);
    assert!(!root.is_empty);
    assert!(root.contains_own_user);
    assert!(!root.contains_other_field);
    // field::Empty is part of the span's FieldSet, but is skipped when recording values
    assert_eq!(
        root.fields,
        vec![
            ("user".to_string(), "\"alice\"".to_string()),
            ("count".to_string(), "42".to_string()),
        ]
    );

    // 2. Contextual span (inherits current span context, no fields provided)
    let contextual = &spans[2];
    assert_eq!(contextual.name, "contextual_op");
    assert!(!contextual.is_root);
    assert!(contextual.is_contextual);
    assert_eq!(contextual.parent_id, None);
    assert!(contextual.is_empty);
    assert!(contextual.fields.is_empty());

    // 3. Explicit parent span
    let explicit = &spans[3];
    assert_eq!(explicit.name, "explicit_child");
    assert!(!explicit.is_root);
    assert!(!explicit.is_contextual);
    assert_eq!(explicit.parent_id, Some(2));
    assert!(explicit.is_empty);
}
test/contract.sh
#!/bin/sh
set -e
cargo run --offline
tests/contract.rs
#[test]
fn contract() {
    let status = std::process::Command::new(env!("CARGO_BIN_EXE_sample"))
        .status()
        .expect("failed to execute binary");
    assert!(status.success());
}

Исходный сидер

аноним