Bazel Visibility Rule Application Scope
Visibility enforcement in Bazel is not uniform across all rule types. The following confirmed facts and known exceptions address the question directly.
Confirmed facts
- Visibility is enforced at analysis time through the
visibility attribute on rule targets. //visibility:private restricts dependents to the defining package, while //visibility:public allows unrestricted access. - Dependencies declared via
data or exports_files are generally exempt from visibility checks, which can inadvertently expose implementation details marked as private.
Rule-type nuances
Starlark-defined rules and macros respect visibility on explicitly declared dependencies. However, macro expansion using glob or collections may dynamically resolve targets across package boundaries, bypassing static visibility enforcement.
Test target behavior
Test targets (_test) traditionally have relaxed visibility to allow testing production code. Bazel 6+ introduces the test_visibility attribute and stricter enforcement, but the actual behavior still depends on the rule type and configuration.
Version assumption
Visibility enforcement for test targets and macro-expanded dependencies varies across Bazel releases. Explicitly setting test_visibility and test_deps is required to enforce expected restrictions in Bazel 6 and later.
Verification
Run the following scoped commands to check enforcement in your workspace:
bazel query 'deps(//mypackage:private_target)'
Inspect the visibility attribute in each BUILD file and confirm that //visibility:private appears on targets that should not be cross-package dependable.
Execute bazel build //mypackage:private_target from a different package; a visibility violation error confirms enforcement.
Missing diagnostic detail: Which Bazel version are you using? Visibility behavior for test targets and macro-expanded dependencies differs between releases, and the recommendation may change based on the version.